diff --git a/src/ios/asyncgate_iOS/.DS_Store b/src/ios/asyncgate_iOS/.DS_Store new file mode 100644 index 00000000..7d1acf9e Binary files /dev/null and b/src/ios/asyncgate_iOS/.DS_Store differ diff --git a/src/ios/asyncgate_iOS/.gitignore b/src/ios/asyncgate_iOS/.gitignore new file mode 100644 index 00000000..6175934e --- /dev/null +++ b/src/ios/asyncgate_iOS/.gitignore @@ -0,0 +1,113 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode,cocoapods +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode,cocoapods + +### CocoaPods ### +## CocoaPods GitIgnore Template + +# CocoaPods - Only use to conserve bandwidth / Save time on Pushing +# - Also handy if you have a large number of dependant pods +# - AS PER https://guides.cocoapods.org/using/using-cocoapods.html NEVER IGNORE THE LOCK FILE +Pods/ + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Accio dependency management +Dependencies/ +.accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### + +## Xcode 8 and earlier + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcodeproj/project.xcworkspace/ +!*.xcworkspace/contents.xcworkspacedata +*.xcconfig +/*.gcno +**/xcshareddata/WorkspaceSettings.xcsettings +.DS_Store +*.xcuserstate +*.xcconfig.xcconfig + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode,cocoapods diff --git a/src/ios/asyncgate_iOS/Podfile b/src/ios/asyncgate_iOS/Podfile new file mode 100644 index 00000000..24a56128 --- /dev/null +++ b/src/ios/asyncgate_iOS/Podfile @@ -0,0 +1,21 @@ +# Uncomment the next line to define a global platform for your project +platform :ios, '17.6' + +target 'asyncgate_iOS' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for asyncgate_iOS + pod 'Alamofire', '~> 5.5' + pod 'KeychainAccess' + pod 'Starscream', '~> 4.0.6' + target 'asyncgate_iOSTests' do + inherit! :search_paths + # Pods for testing + end + + target 'asyncgate_iOSUITests' do + # Pods for UI testing + end + +end diff --git a/src/ios/asyncgate_iOS/Podfile.lock b/src/ios/asyncgate_iOS/Podfile.lock new file mode 100644 index 00000000..8e3bfa19 --- /dev/null +++ b/src/ios/asyncgate_iOS/Podfile.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (5.10.2) + - KeychainAccess (4.2.2) + - Starscream (4.0.8) + +DEPENDENCIES: + - Alamofire (~> 5.5) + - KeychainAccess + - Starscream (~> 4.0.6) + +SPEC REPOS: + trunk: + - Alamofire + - KeychainAccess + - Starscream + +SPEC CHECKSUMS: + Alamofire: 7193b3b92c74a07f85569e1a6c4f4237291e7496 + KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51 + Starscream: 19b5533ddb925208db698f0ac508a100b884a1b9 + +PODFILE CHECKSUM: d5b33e6604d89dac19a1810a1f3fcea6c1ea8bef + +COCOAPODS: 1.16.2 diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/LICENSE b/src/ios/asyncgate_iOS/Pods/Alamofire/LICENSE new file mode 100644 index 00000000..cae030a0 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/README.md b/src/ios/asyncgate_iOS/Pods/Alamofire/README.md new file mode 100644 index 00000000..72ece56d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/README.md @@ -0,0 +1,269 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) + +[![Swift](https://img.shields.io/badge/Swift-5.9_5.10_6.0-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.9_5.10_6.0-Orange?style=flat-square) +[![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_visionOS_Linux_Windows_Android-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_vision_OS_Linux_Windows_Android-Green?style=flat-square) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage) +[![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) +[![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Contributing](#contributing) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) + - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor) + - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers) + - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine) + - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6. +- [x] Combine Support +- [x] URL / JSON Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with `URLCredential` +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) + +## Write Requests Fast! + +Alamofire's compact syntax and extensive feature set allow requests with powerful features like automatic retry to be written in just a few lines of code. + +```swift +// Automatic String to URL conversion, Swift concurrency support, and automatic retry. +let response = await AF.request("https://httpbin.org/get", interceptor: .retryPolicy) + // Automatic HTTP Basic Auth. + .authenticate(username: "user", password: "pass") + // Caching customization. + .cacheResponse(using: .cache) + // Redirect customization. + .redirect(using: .follow) + // Validate response code and Content-Type. + .validate() + // Produce a cURL command for the request. + .cURLDescription { description in + print(description) + } + // Automatic Decodable support with background parsing. + .serializingDecodable(DecodableType.self) + // Await the full response with metrics and a parsed body. + .response +// Detailed response description for easy debugging. +debugPrint(response) +``` + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +| Platform | Minimum Swift Version | Installation | Status | +| ---------------------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------ | +| iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.9 / Xcode 15.0 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested | +| Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | +| Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | +| Android | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | + +#### Known Issues on Linux and Windows + +Alamofire builds on Linux, Windows, and Android but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include: + +- `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support. +- Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges. +- Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called. +- `URLSessionTaskMetrics` are never gathered. +- `WebSocketRequest` is not available. + +Due to these issues, Alamofire is unsupported on Linux, Windows, and Android. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org). + +## Migration Guides + +- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! + +## Installation + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift` or the Package list in Xcode. + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.10.0")) +] +``` + +Normally you'll want to depend on the `Alamofire` target: + +```swift +.product(name: "Alamofire", package: "Alamofire") +``` + +But if you want to force Alamofire to be dynamically linked (do not do this unless you're sure you need it), you can depend on the `AlamofireDynamic` target: + +```swift +.product(name: "AlamofireDynamic", package: "Alamofire") +``` + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'Alamofire' +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for macOS. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +## Contributing + +Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. + - (Resolved): 9/1/17 in Xcode 9 beta 6. +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + - (Resolved): Just add `CFNetwork` to your linked frameworks. +- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS + - (Resolved): Metrics now collected on watchOS 7+. + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Sponsorship + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. +Sponsoring the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated. + +[Sponsor Alamofire](https://github.com/sponsors/Alamofire) + +## Supporters + +[MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini. + +![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png) + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 00000000..56f5e6a7 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,43 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2021 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation +#if canImport(FoundationNetworking) +@_exported import FoundationNetworking +#endif + +// Enforce minimum Swift version for all platforms and build systems. +#if swift(<5.9.0) +#error("Alamofire doesn't support Swift versions below 5.9.") +#endif + +/// Reference to `Session.default` for quick bootstrapping and examples. +public let AF = Session.default + +/// Namespace for informational Alamofire values. +public enum AFInfo { + /// Current Alamofire version. + public static let version = "5.10.2" +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/AFError.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/AFError.swift new file mode 100644 index 00000000..ea678525 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/AFError.swift @@ -0,0 +1,874 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if canImport(Security) +@preconcurrency import Security +#endif + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +public enum AFError: Error, Sendable { + /// The underlying reason the `.multipartEncodingFailed` error occurred. + public enum MultipartEncodingFailureReason: Sendable { + /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. + case bodyPartURLInvalid(url: URL) + /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension`. + case bodyPartFilenameInvalid(in: URL) + /// The file at the `fileURL` provided was not reachable. + case bodyPartFileNotReachable(at: URL) + /// Attempting to check the reachability of the `fileURL` provided threw an error. + case bodyPartFileNotReachableWithError(atURL: URL, error: any Error) + /// The file at the `fileURL` provided is actually a directory. + case bodyPartFileIsDirectory(at: URL) + /// The size of the file at the `fileURL` provided was not returned by the system. + case bodyPartFileSizeNotAvailable(at: URL) + /// The attempt to find the size of the file at the `fileURL` provided threw an error. + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: any Error) + /// An `InputStream` could not be created for the provided `fileURL`. + case bodyPartInputStreamCreationFailed(for: URL) + /// An `OutputStream` could not be created when attempting to write the encoded data to disk. + case outputStreamCreationFailed(for: URL) + /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. + case outputStreamFileAlreadyExists(at: URL) + /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. + case outputStreamURLInvalid(url: URL) + /// The attempt to write the encoded body data to disk failed with an underlying error. + case outputStreamWriteFailed(error: any Error) + /// The attempt to read an encoded body part `InputStream` failed with underlying system error. + case inputStreamReadFailed(error: any Error) + } + + /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be + /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case. + public struct UnexpectedInputStreamLength: Error { + /// The expected byte count to read. + public var bytesExpected: UInt64 + /// The actual byte count read. + public var bytesRead: UInt64 + } + + /// The underlying reason the `.parameterEncodingFailed` error occurred. + public enum ParameterEncodingFailureReason: Sendable { + /// The `URLRequest` did not have a `URL` to encode. + case missingURL + /// JSON serialization failed with an underlying system error during the encoding process. + case jsonEncodingFailed(error: any Error) + /// Custom parameter encoding failed due to the associated `Error`. + case customEncodingFailed(error: any Error) + } + + /// The underlying reason the `.parameterEncoderFailed` error occurred. + public enum ParameterEncoderFailureReason: Sendable { + /// Possible missing components. + public enum RequiredComponent: Sendable { + /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. + case url + /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. + case httpMethod(rawValue: String) + } + + /// A `RequiredComponent` was missing during encoding. + case missingRequiredComponent(RequiredComponent) + /// The underlying encoder failed with the associated error. + case encoderFailed(error: any Error) + } + + /// The underlying reason the `.responseValidationFailed` error occurred. + public enum ResponseValidationFailureReason: Sendable { + /// The data file containing the server response did not exist. + case dataFileNil + /// The data file containing the server response at the associated `URL` could not be read. + case dataFileReadFailed(at: URL) + /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a + /// wildcard type. + case missingContentType(acceptableContentTypes: [String]) + /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + /// The response status code was not acceptable. + case unacceptableStatusCode(code: Int) + /// Custom response validation failed due to the associated `Error`. + case customValidationFailed(error: any Error) + } + + /// The underlying reason the response serialization error occurred. + public enum ResponseSerializationFailureReason: Sendable { + /// The server response contained no data or the data was zero length. + case inputDataNilOrZeroLength + /// The file containing the server response did not exist. + case inputFileNil + /// The file containing the server response could not be read from the associated `URL`. + case inputFileReadFailed(at: URL) + /// String serialization failed using the provided `String.Encoding`. + case stringSerializationFailed(encoding: String.Encoding) + /// JSON serialization failed with an underlying system error. + case jsonSerializationFailed(error: any Error) + /// A `DataDecoder` failed to decode the response due to the associated `Error`. + case decodingFailed(error: any Error) + /// A custom response serializer failed due to the associated `Error`. + case customSerializationFailed(error: any Error) + /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. + case invalidEmptyResponse(type: String) + } + + #if canImport(Security) + /// Underlying reason a server trust evaluation error occurred. + public enum ServerTrustFailureReason: Sendable { + /// The output of a server trust evaluation. + public struct Output: Sendable { + /// The host for which the evaluation was performed. + public let host: String + /// The `SecTrust` value which was evaluated. + public let trust: SecTrust + /// The `OSStatus` of evaluation operation. + public let status: OSStatus + /// The result of the evaluation operation. + public let result: SecTrustResultType + + /// Creates an `Output` value from the provided values. + init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { + self.host = host + self.trust = trust + self.status = status + self.result = result + } + } + + /// No `ServerTrustEvaluator` was found for the associated host. + case noRequiredEvaluator(host: String) + /// No certificates were found with which to perform the trust evaluation. + case noCertificatesFound + /// No public keys were found with which to perform the trust evaluation. + case noPublicKeysFound + /// During evaluation, application of the associated `SecPolicy` failed. + case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) + /// During evaluation, setting the associated anchor certificates failed. + case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) + /// During evaluation, creation of the revocation policy failed. + case revocationPolicyCreationFailed + /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. + case trustEvaluationFailed(error: (any Error)?) + /// Default evaluation failed with the associated `Output`. + case defaultEvaluationFailed(output: Output) + /// Host validation failed with the associated `Output`. + case hostValidationFailed(output: Output) + /// Revocation check failed with the associated `Output` and options. + case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) + /// Certificate pinning failed. + case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) + /// Public key pinning failed. + case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) + /// Custom server trust evaluation failed due to the associated `Error`. + case customEvaluationFailed(error: any Error) + } + #endif + + /// The underlying reason the `.urlRequestValidationFailed` error occurred. + public enum URLRequestValidationFailureReason: Sendable { + /// URLRequest with GET method had body data. + case bodyDataInGETRequest(Data) + } + + /// `UploadableConvertible` threw an error in `createUploadable()`. + case createUploadableFailed(error: any Error) + /// `URLRequestConvertible` threw an error in `asURLRequest()`. + case createURLRequestFailed(error: any Error) + /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. + case downloadedFileMoveFailed(error: any Error, source: URL, destination: URL) + /// `Request` was explicitly cancelled. + case explicitlyCancelled + /// `URLConvertible` type failed to create a valid `URL`. + case invalidURL(url: any URLConvertible) + /// Multipart form encoding failed. + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + /// `ParameterEncoding` threw an error during the encoding process. + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + /// `ParameterEncoder` threw an error while running the encoder. + case parameterEncoderFailed(reason: ParameterEncoderFailureReason) + /// `RequestAdapter` threw an error during adaptation. + case requestAdaptationFailed(error: any Error) + /// `RequestRetrier` threw an error during the request retry process. + case requestRetryFailed(retryError: any Error, originalError: any Error) + /// Response validation failed. + case responseValidationFailed(reason: ResponseValidationFailureReason) + /// Response serialization failed. + case responseSerializationFailed(reason: ResponseSerializationFailureReason) + #if canImport(Security) + /// `ServerTrustEvaluating` instance threw an error during trust evaluation. + case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) + #endif + /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. + case sessionDeinitialized + /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. + case sessionInvalidated(error: (any Error)?) + /// `URLSessionTask` completed with error. + case sessionTaskFailed(error: any Error) + /// `URLRequest` failed validation. + case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) +} + +extension Error { + /// Returns the instance cast as an `AFError`. + public var asAFError: AFError? { + self as? AFError + } + + /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. + public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { + guard let afError = self as? AFError else { + fatalError(message(), file: file, line: line) + } + return afError + } + + /// Casts the instance as `AFError` or returns `defaultAFError` + func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { + self as? AFError ?? defaultAFError() + } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the instance is `.sessionDeinitialized`. + public var isSessionDeinitializedError: Bool { + if case .sessionDeinitialized = self { return true } + return false + } + + /// Returns whether the instance is `.sessionInvalidated`. + public var isSessionInvalidatedError: Bool { + if case .sessionInvalidated = self { return true } + return false + } + + /// Returns whether the instance is `.explicitlyCancelled`. + public var isExplicitlyCancelledError: Bool { + if case .explicitlyCancelled = self { return true } + return false + } + + /// Returns whether the instance is `.invalidURL`. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncoderError: Bool { + if case .parameterEncoderFailed = self { return true } + return false + } + + /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError` + /// properties will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestAdaptationError: Bool { + if case .requestAdaptationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } + + #if canImport(Security) + /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isServerTrustEvaluationError: Bool { + if case .serverTrustEvaluationFailed = self { return true } + return false + } + #endif + + /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestRetryError: Bool { + if case .requestRetryFailed = self { return true } + return false + } + + /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateUploadableError: Bool { + if case .createUploadableFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateURLRequestError: Bool { + if case .createURLRequestFailed = self { return true } + return false + } + + /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will + /// contain the associated values. + public var isDownloadedFileMoveError: Bool { + if case .downloadedFileMoveFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isSessionTaskError: Bool { + if case .sessionTaskFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: (any URLConvertible)? { + guard case let .invalidURL(url) = self else { return nil } + return url + } + + /// The `URL` associated with the error. + public var url: URL? { + guard case let .multipartEncodingFailed(reason) = self else { return nil } + return reason.url + } + + /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, + /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, + /// `.responseSerializationFailed`, `.requestRetryFailed` errors. + public var underlyingError: (any Error)? { + switch self { + case let .multipartEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncoderFailed(reason): + return reason.underlyingError + case let .requestAdaptationFailed(error): + return error + case let .requestRetryFailed(retryError, _): + return retryError + case let .responseValidationFailed(reason): + return reason.underlyingError + case let .responseSerializationFailed(reason): + return reason.underlyingError + #if canImport(Security) + case let .serverTrustEvaluationFailed(reason): + return reason.underlyingError + #endif + case let .sessionInvalidated(error): + return error + case let .createUploadableFailed(error): + return error + case let .createURLRequestFailed(error): + return error + case let .downloadedFileMoveFailed(error, _, _): + return error + case let .sessionTaskFailed(error): + return error + case .explicitlyCancelled, + .invalidURL, + .sessionDeinitialized, + .urlRequestValidationFailed: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.acceptableContentTypes + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseContentType + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseCode + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + guard case let .responseSerializationFailed(reason) = self else { return nil } + return reason.failedStringEncoding + } + + /// The `source` URL of a `.downloadedFileMoveFailed` error. + public var sourceURL: URL? { + guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } + return source + } + + /// The `destination` URL of a `.downloadedFileMoveFailed` error. + public var destinationURL: URL? { + guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } + return destination + } + + #if canImport(Security) + /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s. + public var downloadResumeData: Data? { + (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data + } + #endif +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: (any Error)? { + switch self { + case let .jsonEncodingFailed(error), + let .customEncodingFailed(error): + error + case .missingURL: + nil + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var underlyingError: (any Error)? { + switch self { + case let .encoderFailed(error): + error + case .missingRequiredComponent: + nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case let .bodyPartURLInvalid(url), + let .bodyPartFilenameInvalid(url), + let .bodyPartFileNotReachable(url), + let .bodyPartFileIsDirectory(url), + let .bodyPartFileSizeNotAvailable(url), + let .bodyPartInputStreamCreationFailed(url), + let .outputStreamCreationFailed(url), + let .outputStreamFileAlreadyExists(url), + let .outputStreamURLInvalid(url), + let .bodyPartFileNotReachableWithError(url, _), + let .bodyPartFileSizeQueryFailedWithError(url, _): + url + case .outputStreamWriteFailed, + .inputStreamReadFailed: + nil + } + } + + var underlyingError: (any Error)? { + switch self { + case let .bodyPartFileNotReachableWithError(_, error), + let .bodyPartFileSizeQueryFailedWithError(_, error), + let .outputStreamWriteFailed(error), + let .inputStreamReadFailed(error): + error + case .bodyPartURLInvalid, + .bodyPartFilenameInvalid, + .bodyPartFileNotReachable, + .bodyPartFileIsDirectory, + .bodyPartFileSizeNotAvailable, + .bodyPartInputStreamCreationFailed, + .outputStreamCreationFailed, + .outputStreamFileAlreadyExists, + .outputStreamURLInvalid: + nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case let .missingContentType(types), + let .unacceptableContentType(types, _): + types + case .dataFileNil, + .dataFileReadFailed, + .unacceptableStatusCode, + .customValidationFailed: + nil + } + } + + var responseContentType: String? { + switch self { + case let .unacceptableContentType(_, responseType): + responseType + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableStatusCode, + .customValidationFailed: + nil + } + } + + var responseCode: Int? { + switch self { + case let .unacceptableStatusCode(code): + code + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .customValidationFailed: + nil + } + } + + var underlyingError: (any Error)? { + switch self { + case let .customValidationFailed(error): + error + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .unacceptableStatusCode: + nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case let .stringSerializationFailed(encoding): + encoding + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed(_), + .jsonSerializationFailed(_), + .decodingFailed(_), + .customSerializationFailed(_), + .invalidEmptyResponse: + nil + } + } + + var underlyingError: (any Error)? { + switch self { + case let .jsonSerializationFailed(error), + let .decodingFailed(error), + let .customSerializationFailed(error): + error + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed, + .stringSerializationFailed, + .invalidEmptyResponse: + nil + } + } +} + +#if canImport(Security) +extension AFError.ServerTrustFailureReason { + var output: AFError.ServerTrustFailureReason.Output? { + switch self { + case let .defaultEvaluationFailed(output), + let .hostValidationFailed(output), + let .revocationCheckFailed(output, _): + output + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .trustEvaluationFailed, + .certificatePinningFailed, + .publicKeyPinningFailed, + .customEvaluationFailed: + nil + } + } + + var underlyingError: (any Error)? { + switch self { + case let .customEvaluationFailed(error): + error + case let .trustEvaluationFailed(error): + error + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: + nil + } + } +} +#endif + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .explicitlyCancelled: + return "Request explicitly cancelled." + case let .invalidURL(url): + return "URL is not valid: \(url)" + case let .parameterEncodingFailed(reason): + return reason.localizedDescription + case let .parameterEncoderFailed(reason): + return reason.localizedDescription + case let .multipartEncodingFailed(reason): + return reason.localizedDescription + case let .requestAdaptationFailed(error): + return "Request adaption failed with error: \(error.localizedDescription)" + case let .responseValidationFailed(reason): + return reason.localizedDescription + case let .responseSerializationFailed(reason): + return reason.localizedDescription + case let .requestRetryFailed(retryError, originalError): + return """ + Request retry failed with retry error: \(retryError.localizedDescription), \ + original error: \(originalError.localizedDescription) + """ + case .sessionDeinitialized: + return """ + Session was invalidated without error, so it was likely deinitialized unexpectedly. \ + Be sure to retain a reference to your Session for the duration of your requests. + """ + case let .sessionInvalidated(error): + return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" + #if canImport(Security) + case let .serverTrustEvaluationFailed(reason): + return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" + #endif + case let .urlRequestValidationFailed(reason): + return "URLRequest validation failed due to reason: \(reason.localizedDescription)" + case let .createUploadableFailed(error): + return "Uploadable creation failed with error: \(error.localizedDescription)" + case let .createURLRequestFailed(error): + return "URLRequest creation failed with error: \(error.localizedDescription)" + case let .downloadedFileMoveFailed(error, source, destination): + return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" + case let .sessionTaskFailed(error): + return "URLSessionTask failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + "URL request to encode was missing a URL" + case let .jsonEncodingFailed(error): + "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case let .customEncodingFailed(error): + "Custom parameter encoder failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var localizedDescription: String { + switch self { + case let .missingRequiredComponent(component): + "Encoding failed due to a missing request component: \(component)" + case let .encoderFailed(error): + "The underlying encoder failed with the error: \(error)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case let .bodyPartURLInvalid(url): + "The URL provided is not a file URL: \(url)" + case let .bodyPartFilenameInvalid(url): + "The URL provided does not have a valid filename: \(url)" + case let .bodyPartFileNotReachable(url): + "The URL provided is not reachable: \(url)" + case let .bodyPartFileNotReachableWithError(url, error): + """ + The system returned an error while checking the provided URL for reachability. + URL: \(url) + Error: \(error) + """ + case let .bodyPartFileIsDirectory(url): + "The URL provided is a directory: \(url)" + case let .bodyPartFileSizeNotAvailable(url): + "Could not fetch the file size from the provided URL: \(url)" + case let .bodyPartFileSizeQueryFailedWithError(url, error): + """ + The system returned an error while attempting to fetch the file size from the provided URL. + URL: \(url) + Error: \(error) + """ + case let .bodyPartInputStreamCreationFailed(url): + "Failed to create an InputStream for the provided URL: \(url)" + case let .outputStreamCreationFailed(url): + "Failed to create an OutputStream for URL: \(url)" + case let .outputStreamFileAlreadyExists(url): + "A file already exists at the provided URL: \(url)" + case let .outputStreamURLInvalid(url): + "The provided OutputStream URL is invalid: \(url)" + case let .outputStreamWriteFailed(error): + "OutputStream write failed with error: \(error)" + case let .inputStreamReadFailed(error): + "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNilOrZeroLength: + "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + "Response could not be serialized, input file was nil." + case let .inputFileReadFailed(url): + "Response could not be serialized, input file could not be read: \(url)." + case let .stringSerializationFailed(encoding): + "String could not be serialized with encoding: \(encoding)." + case let .jsonSerializationFailed(error): + "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case let .invalidEmptyResponse(type): + """ + Empty response could not be serialized to type: \(type). \ + Use Empty as the expected type for such responses. + """ + case let .decodingFailed(error): + "Response could not be decoded because of error:\n\(error.localizedDescription)" + case let .customSerializationFailed(error): + "Custom response serializer failed with error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + "Response could not be validated, data file was nil." + case let .dataFileReadFailed(url): + "Response could not be validated, data file could not be read: \(url)." + case let .missingContentType(types): + """ + Response Content-Type was missing and acceptable content types \ + (\(types.joined(separator: ","))) do not match "*/*". + """ + case let .unacceptableContentType(acceptableTypes, responseType): + """ + Response Content-Type "\(responseType)" does not match any acceptable types: \ + \(acceptableTypes.joined(separator: ",")). + """ + case let .unacceptableStatusCode(code): + "Response status code was unacceptable: \(code)." + case let .customValidationFailed(error): + "Custom response validation failed with error: \(error.localizedDescription)" + } + } +} + +#if canImport(Security) +extension AFError.ServerTrustFailureReason { + var localizedDescription: String { + switch self { + case let .noRequiredEvaluator(host): + "A ServerTrustEvaluating value is required for host \(host) but none was found." + case .noCertificatesFound: + "No certificates were found or provided for evaluation." + case .noPublicKeysFound: + "No public keys were found or provided for evaluation." + case .policyApplicationFailed: + "Attempting to set a SecPolicy failed." + case .settingAnchorCertificatesFailed: + "Attempting to set the provided certificates as anchor certificates failed." + case .revocationPolicyCreationFailed: + "Attempting to create a revocation policy failed." + case let .trustEvaluationFailed(error): + "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" + case let .defaultEvaluationFailed(output): + "Default evaluation failed for host \(output.host)." + case let .hostValidationFailed(output): + "Host validation failed for host \(output.host)." + case let .revocationCheckFailed(output, _): + "Revocation check failed for host \(output.host)." + case let .certificatePinningFailed(host, _, _, _): + "Certificate pinning failed for host \(host)." + case let .publicKeyPinningFailed(host, _, _, _): + "Public key pinning failed for host \(host)." + case let .customEvaluationFailed(error): + "Custom trust evaluation failed with error: \(error.localizedDescription)" + } + } +} +#endif + +extension AFError.URLRequestValidationFailureReason { + var localizedDescription: String { + switch self { + case let .bodyDataInGETRequest(data): + """ + Invalid URLRequest: Requests with GET method cannot have body data: + \(String(decoding: data, as: UTF8.self)) + """ + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DataRequest.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DataRequest.swift new file mode 100644 index 00000000..a70f234e --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DataRequest.swift @@ -0,0 +1,458 @@ +// +// DataRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. +public class DataRequest: Request, @unchecked Sendable { + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: any URLRequestConvertible + /// `Data` read from the server so far. + public var data: Data? { dataMutableState.data } + + private struct DataMutableState { + var data: Data? + var httpResponseHandler: (queue: DispatchQueue, + handler: @Sendable (_ response: HTTPURLResponse, + _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void)? + } + + private let dataMutableState = Protected(DataMutableState()) + + /// Creates a `DataRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: any URLRequestConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: (any EventMonitor)?, + interceptor: (any RequestInterceptor)?, + delegate: any RequestDelegate) { + self.convertible = convertible + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + dataMutableState.write { mutableState in + mutableState.data = nil + } + } + + /// Called when `Data` is received by this instance. + /// + /// - Note: Also calls `updateDownloadProgress`. + /// + /// - Parameter data: The `Data` received. + func didReceive(data: Data) { + dataMutableState.write { mutableState in + if mutableState.data == nil { + mutableState.data = data + } else { + mutableState.data?.append(data) + } + } + + updateDownloadProgress() + } + + func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) { + dataMutableState.read { dataMutableState in + guard let httpResponseHandler = dataMutableState.httpResponseHandler else { + underlyingQueue.async { completionHandler(.allow) } + return + } + + httpResponseHandler.queue.async { + httpResponseHandler.handler(response) { disposition in + if disposition == .cancel { + self.mutableState.write { mutableState in + mutableState.state = .cancelled + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + } + + self.underlyingQueue.async { + completionHandler(disposition.sessionDisposition) + } + } + } + } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + /// Called to update the `downloadProgress` of the instance. + func updateDownloadProgress() { + let totalBytesReceived = Int64(data?.count ?? 0) + let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + downloadProgress.totalUnitCount = totalBytesExpected + downloadProgress.completedUnitCount = totalBytesReceived + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure used to validate the response. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: @Sendable () -> Void = { [unowned self] in + guard error == nil, let response else { return } + + let result = validation(request, response, data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + data: data, + withResult: result) + } + + validators.write { $0.append(validator) } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion + /// handler to return a `ResponseDisposition` value. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided + /// MUST be called, otherwise the request will never complete. + /// + /// - Returns: The instance. + @_disfavoredOverload + @preconcurrency + @discardableResult + public func onHTTPResponse( + on queue: DispatchQueue = .main, + perform handler: @escaping @Sendable (_ response: HTTPURLResponse, + _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void + ) -> Self { + dataMutableState.write { mutableState in + mutableState.httpResponseHandler = (queue, handler) + } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func onHTTPResponse(on queue: DispatchQueue = .main, + perform handler: @escaping @Sendable (HTTPURLResponse) -> Void) -> Self { + onHTTPResponse(on: queue) { response, completionHandler in + handler(response) + completionHandler(.allow) + } + + return self + } + + // MARK: Response Serialization + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func response(queue: DispatchQueue = .main, completionHandler: @escaping @Sendable (AFDataResponse) -> Void) -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.data, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serialize(request: self.request, + response: self.response, + data: self.data, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (@Sendable () -> Void)? + + defer { + if let didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @preconcurrency + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } + + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseDecodable(of type: Value.Type = Value.self, + queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping @Sendable (AFDataResponse) -> Void) -> Self where Value: Decodable, Value: Sendable { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DataStreamRequest.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DataStreamRequest.swift new file mode 100644 index 00000000..2028f009 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DataStreamRequest.swift @@ -0,0 +1,590 @@ +// +// DataStreamRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. +public final class DataStreamRequest: Request, @unchecked Sendable { + /// Closure type handling `DataStreamRequest.Stream` values. + public typealias Handler = @Sendable (Stream) throws -> Void + + /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used + /// to stop the stream at any time. + public struct Stream: Sendable where Success: Sendable, Failure: Sendable { + /// Latest `Event` from the stream. + public let event: Event + /// Token used to cancel the stream. + public let token: CancellationToken + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + token.cancel() + } + } + + /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed + /// `Data` or the completion of the stream. + public enum Event: Sendable where Success: Sendable, Failure: Sendable { + /// Output produced every time the instance receives additional `Data`. The associated value contains the + /// `Result` of processing the incoming `Data`. + case stream(Result) + /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. + /// Associated `Completion` value contains the final state. + case complete(Completion) + } + + /// Value containing the state of a `DataStreamRequest` when the stream was completed. + public struct Completion: Sendable { + /// Last `URLRequest` issued by the instance. + public let request: URLRequest? + /// Last `HTTPURLResponse` received by the instance. + public let response: HTTPURLResponse? + /// Last `URLSessionTaskMetrics` produced for the instance. + public let metrics: URLSessionTaskMetrics? + /// `AFError` produced for the instance, if any. + public let error: AFError? + } + + /// Type used to cancel an ongoing stream. + public struct CancellationToken: Sendable { + weak var request: DataStreamRequest? + + init(_ request: DataStreamRequest) { + self.request = request + } + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + request?.cancel() + } + } + + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: any URLRequestConvertible + /// Whether or not the instance will be cancelled if stream parsing encounters an error. + public let automaticallyCancelOnStreamError: Bool + + /// Internal mutable state specific to this type. + struct StreamMutableState { + /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. + var outputStream: OutputStream? + /// Stream closures called as `Data` is received. + var streams: [@Sendable (_ data: Data) -> Void] = [] + /// Number of currently executing streams. Used to ensure completions are only fired after all streams are + /// enqueued. + var numberOfExecutingStreams = 0 + /// Completion calls enqueued while streams are still executing. + var enqueuedCompletionEvents: [@Sendable () -> Void] = [] + /// Handler for any `HTTPURLResponse`s received. + var httpResponseHandler: (queue: DispatchQueue, + handler: @Sendable (_ response: HTTPURLResponse, + _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void)? + } + + let streamMutableState = Protected(StreamMutableState()) + + /// Creates a `DataStreamRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` + /// by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this + /// instance. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` + /// is thrown while serializing stream `Data`. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default + /// targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by + /// the `Request`. + init(id: UUID = UUID(), + convertible: any URLRequestConvertible, + automaticallyCancelOnStreamError: Bool, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: (any EventMonitor)?, + interceptor: (any RequestInterceptor)?, + delegate: any RequestDelegate) { + self.convertible = convertible + self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + override func finish(error: AFError? = nil) { + streamMutableState.write { state in + state.outputStream?.close() + } + + super.finish(error: error) + } + + func didReceive(data: Data) { + streamMutableState.write { state in + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + if let stream = state.outputStream { + underlyingQueue.async { + var bytes = Array(data) + stream.write(&bytes, maxLength: bytes.count) + } + } + #endif + state.numberOfExecutingStreams += state.streams.count + underlyingQueue.async { [streams = state.streams] in streams.forEach { $0(data) } } + } + } + + func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) { + streamMutableState.read { dataMutableState in + guard let httpResponseHandler = dataMutableState.httpResponseHandler else { + underlyingQueue.async { completionHandler(.allow) } + return + } + + httpResponseHandler.queue.async { + httpResponseHandler.handler(response) { disposition in + if disposition == .cancel { + self.mutableState.write { mutableState in + mutableState.state = .cancelled + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + } + + self.underlyingQueue.async { + completionHandler(disposition.sessionDisposition) + } + } + } + } + } + + /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. + /// + /// - Parameter validation: `Validation` closure used to validate the request and response. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: @Sendable () -> Void = { [unowned self] in + guard error == nil, let response else { return } + + let result = validation(request, response) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + withResult: result) + } + + validators.write { $0.append(validator) } + + return self + } + + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + /// Produces an `InputStream` that receives the `Data` received by the instance. + /// + /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. + /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or + /// not the creating session has `startRequestsImmediately` set to `true`. + /// + /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. + /// + /// - Returns: The `InputStream` bound to the internal `OutboundStream`. + public func asInputStream(bufferSize: Int = 1024) -> InputStream? { + defer { resume() } + + var inputStream: InputStream? + streamMutableState.write { state in + Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, + inputStream: &inputStream, + outputStream: &state.outputStream) + state.outputStream?.open() + } + + return inputStream + } + #endif + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion + /// handler to return a `ResponseDisposition` value. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided + /// MUST be called, otherwise the request will never complete. + /// + /// - Returns: The instance. + @_disfavoredOverload + @preconcurrency + @discardableResult + public func onHTTPResponse( + on queue: DispatchQueue = .main, + perform handler: @escaping @Sendable (_ response: HTTPURLResponse, + _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void + ) -> Self { + streamMutableState.write { mutableState in + mutableState.httpResponseHandler = (queue, handler) + } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func onHTTPResponse(on queue: DispatchQueue = .main, + perform handler: @escaping @Sendable (HTTPURLResponse) -> Void) -> Self { + onHTTPResponse(on: queue) { response, completionHandler in + handler(response) + completionHandler(.allow) + } + + return self + } + + func capturingError(from closure: () throws -> Void) { + do { + try closure() + } catch { + self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + cancel() + } + } + + func appendStreamCompletion(on queue: DispatchQueue, + stream: @escaping Handler) where Success: Sendable, Failure: Sendable { + appendResponseSerializer { + self.underlyingQueue.async { + self.responseSerializerDidComplete { + self.streamMutableState.write { state in + guard state.numberOfExecutingStreams == 0 else { + state.enqueuedCompletionEvents.append { + self.enqueueCompletion(on: queue, stream: stream) + } + + return + } + + self.enqueueCompletion(on: queue, stream: stream) + } + } + } + } + } + + func enqueueCompletion(on queue: DispatchQueue, + stream: @escaping Handler) where Success: Sendable, Failure: Sendable { + queue.async { + do { + let completion = Completion(request: self.request, + response: self.response, + metrics: self.metrics, + error: self.error) + try stream(.init(event: .complete(completion), token: .init(self))) + } catch { + // Ignore error, as errors on Completion can't be handled anyway. + } + } + } + + // MARK: Response Serialization + + /// Adds a `StreamHandler` which performs no parsing on incoming `Data`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @preconcurrency + @discardableResult + public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler) -> Self { + let parser = { @Sendable [unowned self] (data: Data) in + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(data)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + + streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @preconcurrency + @discardableResult + public func responseStream(using serializer: Serializer, + on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { @Sendable [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let result = Result { try serializer.serialize(data) } + .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) } + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: result) + + if result.isFailure, self.automaticallyCancelOnStreamError { + self.cancel() + } + + queue.async { + self.capturingError { + try stream(.init(event: .stream(result), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @preconcurrency + @discardableResult + public func responseStreamString(on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { @Sendable [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let string = String(decoding: data, as: UTF8.self) + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: .success(string)) + + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(string)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + private func updateAndCompleteIfPossible() { + streamMutableState.write { state in + state.numberOfExecutingStreams -= 1 + + guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return } + + let completionEvents = state.enqueuedCompletionEvents + self.underlyingQueue.async { completionEvents.forEach { $0() } } + state.enqueuedCompletionEvents.removeAll() + } + } + + /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`. + /// + /// - Parameters: + /// - type: `Decodable` type to parse incoming `Data` into. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - decoder: `DataDecoder` used to decode the incoming `Data`. + /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @preconcurrency + @discardableResult + public func responseStreamDecodable(of type: T.Type = T.self, + on queue: DispatchQueue = .main, + using decoder: any DataDecoder = JSONDecoder(), + preprocessor: any DataPreprocessor = PassthroughPreprocessor(), + stream: @escaping Handler) -> Self where T: Sendable { + responseStream(using: DecodableStreamSerializer(decoder: decoder, dataPreprocessor: preprocessor), + on: queue, + stream: stream) + } +} + +extension DataStreamRequest.Stream { + /// Incoming `Result` values from `Event.stream`. + public var result: Result? { + guard case let .stream(result) = event else { return nil } + + return result + } + + /// `Success` value of the instance, if any. + public var value: Success? { + guard case let .success(value) = result else { return nil } + + return value + } + + /// `Failure` value of the instance, if any. + public var error: Failure? { + guard case let .failure(error) = result else { return nil } + + return error + } + + /// `Completion` value of the instance, if any. + public var completion: DataStreamRequest.Completion? { + guard case let .complete(completion) = event else { return nil } + + return completion + } +} + +// MARK: - Serialization + +/// A type which can serialize incoming `Data`. +public protocol DataStreamSerializer: Sendable { + /// Type produced from the serialized `Data`. + associatedtype SerializedObject: Sendable + + /// Serializes incoming `Data` into a `SerializedObject` value. + /// + /// - Parameter data: `Data` to be serialized. + /// + /// - Throws: Any error produced during serialization. + func serialize(_ data: Data) throws -> SerializedObject +} + +/// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`. +public struct DecodableStreamSerializer: DataStreamSerializer where T: Sendable { + /// `DataDecoder` used to decode incoming `Data`. + public let decoder: any DataDecoder + /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`. + public let dataPreprocessor: any DataPreprocessor + + /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`. + /// - Parameters: + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public init(decoder: any DataDecoder = JSONDecoder(), dataPreprocessor: any DataPreprocessor = PassthroughPreprocessor()) { + self.decoder = decoder + self.dataPreprocessor = dataPreprocessor + } + + public func serialize(_ data: Data) throws -> T { + let processedData = try dataPreprocessor.preprocess(data) + do { + return try decoder.decode(T.self, from: processedData) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +/// `DataStreamSerializer` which performs no serialization on incoming `Data`. +public struct PassthroughStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> Data { data } +} + +/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values. +public struct StringStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> String { + String(decoding: data, as: UTF8.self) + } +} + +extension DataStreamSerializer { + /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from stream data. + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public static func decodable(of type: T.Type, + decoder: any DataDecoder = JSONDecoder(), + dataPreprocessor: any DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer { + DecodableStreamSerializer(decoder: decoder, dataPreprocessor: dataPreprocessor) + } +} + +extension DataStreamSerializer where Self == PassthroughStreamSerializer { + /// Provides a `PassthroughStreamSerializer` instance. + public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() } +} + +extension DataStreamSerializer where Self == StringStreamSerializer { + /// Provides a `StringStreamSerializer` instance. + public static var string: StringStreamSerializer { StringStreamSerializer() } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DownloadRequest.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DownloadRequest.swift new file mode 100644 index 00000000..769b3b55 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/DownloadRequest.swift @@ -0,0 +1,607 @@ +// +// DownloadRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. +public final class DownloadRequest: Request, @unchecked Sendable { + /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination + /// `URL`. + public struct Options: OptionSet, Sendable { + /// Specifies that intermediate directories for the destination URL should be created. + public static let createIntermediateDirectories = Options(rawValue: 1 << 0) + /// Specifies that any previous file at the destination `URL` should be removed. + public static let removePreviousFile = Options(rawValue: 1 << 1) + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + } + + // MARK: Destination + + /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + /// + /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not + /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. + public typealias Destination = @Sendable (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - Parameters: + /// - directory: The search path directory. `.documentDirectory` by default. + /// - domain: The search path domain mask. `.userDomainMask` by default. + /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by + /// default. + /// - Returns: The `Destination` closure. + public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask, + options: Options = []) -> Destination { + { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL + + return (url, options) + } + } + + /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends + /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files + /// with this destination must be additionally moved if they should survive the system reclamation of temporary + /// space. + static let defaultDestination: Destination = { url, _ in + (defaultDestinationURL(url), []) + } + + /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the + /// provided file name. + static let defaultDestinationURL: @Sendable (URL) -> URL = { url in + let filename = "Alamofire_\(url.lastPathComponent)" + let destination = url.deletingLastPathComponent().appendingPathComponent(filename) + + return destination + } + + // MARK: Downloadable + + /// Type describing the source used to create the underlying `URLSessionDownloadTask`. + public enum Downloadable { + /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. + case request(any URLRequestConvertible) + /// Download should be started from the associated resume `Data` value. + case resumeData(Data) + } + + // MARK: Mutable State + + /// Type containing all mutable state for `DownloadRequest` instances. + private struct DownloadRequestMutableState { + /// Possible resume `Data` produced when cancelling the instance. + var resumeData: Data? + /// `URL` to which `Data` is being downloaded. + var fileURL: URL? + } + + /// Protected mutable state specific to `DownloadRequest`. + private let mutableDownloadState = Protected(DownloadRequestMutableState()) + + /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download + /// using the `download(resumingWith data:)` API. + /// + /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). + public var resumeData: Data? { + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + return mutableDownloadState.resumeData ?? error?.downloadResumeData + #else + return mutableDownloadState.resumeData + #endif + } + + /// If the download is successful, the `URL` where the file was downloaded. + public var fileURL: URL? { mutableDownloadState.fileURL } + + // MARK: Initial State + + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination + + /// Creates a `DownloadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` + /// - destination: `Destination` closure used to move the downloaded file to its final location. + init(id: UUID = UUID(), + downloadable: Downloadable, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: (any EventMonitor)?, + interceptor: (any RequestInterceptor)?, + delegate: any RequestDelegate, + destination: @escaping Destination) { + self.downloadable = downloadable + self.destination = destination + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + mutableDownloadState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. + /// + /// - Parameters: + /// - task: `URLSessionTask` that finished the download. + /// - result: `Result` of the automatic move to `destination`. + func didFinishDownloading(using task: URLSessionTask, with result: Result) { + eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) + + switch result { + case let .success(url): mutableDownloadState.fileURL = url + case let .failure(error): self.error = error + } + } + + /// Updates the `downloadProgress` using the provided values. + /// + /// - Parameters: + /// - bytesWritten: Total bytes written so far. + /// - totalBytesExpectedToWrite: Total bytes expected to write. + func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + downloadProgress.totalUnitCount = totalBytesExpectedToWrite + downloadProgress.completedUnitCount += bytesWritten + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + session.downloadTask(with: request) + } + + /// Creates a `URLSessionTask` from the provided resume data. + /// + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + session.downloadTask(withResumeData: data) + } + + /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. + /// + /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use + /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. + /// + /// - Returns: The instance. + @discardableResult + override public func cancel() -> Self { + cancel(producingResumeData: false) + } + + /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be + /// resumed or suspended. + /// + /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if + /// available. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { + cancel(optionallyProducingResumeData: shouldProduceResumeData ? { @Sendable _ in } : nil) + } + + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. + /// + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. + /// + /// - Parameter completionHandler: The completion handler that is called when the download has been successfully + /// cancelled. It is not guaranteed to be called on a particular queue, so you may + /// want use an appropriate queue to perform your work. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func cancel(byProducingResumeData completionHandler: @escaping @Sendable (_ data: Data?) -> Void) -> Self { + cancel(optionallyProducingResumeData: completionHandler) + } + + /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, + /// cancellation is performed without producing resume data. + /// + /// - Parameter completionHandler: Optional resume data handler. + /// + /// - Returns: The instance. + private func cancel(optionallyProducingResumeData completionHandler: (@Sendable (_ resumeData: Data?) -> Void)?) -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + if let completionHandler { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel { resumeData in + self.mutableDownloadState.resumeData = resumeData + self.underlyingQueue.async { self.didCancelTask(task) } + completionHandler(resumeData) + } + } else { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + self.underlyingQueue.async { self.didCancelTask(task) } + } + } + + return self + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: @Sendable () -> Void = { [unowned self] in + guard error == nil, let response else { return } + + let result = validation(request, response, fileURL) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + fileURL: fileURL, + withResult: result) + } + + validators.write { $0.append(validator) } + + return self + } + + // MARK: - Response Serialization + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func response(queue: DispatchQueue = .main, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.fileURL, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serializeDownload(request: self.request, + response: self.response, + fileURL: self.fileURL, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (@Sendable () -> Void)? + + defer { + if let didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Note: This handler will read the entire downloaded file into memory, use with caution. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Note: This handler will read the entire downloaded file into memory, use with caution. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseURL(queue: DispatchQueue = .main, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler) + } + + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Note: This handler will read the entire downloaded file into memory, use with caution. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Note: This handler will read the entire downloaded file into memory, use with caution. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Note: This handler will read the entire downloaded file into memory, use with caution. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @preconcurrency + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } + + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Note: This handler will read the entire downloaded file into memory, use with caution. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @preconcurrency + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping @Sendable (AFDownloadResponse) -> Void) -> Self where T: Sendable { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/HTTPHeaders.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/HTTPHeaders.swift new file mode 100644 index 00000000..dbdcabcf --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/HTTPHeaders.swift @@ -0,0 +1,465 @@ +// +// HTTPHeaders.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An order-preserving and case-insensitive representation of HTTP headers. +public struct HTTPHeaders: Equatable, Hashable, Sendable { + private var headers: [HTTPHeader] = [] + + /// Creates an empty instance. + public init() {} + + /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last + /// name and value encountered. + public init(_ headers: [HTTPHeader]) { + headers.forEach { update($0) } + } + + /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name + /// and value encountered. + public init(_ dictionary: [String: String]) { + dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader` value. + public mutating func add(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func add(_ header: HTTPHeader) { + update(header) + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader` value. + public mutating func update(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func update(_ header: HTTPHeader) { + guard let index = headers.index(of: header.name) else { + headers.append(header) + return + } + + headers.replaceSubrange(index...index, with: [header]) + } + + /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. + /// + /// - Parameter name: The name of the `HTTPHeader` to remove. + public mutating func remove(name: String) { + guard let index = headers.index(of: name) else { return } + + headers.remove(at: index) + } + + /// Sort the current instance by header name, case insensitively. + public mutating func sort() { + headers.sort { $0.name.lowercased() < $1.name.lowercased() } + } + + /// Returns an instance sorted by header name. + /// + /// - Returns: A copy of the current instance sorted by name. + public func sorted() -> HTTPHeaders { + var headers = self + headers.sort() + + return headers + } + + /// Case-insensitively find a header's value by name. + /// + /// - Parameter name: The name of the header to search for, case-insensitively. + /// + /// - Returns: The value of header, if it exists. + public func value(for name: String) -> String? { + guard let index = headers.index(of: name) else { return nil } + + return headers[index].value + } + + /// Case-insensitively access the header with the given name. + /// + /// - Parameter name: The name of the header. + public subscript(_ name: String) -> String? { + get { value(for: name) } + set { + if let value = newValue { + update(name: name, value: value) + } else { + remove(name: name) + } + } + } + + /// The dictionary representation of all headers. + /// + /// This representation does not preserve the current order of the instance. + public var dictionary: [String: String] { + let namesAndValues = headers.map { ($0.name, $0.value) } + + return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) + } +} + +extension HTTPHeaders: ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, String)...) { + elements.forEach { update(name: $0.0, value: $0.1) } + } +} + +extension HTTPHeaders: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: HTTPHeader...) { + self.init(elements) + } +} + +extension HTTPHeaders: Sequence { + public func makeIterator() -> IndexingIterator<[HTTPHeader]> { + headers.makeIterator() + } +} + +extension HTTPHeaders: Collection { + public var startIndex: Int { + headers.startIndex + } + + public var endIndex: Int { + headers.endIndex + } + + public subscript(position: Int) -> HTTPHeader { + headers[position] + } + + public func index(after i: Int) -> Int { + headers.index(after: i) + } +} + +extension HTTPHeaders: CustomStringConvertible { + public var description: String { + headers.map(\.description) + .joined(separator: "\n") + } +} + +// MARK: - HTTPHeader + +/// A representation of a single HTTP header's name / value pair. +public struct HTTPHeader: Equatable, Hashable, Sendable { + /// Name of the header. + public let name: String + + /// Value of the header. + public let value: String + + /// Creates an instance from the given `name` and `value`. + /// + /// - Parameters: + /// - name: The name of the header. + /// - value: The value of the header. + public init(name: String, value: String) { + self.name = name + self.value = value + } +} + +extension HTTPHeader: CustomStringConvertible { + public var description: String { + "\(name): \(value)" + } +} + +extension HTTPHeader { + /// Returns an `Accept` header. + /// + /// - Parameter value: The `Accept` value. + /// - Returns: The header. + public static func accept(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept", value: value) + } + + /// Returns an `Accept-Charset` header. + /// + /// - Parameter value: The `Accept-Charset` value. + /// - Returns: The header. + public static func acceptCharset(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Charset", value: value) + } + + /// Returns an `Accept-Language` header. + /// + /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. + /// Use `HTTPHeader.defaultAcceptLanguage`. + /// + /// - Parameter value: The `Accept-Language` value. + /// + /// - Returns: The header. + public static func acceptLanguage(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Language", value: value) + } + + /// Returns an `Accept-Encoding` header. + /// + /// Alamofire offers a default accept encoding value that provides the most common values. Use + /// `HTTPHeader.defaultAcceptEncoding`. + /// + /// - Parameter value: The `Accept-Encoding` value. + /// + /// - Returns: The header + public static func acceptEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Encoding", value: value) + } + + /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. + /// + /// - Parameters: + /// - username: The username of the header. + /// - password: The password of the header. + /// + /// - Returns: The header. + public static func authorization(username: String, password: String) -> HTTPHeader { + let credential = Data("\(username):\(password)".utf8).base64EncodedString() + + return authorization("Basic \(credential)") + } + + /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided. + /// + /// - Parameter bearerToken: The bearer token. + /// + /// - Returns: The header. + public static func authorization(bearerToken: String) -> HTTPHeader { + authorization("Bearer \(bearerToken)") + } + + /// Returns an `Authorization` header. + /// + /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use + /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use + /// `HTTPHeader.authorization(bearerToken:)`. + /// + /// - Parameter value: The `Authorization` value. + /// + /// - Returns: The header. + public static func authorization(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Authorization", value: value) + } + + /// Returns a `Content-Disposition` header. + /// + /// - Parameter value: The `Content-Disposition` value. + /// + /// - Returns: The header. + public static func contentDisposition(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Disposition", value: value) + } + + /// Returns a `Content-Encoding` header. + /// + /// - Parameter value: The `Content-Encoding`. + /// + /// - Returns: The header. + public static func contentEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Encoding", value: value) + } + + /// Returns a `Content-Type` header. + /// + /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not + /// be necessary to manually set this value. + /// + /// - Parameter value: The `Content-Type` value. + /// + /// - Returns: The header. + public static func contentType(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Type", value: value) + } + + /// Returns a `User-Agent` header. + /// + /// - Parameter value: The `User-Agent` value. + /// + /// - Returns: The header. + public static func userAgent(_ value: String) -> HTTPHeader { + HTTPHeader(name: "User-Agent", value: value) + } + + /// Returns a `Sec-WebSocket-Protocol` header. + /// + /// - Parameter value: The `Sec-WebSocket-Protocol` value. + /// - Returns: The header. + public static func websocketProtocol(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Sec-WebSocket-Protocol", value: value) + } +} + +extension [HTTPHeader] { + /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. + func index(of name: String) -> Int? { + let lowercasedName = name.lowercased() + return firstIndex { $0.name.lowercased() == lowercasedName } + } +} + +// MARK: - Defaults + +extension HTTPHeaders { + /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and + /// `User-Agent`. + public static let `default`: HTTPHeaders = [.defaultAcceptEncoding, + .defaultAcceptLanguage, + .defaultUserAgent] +} + +extension HTTPHeader { + /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS + /// versions. + /// + /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . + public static let defaultAcceptEncoding: HTTPHeader = { + let encodings: [String] = if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { + ["br", "gzip", "deflate"] + } else { + ["gzip", "deflate"] + } + + return .acceptEncoding(encodings.qualityEncoded()) + }() + + /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's + /// `preferredLanguages`. + /// + /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). + public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) + + /// Returns Alamofire's default `User-Agent` header. + /// + /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). + /// + /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` + public static let defaultUserAgent: HTTPHeader = { + let info = Bundle.main.infoDictionary + let executable = (info?["CFBundleExecutable"] as? String) ?? + (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ?? + "Unknown" + let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown" + let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info?["CFBundleVersion"] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + let osName: String = { + #if os(iOS) + #if targetEnvironment(macCatalyst) + return "macOS(Catalyst)" + #else + return "iOS" + #endif + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + #if targetEnvironment(macCatalyst) + return "macOS(Catalyst)" + #else + return "macOS" + #endif + #elseif swift(>=5.9.2) && os(visionOS) + return "visionOS" + #elseif os(Linux) + return "Linux" + #elseif os(Windows) + return "Windows" + #elseif os(Android) + return "Android" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion = "Alamofire/\(AFInfo.version)" + + let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + + return .userAgent(userAgent) + }() +} + +extension Collection { + func qualityEncoded() -> String { + enumerated().map { index, encoding in + let quality = 1.0 - (Double(index) * 0.1) + return "\(encoding);q=\(quality)" + }.joined(separator: ", ") + } +} + +// MARK: - System Type Extensions + +extension URLRequest { + /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } + set { allHTTPHeaderFields = newValue.dictionary } + } +} + +extension HTTPURLResponse { + /// Returns `allHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() + } +} + +extension URLSessionConfiguration { + /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } + set { httpAdditionalHeaders = newValue.dictionary } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/HTTPMethod.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/HTTPMethod.swift new file mode 100644 index 00000000..ed51b689 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/HTTPMethod.swift @@ -0,0 +1,56 @@ +// +// HTTPMethod.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so +/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public struct HTTPMethod: RawRepresentable, Equatable, Hashable, Sendable { + /// `CONNECT` method. + public static let connect = HTTPMethod(rawValue: "CONNECT") + /// `DELETE` method. + public static let delete = HTTPMethod(rawValue: "DELETE") + /// `GET` method. + public static let get = HTTPMethod(rawValue: "GET") + /// `HEAD` method. + public static let head = HTTPMethod(rawValue: "HEAD") + /// `OPTIONS` method. + public static let options = HTTPMethod(rawValue: "OPTIONS") + /// `PATCH` method. + public static let patch = HTTPMethod(rawValue: "PATCH") + /// `POST` method. + public static let post = HTTPMethod(rawValue: "POST") + /// `PUT` method. + public static let put = HTTPMethod(rawValue: "PUT") + /// `QUERY` method. + public static let query = HTTPMethod(rawValue: "QUERY") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Notifications.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Notifications.swift new file mode 100644 index 00000000..6fa9dac3 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Notifications.swift @@ -0,0 +1,118 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. + public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. + public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") + /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. + public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") + /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. + public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") + + /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") + /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") + /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") + /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") +} + +// MARK: - + +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + userInfo?[String.requestKey] as? Request + } + + /// Convenience initializer for a `Notification` containing a `Request` payload. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + init(name: Notification.Name, request: Request) { + self.init(name: name, object: nil, userInfo: [String.requestKey: request]) + } +} + +extension NotificationCenter { + /// Convenience function for posting notifications with `Request` payloads. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + func postNotification(named name: Notification.Name, with request: Request) { + let notification = Notification(name: name, request: request) + post(notification) + } +} + +extension String { + /// User info dictionary key representing the `Request` associated with the notification. + fileprivate static let requestKey = "org.alamofire.notification.key.request" +} + +/// `EventMonitor` that provides Alamofire's notifications. +public final class AlamofireNotifications: EventMonitor { + /// Creates an instance. + public init() {} + + public func requestDidResume(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) + } + + public func requestDidSuspend(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) + } + + public func requestDidCancel(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) + } + + public func requestDidFinish(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/ParameterEncoder.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/ParameterEncoder.swift new file mode 100644 index 00000000..eadd3c7b --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/ParameterEncoder.swift @@ -0,0 +1,213 @@ +// +// ParameterEncoder.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can encode any `Encodable` type into a `URLRequest`. +public protocol ParameterEncoder: Sendable { + /// Encode the provided `Encodable` parameters into `request`. + /// + /// - Parameters: + /// - parameters: The `Encodable` parameter value. + /// - request: The `URLRequest` into which to encode the parameters. + /// + /// - Returns: A `URLRequest` with the result of the encoding. + /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of + /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. + func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest +} + +/// A `ParameterEncoder` that encodes types as JSON body data. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. +open class JSONParameterEncoder: @unchecked Sendable, ParameterEncoder { + /// Returns an encoder with default parameters. + public static var `default`: JSONParameterEncoder { JSONParameterEncoder() } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. + public static var prettyPrinted: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .prettyPrinted + + return JSONParameterEncoder(encoder: encoder) + } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public static var sortedKeys: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + + return JSONParameterEncoder(encoder: encoder) + } + + /// `JSONEncoder` used to encode parameters. + public let encoder: JSONEncoder + + /// Creates an instance with the provided `JSONEncoder`. + /// + /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. + public init(encoder: JSONEncoder = JSONEncoder()) { + self.encoder = encoder + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters else { return request } + + var request = request + + do { + let data = try encoder.encode(parameters) + request.httpBody = data + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/json")) + } + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return request + } +} + +extension ParameterEncoder where Self == JSONParameterEncoder { + /// Provides a default `JSONParameterEncoder` instance. + public static var json: JSONParameterEncoder { JSONParameterEncoder() } + + /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`. + /// + /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default. + /// - Returns: The `JSONParameterEncoder`. + public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder { + JSONParameterEncoder(encoder: encoder) + } +} + +/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending +/// on the `Destination` set. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. +open class URLEncodedFormParameterEncoder: @unchecked Sendable, ParameterEncoder { + /// Defines where the URL-encoded string should be set for each `URLRequest`. + public enum Destination { + /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. + /// Sets it to the `httpBody` for all other methods. + case methodDependent + /// Applies the encoded query string to any existing query string from the `URLRequest`. + case queryString + /// Applies the encoded query string to the `httpBody` of the `URLRequest`. + case httpBody + + /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. + /// + /// - Parameter method: The `HTTPMethod`. + /// + /// - Returns: Whether the URL-encoded string should be applied to a `URL`. + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: [.get, .head, .delete].contains(method) + case .queryString: true + case .httpBody: false + } + } + } + + /// Returns an encoder with default parameters. + public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// The `URLEncodedFormEncoder` to use. + public let encoder: URLEncodedFormEncoder + + /// The `Destination` for the URL-encoded string. + public let destination: Destination + + /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. + /// + /// - Parameters: + /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. + /// - destination: The `Destination`. `.methodDependent` by default. + public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { + self.encoder = encoder + self.destination = destination + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters else { return request } + + var request = request + + guard let url = request.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + guard let method = request.method else { + let rawValue = request.method?.rawValue ?? "nil" + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) + } + + if destination.encodesParametersInURL(for: method), + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { + let query: String = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() + components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString + + guard let newURL = components.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + request.url = newURL + } else { + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + request.httpBody = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + } + + return request + } +} + +extension ParameterEncoder where Self == URLEncodedFormParameterEncoder { + /// Provides a default `URLEncodedFormParameterEncoder` instance. + public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination. + /// + /// - Parameters: + /// - encoder: `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default. + /// - destination: `Destination` to which to encode the parameters. `.methodDependent` by default. + /// - Returns: The `URLEncodedFormParameterEncoder`. + public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), + destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder { + URLEncodedFormParameterEncoder(encoder: encoder, destination: destination) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/ParameterEncoding.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/ParameterEncoding.swift new file mode 100644 index 00000000..d3341b05 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/ParameterEncoding.swift @@ -0,0 +1,349 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: any Any & Sendable] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding: Sendable { + /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. + func encode(_ urlRequest: any URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + public enum Destination: Sendable { + /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and + /// sets as the HTTP body for requests with any other HTTP method. + case methodDependent + /// Sets or appends encoded query string result to existing query string. + case queryString + /// Sets encoded query string result as the HTTP body of the URL request. + case httpBody + + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: [.get, .head, .delete].contains(method) + case .queryString: true + case .httpBody: false + } + } + } + + /// Configures how `Array` parameters are encoded. + public enum ArrayEncoding: Sendable { + /// An empty set of square brackets is appended to the key for every value. This is the default behavior. + case brackets + /// No brackets are appended. The key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom(@Sendable (_ key: String, _ index: Int) -> String) + + func encode(key: String, atIndex index: Int) -> String { + switch self { + case .brackets: + "\(key)[]" + case .noBrackets: + key + case .indexInBrackets: + "\(key)[\(index)]" + case let .custom(encoding): + encoding(key, index) + } + } + } + + /// Configures how `Bool` parameters are encoded. + public enum BoolEncoding: Sendable { + /// Encode `true` as `1` and `false` as `0`. This is the default behavior. + case numeric + /// Encode `true` and `false` as string literals. + case literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + value ? "1" : "0" + case .literal: + value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. + public static var `default`: URLEncoding { URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + + // MARK: Initialization + + /// Creates an instance using the specified parameters. + /// + /// - Parameters: + /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by + /// default. + /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. + public init(destination: Destination = .methodDependent, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + public func encode(_ urlRequest: any URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters else { return urlRequest } + + if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + urlRequest.httpBody = Data(query(parameters).utf8) + } + + return urlRequest + } + + /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. + /// + /// - Parameters: + /// - key: Key of the query component. + /// - value: Value of the query component. + /// + /// - Returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + switch value { + case let dictionary as [String: Any]: + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + case let array as [Any]: + for (index, value) in array.enumerated() { + components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value) + } + case let number as NSNumber: + if number.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue)))) + } else { + components.append((escape(key), escape("\(number)"))) + } + case let bool as Bool: + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + default: + components.append((escape(key), escape("\(value)"))) + } + return components + } + + /// Creates a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// - Parameter string: `String` to be percent-escaped. + /// + /// - Returns: The percent-escaped `String`. + public func escape(_ string: String) -> String { + string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string + } + + private func query(_ parameters: [String: Any]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + /// Error produced by `JSONEncoding`. + public enum Error: Swift.Error { + /// `JSONEncoding` attempted to encode an invalid JSON object. Usually this means the value included types not + /// representable in Objective-C. See `JSONSerialization.isValidJSONObject` for details. + case invalidJSONObject + } + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates an instance using the specified `WritingOptions`. + /// + /// - Parameter options: `JSONSerialization.WritingOptions` to use. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + public func encode(_ urlRequest: any URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(parameters) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Encodes any JSON compatible object into a `URLRequest`. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. + /// - jsonObject: `Any` value (must be JSON compatible) to be encoded into the `URLRequest`. `nil` by default. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during encoding. + public func encode(_ urlRequest: any URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(jsonObject) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +extension JSONEncoding.Error { + public var localizedDescription: String { + """ + Invalid JSON object provided for parameter or object encoding. \ + This is most likely due to a value which can't be represented in Objective-C. + """ + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { + // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of + // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22). + String(cString: objCType) == "c" + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Protected.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Protected.swift new file mode 100644 index 00000000..91a8adeb --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Protected.swift @@ -0,0 +1,179 @@ +// +// Protected.swift +// +// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +private protocol Lock: Sendable { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value the closure generated. + func around(_ closure: () throws -> T) rethrows -> T { + lock(); defer { unlock() } + return try closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () throws -> Void) rethrows { + lock(); defer { unlock() } + try closure() + } +} + +#if canImport(Darwin) +// Number of Apple engineers who insisted on inspecting this: 5 +/// An `os_unfair_lock` wrapper. +final class UnfairLock: Lock, @unchecked Sendable { + private let unfairLock: os_unfair_lock_t + + init() { + unfairLock = .allocate(capacity: 1) + unfairLock.initialize(to: os_unfair_lock()) + } + + deinit { + unfairLock.deinitialize(count: 1) + unfairLock.deallocate() + } + + fileprivate func lock() { + os_unfair_lock_lock(unfairLock) + } + + fileprivate func unlock() { + os_unfair_lock_unlock(unfairLock) + } +} + +#elseif canImport(Foundation) +extension NSLock: Lock {} +#else +#error("This platform needs a Lock-conforming type without Foundation.") +#endif + +/// A thread-safe wrapper around a value. +@dynamicMemberLookup +final class Protected { + #if canImport(Darwin) + private let lock = UnfairLock() + #elseif canImport(Foundation) + private let lock = NSLock() + #else + #error("This platform needs a Lock-conforming type without Foundation.") + #endif + #if compiler(>=6) + private nonisolated(unsafe) var value: Value + #else + private var value: Value + #endif + + init(_ value: Value) { + self.value = value + } + + /// Synchronously read or transform the contained value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The return value of the closure passed. + func read(_ closure: (Value) throws -> U) rethrows -> U { + try lock.around { try closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout Value) throws -> U) rethrows -> U { + try lock.around { try closure(&self.value) } + } + + /// Synchronously update the protected value. + /// + /// - Parameter value: The `Value`. + func write(_ value: Value) { + write { $0 = value } + } + + subscript(dynamicMember keyPath: WritableKeyPath) -> Property { + get { lock.around { value[keyPath: keyPath] } } + set { lock.around { value[keyPath: keyPath] = newValue } } + } + + subscript(dynamicMember keyPath: KeyPath) -> Property { + lock.around { value[keyPath: keyPath] } + } +} + +#if compiler(>=6) +extension Protected: Sendable {} +#else +extension Protected: @unchecked Sendable {} +#endif + +extension Protected where Value == Request.MutableState { + /// Attempts to transition to the passed `State`. + /// + /// - Parameter state: The `State` to attempt transition to. + /// + /// - Returns: Whether the transition occurred. + func attemptToTransitionTo(_ state: Request.State) -> Bool { + lock.around { + guard value.state.canTransitionTo(state) else { return false } + + value.state = state + + return true + } + } + + /// Perform a closure while locked with the provided `Request.State`. + /// + /// - Parameter perform: The closure to perform while locked. + func withState(perform: (Request.State) -> Void) { + lock.around { perform(value.state) } + } +} + +extension Protected: Equatable where Value: Equatable { + static func ==(lhs: Protected, rhs: Protected) -> Bool { + lhs.read { left in rhs.read { right in left == right }} + } +} + +extension Protected: Hashable where Value: Hashable { + func hash(into hasher: inout Hasher) { + read { hasher.combine($0) } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Request.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Request.swift new file mode 100644 index 00000000..574b6d13 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Request.swift @@ -0,0 +1,1100 @@ +// +// Request.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback +/// handling. +public class Request: @unchecked Sendable { + /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or + /// `cancel()` on the `Request`. + public enum State { + /// Initial state of the `Request`. + case initialized + /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on + /// them in this state. + case resumed + /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on + /// them in this state. + case suspended + /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on + /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition + /// to any other state. + case cancelled + /// `State` set when all response serialization completion closures have been cleared on the `Request` and + /// enqueued on their respective queues. + case finished + + /// Determines whether `self` can be transitioned to the provided `State`. + func canTransitionTo(_ state: State) -> Bool { + switch (self, state) { + case (.initialized, _): + true + case (_, .initialized), (.cancelled, _), (.finished, _): + false + case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): + true + case (.suspended, .suspended), (.resumed, .resumed): + false + case (_, .finished): + true + } + } + } + + // MARK: - Initial State + + /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. + public let id: UUID + /// The serial queue for all internal async actions. + public let underlyingQueue: DispatchQueue + /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. + public let serializationQueue: DispatchQueue + /// `EventMonitor` used for event callbacks. + public let eventMonitor: (any EventMonitor)? + /// The `Request`'s interceptor. + public let interceptor: (any RequestInterceptor)? + /// The `Request`'s delegate. + public private(set) weak var delegate: (any RequestDelegate)? + + // MARK: - Mutable State + + /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. + struct MutableState { + /// State of the `Request`. + var state: State = .initialized + /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. + var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. + var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `RedirectHandler` provided for to handle request redirection. + var redirectHandler: (any RedirectHandler)? + /// `CachedResponseHandler` provided to handle response caching. + var cachedResponseHandler: (any CachedResponseHandler)? + /// Queue and closure called when the `Request` is able to create a cURL description of itself. + var cURLHandler: (queue: DispatchQueue, handler: @Sendable (String) -> Void)? + /// Queue and closure called when the `Request` creates a `URLRequest`. + var urlRequestHandler: (queue: DispatchQueue, handler: @Sendable (URLRequest) -> Void)? + /// Queue and closure called when the `Request` creates a `URLSessionTask`. + var urlSessionTaskHandler: (queue: DispatchQueue, handler: @Sendable (URLSessionTask) -> Void)? + /// Response serialization closures that handle response parsing. + var responseSerializers: [@Sendable () -> Void] = [] + /// Response serialization completion closures executed once all response serializers are complete. + var responseSerializerCompletions: [@Sendable () -> Void] = [] + /// Whether response serializer processing is finished. + var responseSerializerProcessingFinished = false + /// `URLCredential` used for authentication challenges. + var credential: URLCredential? + /// All `URLRequest`s created by Alamofire on behalf of the `Request`. + var requests: [URLRequest] = [] + /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. + var tasks: [URLSessionTask] = [] + /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond + /// exactly the the `tasks` created. + var metrics: [URLSessionTaskMetrics] = [] + /// Number of times any retriers provided retried the `Request`. + var retryCount = 0 + /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. + var error: AFError? + /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a + /// representation in the state machine in the future. + var isFinishing = false + /// Actions to run when requests are finished. Use for concurrency support. + var finishHandlers: [() -> Void] = [] + } + + /// Protected `MutableState` value that provides thread-safe access to state values. + let mutableState = Protected(MutableState()) + + /// `State` of the `Request`. + public var state: State { mutableState.state } + /// Returns whether `state` is `.initialized`. + public var isInitialized: Bool { state == .initialized } + /// Returns whether `state` is `.resumed`. + public var isResumed: Bool { state == .resumed } + /// Returns whether `state` is `.suspended`. + public var isSuspended: Bool { state == .suspended } + /// Returns whether `state` is `.cancelled`. + public var isCancelled: Bool { state == .cancelled } + /// Returns whether `state` is `.finished`. + public var isFinished: Bool { state == .finished } + + // MARK: Progress + + /// Closure type executed when monitoring the upload or download progress of a request. + public typealias ProgressHandler = @Sendable (_ progress: Progress) -> Void + + /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. + public let uploadProgress = Progress(totalUnitCount: 0) + /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. + public let downloadProgress = Progress(totalUnitCount: 0) + /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. + public internal(set) var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { mutableState.uploadProgressHandler } + set { mutableState.uploadProgressHandler = newValue } + } + + /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. + public internal(set) var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { mutableState.downloadProgressHandler } + set { mutableState.downloadProgressHandler = newValue } + } + + // MARK: Redirect Handling + + /// `RedirectHandler` set on the instance. + public internal(set) var redirectHandler: (any RedirectHandler)? { + get { mutableState.redirectHandler } + set { mutableState.redirectHandler = newValue } + } + + // MARK: Cached Response Handling + + /// `CachedResponseHandler` set on the instance. + public internal(set) var cachedResponseHandler: (any CachedResponseHandler)? { + get { mutableState.cachedResponseHandler } + set { mutableState.cachedResponseHandler = newValue } + } + + // MARK: URLCredential + + /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. + public internal(set) var credential: URLCredential? { + get { mutableState.credential } + set { mutableState.credential = newValue } + } + + // MARK: Validators + + /// `Validator` callback closures that store the validation calls enqueued. + let validators = Protected<[@Sendable () -> Void]>([]) + + // MARK: URLRequests + + /// All `URLRequest`s created on behalf of the `Request`, including original and adapted requests. + public var requests: [URLRequest] { mutableState.requests } + /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. + public var firstRequest: URLRequest? { requests.first } + /// Last `URLRequest` created on behalf of the `Request`. + public var lastRequest: URLRequest? { requests.last } + /// Current `URLRequest` created on behalf of the `Request`. + public var request: URLRequest? { lastRequest } + + /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from + /// `requests` due to `URLSession` manipulation. + public var performedRequests: [URLRequest] { mutableState.read { $0.tasks.compactMap(\.currentRequest) } } + + // MARK: HTTPURLResponse + + /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the + /// last `URLSessionTask`. + public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } + + // MARK: Tasks + + /// All `URLSessionTask`s created on behalf of the `Request`. + public var tasks: [URLSessionTask] { mutableState.tasks } + /// First `URLSessionTask` created on behalf of the `Request`. + public var firstTask: URLSessionTask? { tasks.first } + /// Last `URLSessionTask` created on behalf of the `Request`. + public var lastTask: URLSessionTask? { tasks.last } + /// Current `URLSessionTask` created on behalf of the `Request`. + public var task: URLSessionTask? { lastTask } + + // MARK: Metrics + + /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. + public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics } + /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } + /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } + /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var metrics: URLSessionTaskMetrics? { lastMetrics } + + // MARK: Retry Count + + /// Number of times the `Request` has been retried. + public var retryCount: Int { mutableState.retryCount } + + // MARK: Error + + /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. + public internal(set) var error: AFError? { + get { mutableState.error } + set { mutableState.error = newValue } + } + + /// Default initializer for the `Request` superclass. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: (any EventMonitor)?, + interceptor: (any RequestInterceptor)?, + delegate: any RequestDelegate) { + self.id = id + self.underlyingQueue = underlyingQueue + self.serializationQueue = serializationQueue + self.eventMonitor = eventMonitor + self.interceptor = interceptor + self.delegate = delegate + } + + // MARK: - Internal Event API + + // All API must be called from underlyingQueue. + + /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, + /// the `URLRequest` will be adapted before being issued. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateInitialURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.requests.append(request) } + + eventMonitor?.request(self, didCreateInitialURLRequest: request) + } + + /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. + /// + /// - Note: Triggers retry. + /// + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. + /// + /// - Parameters: + /// - initialRequest: The `URLRequest` that was adapted. + /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. + func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.requests.append(adaptedRequest) } + + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. + /// + /// - Note: Triggers retry. + /// + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Final `URLRequest` has been created for the instance. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.read { state in + guard let urlRequestHandler = state.urlRequestHandler else { return } + + urlRequestHandler.queue.async { urlRequestHandler.handler(request) } + } + + eventMonitor?.request(self, didCreateURLRequest: request) + + callCURLHandlerIfNecessary() + } + + /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. + private func callCURLHandlerIfNecessary() { + mutableState.write { mutableState in + guard let cURLHandler = mutableState.cURLHandler else { return } + + cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } + + mutableState.cURLHandler = nil + } + } + + /// Called when a `URLSessionTask` is created on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` created. + func didCreateTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { state in + state.tasks.append(task) + + guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } + + urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } + } + + eventMonitor?.request(self, didCreateTask: task) + } + + /// Called when resumption is completed. + func didResume() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidResume(self) + } + + /// Called when a `URLSessionTask` is resumed on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` resumed. + func didResumeTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didResumeTask: task) + } + + /// Called when suspension is completed. + func didSuspend() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidSuspend(self) + } + + /// Called when a `URLSessionTask` is suspended on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` suspended. + func didSuspendTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didSuspendTask: task) + } + + /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. + func didCancel() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { mutableState in + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + + eventMonitor?.requestDidCancel(self) + } + + /// Called when a `URLSessionTask` is cancelled on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` cancelled. + func didCancelTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didCancelTask: task) + } + + /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. + /// + /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. + func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.metrics.append(metrics) } + + eventMonitor?.request(self, didGatherMetrics: metrics) + } + + /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which failed. + /// - error: The early failure `AFError`. + func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + // Task will still complete, so didCompleteTask(_:with:) will handle retry. + eventMonitor?.request(self, didFailTask: task, earlyWithError: error) + } + + /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. + /// + /// - Note: Response validation is synchronously triggered in this step. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which completed. + /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this + /// value is ignored. + func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = self.error ?? error + + let validators = validators.read { $0 } + validators.forEach { $0() } + + eventMonitor?.request(self, didCompleteTask: task, with: error) + + retryOrFinish(error: self.error) + } + + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.retryCount += 1 } + + reset() + + eventMonitor?.requestIsRetrying(self) + } + + /// Called to determine whether retry will be triggered for the particular error, or whether the instance should + /// call `finish()`. + /// + /// - Parameter error: The possible `AFError` which may trigger retry. + func retryOrFinish(error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !isCancelled, let error, let delegate else { finish(); return } + + delegate.retryResult(for: self, dueTo: error) { retryResult in + switch retryResult { + case .doNotRetry: + self.finish() + case let .doNotRetryWithError(retryError): + self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + + /// Finishes this `Request` and starts the response serializers. + /// + /// - Parameter error: The possible `Error` with which the instance will finish. + func finish(error: AFError? = nil) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !mutableState.isFinishing else { return } + + mutableState.isFinishing = true + + if let error { self.error = error } + + // Start response handlers + processNextResponseSerializer() + + eventMonitor?.requestDidFinish(self) + } + + /// Appends the response serialization closure to the instance. + /// + /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. + /// + /// - Parameter closure: The closure containing the response serialization call. + func appendResponseSerializer(_ closure: @escaping @Sendable () -> Void) { + mutableState.write { mutableState in + mutableState.responseSerializers.append(closure) + + if mutableState.state == .finished { + mutableState.state = .resumed + } + + if mutableState.responseSerializerProcessingFinished { + underlyingQueue.async { self.processNextResponseSerializer() } + } + + if mutableState.state.canTransitionTo(.resumed) { + underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } + } + } + } + + /// Returns the next response serializer closure to execute if there's one left. + /// + /// - Returns: The next response serialization closure, if there is one. + func nextResponseSerializer() -> (@Sendable () -> Void)? { + var responseSerializer: (@Sendable () -> Void)? + + mutableState.write { mutableState in + let responseSerializerIndex = mutableState.responseSerializerCompletions.count + + if responseSerializerIndex < mutableState.responseSerializers.count { + responseSerializer = mutableState.responseSerializers[responseSerializerIndex] + } + } + + return responseSerializer + } + + /// Processes the next response serializer and calls all completions if response serialization is complete. + func processNextResponseSerializer() { + guard let responseSerializer = nextResponseSerializer() else { + // Execute all response serializer completions and clear them + var completions: [@Sendable () -> Void] = [] + + mutableState.write { mutableState in + completions = mutableState.responseSerializerCompletions + + // Clear out all response serializers and response serializer completions in mutable state since the + // request is complete. It's important to do this prior to calling the completion closures in case + // the completions call back into the request triggering a re-processing of the response serializers. + // An example of how this can happen is by calling cancel inside a response completion closure. + mutableState.responseSerializers.removeAll() + mutableState.responseSerializerCompletions.removeAll() + + if mutableState.state.canTransitionTo(.finished) { + mutableState.state = .finished + } + + mutableState.responseSerializerProcessingFinished = true + mutableState.isFinishing = false + } + + completions.forEach { $0() } + + // Cleanup the request + cleanup() + + return + } + + serializationQueue.async { responseSerializer() } + } + + /// Notifies the `Request` that the response serializer is complete. + /// + /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers + /// are complete. + func responseSerializerDidComplete(completion: @escaping @Sendable () -> Void) { + mutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() + } + + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil + + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 + + mutableState.write { state in + state.isFinishing = false + state.responseSerializerCompletions = [] + } + } + + /// Called when updating the upload progress. + /// + /// - Parameters: + /// - totalBytesSent: Total bytes sent so far. + /// - totalBytesExpectedToSend: Total bytes expected to send. + func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } + } + + /// Perform a closure on the current `state` while locked. + /// + /// - Parameter perform: The closure to perform. + func withState(perform: (State) -> Void) { + mutableState.withState(perform: perform) + } + + // MARK: Task Creation + + /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. + /// + /// - Parameters: + /// - request: `URLRequest` to use to create the `URLSessionTask`. + /// - session: `URLSession` which creates the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + fatalError("Subclasses must override.") + } + + // MARK: - Public API + + // These APIs are callable from any queue. + + // MARK: State + + /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. + /// + /// - Returns: The instance. + @discardableResult + public func cancel() -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + /// Suspends the instance. + /// + /// - Returns: The instance. + @discardableResult + public func suspend() -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.suspended) else { return } + + mutableState.state = .suspended + + underlyingQueue.async { self.didSuspend() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.suspend() + underlyingQueue.async { self.didSuspendTask(task) } + } + + return self + } + + /// Resumes the instance. + /// + /// - Returns: The instance. + @discardableResult + public func resume() -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.resumed) else { return } + + mutableState.state = .resumed + + underlyingQueue.async { self.didResume() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.resume() + underlyingQueue.async { self.didResumeTask(task) } + } + + return self + } + + // MARK: - Closure API + + /// Associates a credential using the provided values with the instance. + /// + /// - Parameters: + /// - username: The username. + /// - password: The password. + /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { + let credential = URLCredential(user: username, password: password, persistence: persistence) + + return authenticate(with: credential) + } + + /// Associates the provided credential with the instance. + /// + /// - Parameter credential: The `URLCredential`. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(with credential: URLCredential) -> Self { + mutableState.credential = credential + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is read from the server. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + mutableState.downloadProgressHandler = (handler: closure, queue: queue) + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is sent to the server. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + mutableState.uploadProgressHandler = (handler: closure, queue: queue) + + return self + } + + // MARK: Redirects + + /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. + /// + /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `RedirectHandler`. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func redirect(using handler: any RedirectHandler) -> Self { + mutableState.write { mutableState in + precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") + mutableState.redirectHandler = handler + } + + return self + } + + // MARK: Cached Responses + + /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. + /// + /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `CachedResponseHandler`. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func cacheResponse(using handler: any CachedResponseHandler) -> Self { + mutableState.write { mutableState in + precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") + mutableState.cachedResponseHandler = handler + } + + return self + } + + // MARK: - Lifetime APIs + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. + /// - handler: Closure to be called when the cURL description is available. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping @Sendable (String) -> Void) -> Self { + mutableState.write { mutableState in + if mutableState.requests.last != nil { + queue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = (queue, handler) + } + } + + return self + } + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's + /// `underlyingQueue` by default. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func cURLDescription(calling handler: @escaping @Sendable (String) -> Void) -> Self { + cURLDescription(on: underlyingQueue, calling: handler) + + return self + } + + /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. + /// + /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when a `URLRequest` is available. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping @Sendable (URLRequest) -> Void) -> Self { + mutableState.write { state in + if let request = state.requests.last { + queue.async { handler(request) } + } + + state.urlRequestHandler = (queue, handler) + } + + return self + } + + /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. + /// + /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It + /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. + /// Additionally, this closure may be called multiple times if the instance is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when the `URLSessionTask` is available. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping @Sendable (URLSessionTask) -> Void) -> Self { + mutableState.write { state in + if let task = state.tasks.last { + queue.async { handler(task) } + } + + state.urlSessionTaskHandler = (queue, handler) + } + + return self + } + + // MARK: Cleanup + + /// Adds a `finishHandler` closure to be called when the request completes. + /// + /// - Parameter closure: Closure to be called when the request finishes. + func onFinish(perform finishHandler: @escaping () -> Void) { + guard !isFinished else { finishHandler(); return } + + mutableState.write { state in + state.finishHandlers.append(finishHandler) + } + } + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + let handlers = mutableState.finishHandlers + handlers.forEach { $0() } + mutableState.write { state in + state.finishHandlers.removeAll() + } + + delegate?.cleanup(after: self) + } +} + +extension Request { + /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`. + public enum ResponseDisposition: Sendable { + /// Allow the request to continue normally. + case allow + /// Cancel the request, similar to calling `cancel()`. + case cancel + + var sessionDisposition: URLSession.ResponseDisposition { + switch self { + case .allow: .allow + case .cancel: .cancel + } + } + } +} + +// MARK: - Protocol Conformances + +extension Request: Equatable { + public static func ==(lhs: Request, rhs: Request) -> Bool { + lhs.id == rhs.id + } +} + +extension Request: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } +} + +extension Request: CustomStringConvertible { + /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been + /// created, as well as the response status code, if a response has been received. + public var description: String { + guard let request = performedRequests.last ?? lastRequest, + let url = request.url, + let method = request.httpMethod else { return "No request created yet." } + + let requestDescription = "\(method) \(url.absoluteString)" + + return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription + } +} + +extension Request { + /// cURL representation of the instance. + /// + /// - Returns: The cURL equivalent of the instance. + public func cURLDescription() -> String { + guard + let request = lastRequest, + let url = request.url, + let host = url.host, + let method = request.httpMethod else { return "$ curl command could not be created" } + + var components = ["$ curl -v"] + + components.append("-X \(method)") + + if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace(host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { + if + let cookieStorage = configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { + let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") + + components.append("-b \"\(allCookies)\"") + } + } + + var headers = HTTPHeaders() + + if let sessionHeaders = delegate?.sessionConfiguration.headers { + for header in sessionHeaders where header.name != "Cookie" { + headers[header.name] = header.value + } + } + + for header in request.headers where header.name != "Cookie" { + headers[header.name] = header.value + } + + for header in headers { + let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") + components.append("-H \"\(header.name): \(escapedValue)\"") + } + + if let httpBodyData = request.httpBody { + let httpBody = String(decoding: httpBodyData, as: UTF8.self) + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. +public protocol RequestDelegate: AnyObject, Sendable { + /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. + var sessionConfiguration: URLSessionConfiguration { get } + + /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. + var startImmediately: Bool { get } + + /// Notifies the delegate the `Request` has reached a point where it needs cleanup. + /// + /// - Parameter request: The `Request` to cleanup after. + func cleanup(after request: Request) + + /// Asynchronously ask the delegate whether a `Request` will be retried. + /// + /// - Parameters: + /// - request: `Request` which failed. + /// - error: `Error` which produced the failure. + /// - completion: Closure taking the `RetryResult` for evaluation. + func retryResult(for request: Request, dueTo error: AFError, completion: @escaping @Sendable (RetryResult) -> Void) + + /// Asynchronously retry the `Request`. + /// + /// - Parameters: + /// - request: `Request` which will be retried. + /// - timeDelay: `TimeInterval` after which the retry will be triggered. + func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/RequestTaskMap.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/RequestTaskMap.swift new file mode 100644 index 00000000..e49e564a --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/RequestTaskMap.swift @@ -0,0 +1,150 @@ +// +// RequestTaskMap.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s. +struct RequestTaskMap { + private typealias Events = (completed: Bool, metricsGathered: Bool) + + private var tasksToRequests: [URLSessionTask: Request] + private var requestsToTasks: [Request: URLSessionTask] + private var taskEvents: [URLSessionTask: Events] + + var requests: [Request] { + Array(tasksToRequests.values) + } + + init(tasksToRequests: [URLSessionTask: Request] = [:], + requestsToTasks: [Request: URLSessionTask] = [:], + taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { + self.tasksToRequests = tasksToRequests + self.requestsToTasks = requestsToTasks + self.taskEvents = taskEvents + } + + subscript(_ request: Request) -> URLSessionTask? { + get { requestsToTasks[request] } + set { + guard let newValue else { + guard let task = requestsToTasks[request] else { + fatalError("RequestTaskMap consistency error: no task corresponding to request found.") + } + + requestsToTasks.removeValue(forKey: request) + tasksToRequests.removeValue(forKey: task) + taskEvents.removeValue(forKey: task) + + return + } + + requestsToTasks[request] = newValue + tasksToRequests[newValue] = request + taskEvents[newValue] = (completed: false, metricsGathered: false) + } + } + + subscript(_ task: URLSessionTask) -> Request? { + get { tasksToRequests[task] } + set { + guard let newValue else { + guard let request = tasksToRequests[task] else { + fatalError("RequestTaskMap consistency error: no request corresponding to task found.") + } + + tasksToRequests.removeValue(forKey: task) + requestsToTasks.removeValue(forKey: request) + taskEvents.removeValue(forKey: task) + + return + } + + tasksToRequests[task] = newValue + requestsToTasks[newValue] = task + taskEvents[task] = (completed: false, metricsGathered: false) + } + } + + var count: Int { + precondition(tasksToRequests.count == requestsToTasks.count, + "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") + + return tasksToRequests.count + } + + var eventCount: Int { + precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") + + return taskEvents.count + } + + var isEmpty: Bool { + precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, + "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") + + return tasksToRequests.isEmpty + } + + var isEventsEmpty: Bool { + precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") + + return taskEvents.isEmpty + } + + mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") + case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false + case (true, false): self[task] = nil; return true + } + } + + mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") + // swift-corelibs-foundation doesn't gather metrics, so unconditionally remove the reference and return true. + #if canImport(FoundationNetworking) + default: self[task] = nil; return true + #else + case (false, false): + if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) { + taskEvents[task] = (completed: true, metricsGathered: false); return false + } else { + // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true. + self[task] = nil; return true + } + case (false, true): + self[task] = nil; return true + #endif + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Response.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Response.swift new file mode 100644 index 00000000..57486f6d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Response.swift @@ -0,0 +1,453 @@ +// +// Response.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDataResponse = DataResponse +/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDownloadResponse = DownloadResponse + +/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. +public struct DataResponse: Sendable where Success: Sendable, Failure: Sendable { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - data: The `Data` returned by the server. + /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.data = data + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes (if available) a summary + /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the + /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and + /// the `Result` of serialization. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + + let responseDescription = response.map { response in + let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers) + + return """ + \(DebugDescription.description(of: response)) + \(responseBodyDescription.indentingNewlines()) + """ + } ?? "[Response]: None" + + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse: Sendable where Success: Sendable, Failure: Sendable { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The final destination URL of the data returned from the server after it is moved. + public let fileURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - fileURL: The final destination URL of the data returned from the server after it is moved. + /// - resumeData: The resume `Data` generated if the request was cancelled. + /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + resumeData: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.fileURL = fileURL + self.resumeData = resumeData + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization + /// actions, and the response serialization result. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None" + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [File URL]: \(fileURL?.path ?? "None") + [Resume Data]: \(resumeDataDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +private enum DebugDescription { + static func description(of request: URLRequest) -> String { + let requestSummary = "\(request.httpMethod!) \(request)" + let requestHeadersDescription = DebugDescription.description(for: request.headers) + let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers) + + return """ + [Request]: \(requestSummary) + \(requestHeadersDescription.indentingNewlines()) + \(requestBodyDescription.indentingNewlines()) + """ + } + + static func description(of response: HTTPURLResponse) -> String { + """ + [Response]: + [Status Code]: \(response.statusCode) + \(DebugDescription.description(for: response.headers).indentingNewlines()) + """ + } + + static func description(for headers: HTTPHeaders) -> String { + guard !headers.isEmpty else { return "[Headers]: None" } + + let headerDescription = "\(headers.sorted())".indentingNewlines() + return """ + [Headers]: + \(headerDescription) + """ + } + + static func description(for data: Data?, + headers: HTTPHeaders, + allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"], + maximumLength: Int = 100_000) -> String { + guard let data, !data.isEmpty else { return "[Body]: None" } + + guard + data.count <= maximumLength, + printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true) + else { return "[Body]: \(data.count) bytes" } + + return """ + [Body]: + \(String(decoding: data, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + .indentingNewlines()) + """ + } +} + +extension String { + fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String { + let spaces = String(repeating: " ", count: spaceCount) + return replacingOccurrences(of: "\n", with: "\n\(spaces)") + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Session.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Session.swift new file mode 100644 index 00000000..341fd759 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/Session.swift @@ -0,0 +1,1349 @@ +// +// Session.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common +/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response +/// cache handling. +open class Session: @unchecked Sendable { + /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. + public static let `default` = Session() + + /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's + /// `delegate` handles `URLSessionDelegate` callbacks. + /// + /// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will + /// break internal Alamofire logic that tracks those tasks. + /// + public let session: URLSession + /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. + public let delegate: SessionDelegate + /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. + public let rootQueue: DispatchQueue + /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. + public let startRequestsImmediately: Bool + /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its + /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile + /// and test before introducing an additional queue. + public let requestQueue: DispatchQueue + /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this + /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined + /// to be a bottleneck. Always profile and test before introducing an additional queue. + public let serializationQueue: DispatchQueue + /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a + /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. + public let interceptor: (any RequestInterceptor)? + /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. + public let serverTrustManager: ServerTrustManager? + /// `RedirectHandler` instance used to provide customization for request redirection. + public let redirectHandler: (any RedirectHandler)? + /// `CachedResponseHandler` instance used to provide customization of cached response handling. + public let cachedResponseHandler: (any CachedResponseHandler)? + /// `CompositeEventMonitor` used to compose any passed `EventMonitor`s. + public let eventMonitor: CompositeEventMonitor + /// `EventMonitor`s included in all instances unless overwritten. `[AlamofireNotifications()]` by default. + @available(*, deprecated, message: "Use [AlamofireNotifications()] directly.") + public let defaultEventMonitors: [any EventMonitor] = [AlamofireNotifications()] + + /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. + var requestTaskMap = RequestTaskMap() + /// `Set` of currently active `Request`s. + var activeRequests: Set = [] + /// Completion events awaiting `URLSessionTaskMetrics`. + var waitingCompletions: [URLSessionTask: () -> Void] = [:] + + /// Creates a `Session` from a `URLSession` and other parameters. + /// + /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and + /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. + /// + /// - Parameters: + /// - session: Underlying `URLSession` for this instance. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: `EventMonitor`s used by the instance. `[AlamofireNotifications()]` by default. + public init(session: URLSession, + delegate: SessionDelegate, + rootQueue: DispatchQueue, + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: (any RequestInterceptor)? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: (any RedirectHandler)? = nil, + cachedResponseHandler: (any CachedResponseHandler)? = nil, + eventMonitors: [any EventMonitor] = [AlamofireNotifications()]) { + precondition(session.configuration.identifier == nil, + "Alamofire does not support background URLSessionConfigurations.") + precondition(session.delegateQueue.underlyingQueue === rootQueue, + "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") + + self.session = session + self.delegate = delegate + self.rootQueue = rootQueue + self.startRequestsImmediately = startRequestsImmediately + self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) + self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) + self.interceptor = interceptor + self.serverTrustManager = serverTrustManager + self.redirectHandler = redirectHandler + self.cachedResponseHandler = cachedResponseHandler + eventMonitor = CompositeEventMonitor(monitors: eventMonitors) + delegate.eventMonitor = eventMonitor + delegate.stateProvider = self + } + + /// Creates a `Session` from a `URLSessionConfiguration`. + /// + /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its + /// `delegateQueue`, and is the recommended initializer for most uses. + /// + /// - Parameters: + /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes + /// to this value after being passed to this initializer will have no effect. + /// `URLSessionConfiguration.af.default` by default. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. `SessionDelegate()` by default. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: `EventMonitor`s used by the instance. `[AlamofireNotifications()]` by default. + public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, + delegate: SessionDelegate = SessionDelegate(), + rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: (any RequestInterceptor)? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: (any RedirectHandler)? = nil, + cachedResponseHandler: (any CachedResponseHandler)? = nil, + eventMonitors: [any EventMonitor] = [AlamofireNotifications()]) { + precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") + + // Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe. + let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label, + target: rootQueue) + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: serialRootQueue, + startRequestsImmediately: startRequestsImmediately, + requestQueue: requestQueue, + serializationQueue: serializationQueue, + interceptor: interceptor, + serverTrustManager: serverTrustManager, + redirectHandler: redirectHandler, + cachedResponseHandler: cachedResponseHandler, + eventMonitors: eventMonitors) + } + + deinit { + finishRequestsForDeinit() + session.invalidateAndCancel() + } + + // MARK: - All Requests API + + /// Perform an action on all active `Request`s. + /// + /// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and + /// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`, + /// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any + /// additional work should be performed on another queue. + /// + /// - Parameters: + /// - action: Closure to perform with all `Request`s. + public func withAllRequests(perform action: @escaping @Sendable (Set) -> Void) { + rootQueue.async { + action(self.activeRequests) + } + } + + /// Cancel all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled + /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to + /// completion when cancelled. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. + /// - completion: Closure to be called when all `Request`s have been cancelled. + public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (@Sendable () -> Void)? = nil) { + withAllRequests { requests in + requests.forEach { $0.cancel() } + queue.async { + completion?() + } + } + } + + // MARK: - DataRequest + + /// Closure which provides a `URLRequest` for mutation. + public typealias RequestModifier = @Sendable (inout URLRequest) throws -> Void + + struct RequestConvertible: URLRequestConvertible { + let url: any URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoding: any ParameterEncoding + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try encoding.encode(request, with: parameters) + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncoding.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: any URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: any ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + struct RequestEncodableConvertible: URLRequestConvertible { + let url: any URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoder: any ParameterEncoder + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try parameters.map { try encoder.encode($0, into: request) } ?? request + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: any URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: any ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: any URLRequestConvertible, interceptor: (any RequestInterceptor)? = nil) -> DataRequest { + let request = DataRequest(convertible: convertible, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DataStreamRequest + + /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the + /// `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: any URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: any ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: any URLConvertible, + method: HTTPMethod = .get, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: Empty?.none, + encoder: URLEncodedFormParameterEncoder.default, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// + /// - Returns: The created `DataStreamRequest`. + open func streamRequest(_ convertible: any URLRequestConvertible, + automaticallyCancelOnStreamError: Bool = false, + interceptor: (any RequestInterceptor)? = nil) -> DataStreamRequest { + let request = DataStreamRequest(convertible: convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + #if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(WebSocket) open func webSocketRequest( + to url: any URLConvertible, + configuration: WebSocketRequest.Configuration = .default, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil + ) -> WebSocketRequest { + webSocketRequest( + to: url, + configuration: configuration, + parameters: Empty?.none, + encoder: URLEncodedFormParameterEncoder.default, + headers: headers, + interceptor: interceptor, + requestModifier: requestModifier + ) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(WebSocket) open func webSocketRequest( + to url: any URLConvertible, + configuration: WebSocketRequest.Configuration = .default, + parameters: Parameters? = nil, + encoder: any ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil + ) -> WebSocketRequest where Parameters: Encodable & Sendable { + let convertible = RequestEncodableConvertible(url: url, + method: .get, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + let request = WebSocketRequest(convertible: convertible, + configuration: configuration, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(WebSocket) open func webSocketRequest(performing convertible: any URLRequestConvertible, + configuration: WebSocketRequest.Configuration = .default, + interceptor: (any RequestInterceptor)? = nil) -> WebSocketRequest { + let request = WebSocketRequest(convertible: convertible, + configuration: configuration, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + #endif + + // MARK: - DownloadRequest + + /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and + /// `Destination`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncoding.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: any URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: any ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and + /// a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncodedFormParameterEncoder.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: any URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: any ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: any URLRequestConvertible, + interceptor: (any RequestInterceptor)? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .request(convertible), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as + /// well as a `RequestInterceptor`, and a `Destination`. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. The file will not be deleted until the system purges the temporary files. + /// + /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), + /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` + /// generation logic where the data is written incorrectly and will always fail to resume the download. For more + /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). + /// + /// - Parameters: + /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(resumingWith data: Data, + interceptor: (any RequestInterceptor)? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .resumeData(data), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + // MARK: - UploadRequest + + struct ParameterlessRequestConvertible: URLRequestConvertible { + let url: any URLConvertible + let method: HTTPMethod + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return request + } + } + + struct Upload: UploadConvertible { + let request: any URLRequestConvertible + let uploadable: any UploadableConvertible + + func createUploadable() throws -> UploadRequest.Uploadable { + try uploadable.createUploadable() + } + + func asURLRequest() throws -> URLRequest { + try request.asURLRequest() + } + } + + // MARK: Data + + /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + to convertible: any URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + with convertible: any URLRequestConvertible, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: File + + /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided + /// components and `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + to convertible: any URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + with convertible: any URLRequestConvertible, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + to convertible: any URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + with convertible: any URLRequestConvertible, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: MultipartFormData + + /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided + /// `URLRequest` components and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: any URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: convertible, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` + /// value, and a `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + with request: any URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components + /// and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + to url: any URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: convertible, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` + /// value and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + with request: any URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: (any RequestInterceptor)? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: request, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: - Internal API + + // MARK: Uploadable + + func upload(_ uploadable: UploadRequest.Uploadable, + with convertible: any URLRequestConvertible, + interceptor: (any RequestInterceptor)?, + fileManager: FileManager) -> UploadRequest { + let uploadable = Upload(request: convertible, uploadable: uploadable) + + return upload(uploadable, interceptor: interceptor, fileManager: fileManager) + } + + func upload(_ upload: any UploadConvertible, interceptor: (any RequestInterceptor)?, fileManager: FileManager) -> UploadRequest { + let request = UploadRequest(convertible: upload, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + fileManager: fileManager, + delegate: self) + + perform(request) + + return request + } + + // MARK: Perform + + /// Starts performing the provided `Request`. + /// + /// - Parameter request: The `Request` to perform. + func perform(_ request: Request) { + rootQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + self.requestQueue.async { + // Leaf types must come first, otherwise they will cast as their superclass. + switch request { + case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship. + case let r as DataRequest: self.performDataRequest(r) + case let r as DownloadRequest: self.performDownloadRequest(r) + case let r as DataStreamRequest: self.performDataStreamRequest(r) + default: + #if canImport(Darwin) && !canImport(FoundationNetworking) + if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *), + let request = request as? WebSocketRequest { + self.performWebSocketRequest(request) + } else { + fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + } + #else + fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + #endif + } + } + } + } + + func performDataRequest(_ request: DataRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + func performDataStreamRequest(_ request: DataStreamRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + #if canImport(Darwin) && !canImport(FoundationNetworking) + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + func performWebSocketRequest(_ request: WebSocketRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + #endif + + func performUploadRequest(_ request: UploadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) { + do { + let uploadable = try request.upload.createUploadable() + self.rootQueue.async { request.didCreateUploadable(uploadable) } + return true + } catch { + self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } + return false + } + } + } + + func performDownloadRequest(_ request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + switch request.downloadable { + case let .request(convertible): + performSetupOperations(for: request, convertible: convertible) + case let .resumeData(resumeData): + rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } + } + } + + func performSetupOperations(for request: Request, + convertible: any URLRequestConvertible, + shouldCreateTask: @escaping @Sendable () -> Bool = { true }) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + let initialRequest: URLRequest + + do { + initialRequest = try convertible.asURLRequest() + try initialRequest.validate() + } catch { + rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } + return + } + + rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } + + guard !request.isCancelled else { return } + + guard let adapter = adapter(for: request) else { + guard shouldCreateTask() else { return } + rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } + return + } + + let adapterState = RequestAdapterState(requestID: request.id, session: self) + + adapter.adapt(initialRequest, using: adapterState) { result in + do { + let adaptedRequest = try result.get() + try adaptedRequest.validate() + + self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) } + + guard shouldCreateTask() else { return } + + self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) } + } catch { + self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } + } + } + } + + // MARK: - Task Handling + + func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.didCreateURLRequest(urlRequest) + + guard !request.isCancelled else { return } + + let task = request.task(for: urlRequest, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + guard !request.isCancelled else { return } + + let task = request.task(forResumeData: data, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func updateStatesForTask(_ task: URLSessionTask, request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.withState { state in + switch state { + case .initialized, .finished: + // Do nothing. + break + case .resumed: + task.resume() + rootQueue.async { request.didResumeTask(task) } + case .suspended: + task.suspend() + rootQueue.async { request.didSuspendTask(task) } + case .cancelled: + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + rootQueue.async { request.didCancelTask(task) } + } + } + } + + // MARK: - Adapters and Retriers + + func adapter(for request: Request) -> (any RequestAdapter)? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + Interceptor(adapters: [requestInterceptor, sessionInterceptor]) + } else { + request.interceptor ?? interceptor + } + } + + func retrier(for request: Request) -> (any RequestRetrier)? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + Interceptor(retriers: [requestInterceptor, sessionInterceptor]) + } else { + request.interceptor ?? interceptor + } + } + + // MARK: - Invalidation + + func finishRequestsForDeinit() { + for request in requestTaskMap.requests { + rootQueue.async { + request.finish(error: AFError.sessionDeinitialized) + } + } + } +} + +// MARK: - RequestDelegate + +extension Session: RequestDelegate { + public var sessionConfiguration: URLSessionConfiguration { + session.configuration + } + + public var startImmediately: Bool { startRequestsImmediately } + + public func cleanup(after request: Request) { + activeRequests.remove(request) + } + + public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping @Sendable (RetryResult) -> Void) { + guard let retrier = retrier(for: request) else { + rootQueue.async { completion(.doNotRetry) } + return + } + + retrier.retry(request, for: self, dueTo: error) { retryResult in + self.rootQueue.async { + guard let retryResultError = retryResult.error else { completion(retryResult); return } + + let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) + completion(.doNotRetryWithError(retryError)) + } + } + } + + public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { + rootQueue.async { + let retry: @Sendable () -> Void = { + guard !request.isCancelled else { return } + + request.prepareForRetry() + self.perform(request) + } + + if let retryDelay = timeDelay { + self.rootQueue.after(retryDelay) { retry() } + } else { + retry() + } + } + } +} + +// MARK: - SessionStateProvider + +extension Session: SessionStateProvider { + func request(for task: URLSessionTask) -> Request? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task] + } + + func didGatherMetricsForTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) + + if didDisassociate { + waitingCompletions[task]?() + waitingCompletions[task] = nil + } + } + + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) + + if didDisassociate { + completion() + } else { + waitingCompletions[task] = completion + } + } + + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task]?.credential ?? + session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) + } + + func cancelRequestsForSessionInvalidation(with error: (any Error)?) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/SessionDelegate.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/SessionDelegate.swift new file mode 100644 index 00000000..1d120e66 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/SessionDelegate.swift @@ -0,0 +1,387 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. +open class SessionDelegate: NSObject, @unchecked Sendable { + private let fileManager: FileManager + + weak var stateProvider: (any SessionStateProvider)? + var eventMonitor: (any EventMonitor)? + + /// Creates an instance from the given `FileManager`. + /// + /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. + /// `.default` by default. + public init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + /// Internal method to find and cast requests while maintaining some integrity checking. + /// + /// - Parameters: + /// - task: The `URLSessionTask` for which to find the associated `Request`. + /// - type: The `Request` subclass type to cast any `Request` associate with `task`. + func request(for task: URLSessionTask, as type: R.Type) -> R? { + guard let provider = stateProvider else { + assertionFailure("StateProvider is nil for task \(task.taskIdentifier).") + return nil + } + + return provider.request(for: task) as? R + } +} + +/// Type which provides various `Session` state values. +protocol SessionStateProvider: AnyObject, Sendable { + var serverTrustManager: ServerTrustManager? { get } + var redirectHandler: (any RedirectHandler)? { get } + var cachedResponseHandler: (any CachedResponseHandler)? { get } + + func request(for task: URLSessionTask) -> Request? + func didGatherMetricsForTask(_ task: URLSessionTask) + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? + func cancelRequestsForSessionInvalidation(with error: (any Error)?) +} + +// MARK: URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) + + stateProvider?.cancelRequestsForSessionInvalidation(with: error) + } +} + +// MARK: URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Result of a `URLAuthenticationChallenge` evaluation. + typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + eventMonitor?.urlSession(session, task: task, didReceive: challenge) + + let evaluation: ChallengeEvaluation + switch challenge.protectionSpace.authenticationMethod { + case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, + NSURLAuthenticationMethodNegotiate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #if canImport(Security) + case NSURLAuthenticationMethodServerTrust: + evaluation = attemptServerTrustAuthentication(with: challenge) + case NSURLAuthenticationMethodClientCertificate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #endif + default: + evaluation = (.performDefaultHandling, nil, nil) + } + + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) + } + + completionHandler(evaluation.disposition, evaluation.credential) + } + + #if canImport(Security) + /// Evaluates the server trust `URLAuthenticationChallenge` received. + /// + /// - Parameter challenge: The `URLAuthenticationChallenge`. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { + let host = challenge.protectionSpace.host + + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + return (.performDefaultHandling, nil, nil) + } + + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) + } + + try evaluator.evaluate(trust, forHost: host) + + return (.useCredential, URLCredential(trust: trust), nil) + } catch { + return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) + } + } + #endif + + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. + /// + /// - Parameters: + /// - challenge: The `URLAuthenticationChallenge`. + /// - task: The `URLSessionTask` which received the challenge. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, + belongingTo task: URLSessionTask) -> ChallengeEvaluation { + guard challenge.previousFailureCount == 0 else { + return (.rejectProtectionSpace, nil, nil) + } + + guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { + return (.performDefaultHandling, nil, nil) + } + + return (.useCredential, credential, nil) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + eventMonitor?.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + + stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) + + guard let request = request(for: task, as: UploadRequest.self) else { + assertionFailure("needNewBodyStream did not find UploadRequest.") + completionHandler(nil) + return + } + + completionHandler(request.inputStream()) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) + + if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { + redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) + } else { + completionHandler(request) + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) + + stateProvider?.request(for: task)?.didGatherMetrics(metrics) + + stateProvider?.didGatherMetricsForTask(task) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) { +// NSLog("URLSession: \(session), task: \(task), didCompleteWithError: \(error)") + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) + + let request = stateProvider?.request(for: task) + + stateProvider?.didCompleteTask(task) { + request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) + } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) + } +} + +// MARK: URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: response) + + guard let response = response as? HTTPURLResponse else { completionHandler(.allow); return } + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceiveResponse(response, completionHandler: completionHandler) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceiveResponse(response, completionHandler: completionHandler) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive response") + completionHandler(.allow) + return + } + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceive(data: data) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceive(data: data) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive data") + return + } + } + + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) + + if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { + handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: URLSessionWebSocketDelegate + +#if canImport(Darwin) && !canImport(FoundationNetworking) + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension SessionDelegate: URLSessionWebSocketDelegate { + open func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { + // TODO: Add event monitor method. +// NSLog("URLSession: \(session), webSocketTask: \(webSocketTask), didOpenWithProtocol: \(`protocol` ?? "None")") + guard let request = request(for: webSocketTask, as: WebSocketRequest.self) else { + return + } + + request.didConnect(protocol: `protocol`) + } + + open func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + // TODO: Add event monitor method. +// NSLog("URLSession: \(session), webSocketTask: \(webSocketTask), didCloseWithCode: \(closeCode.rawValue), reason: \(reason ?? Data())") + guard let request = request(for: webSocketTask, as: WebSocketRequest.self) else { + return + } + + // On 2021 OSes and above, empty reason is returned as empty Data rather than nil, so make it nil always. + let reason = (reason?.isEmpty == true) ? nil : reason + request.didDisconnect(closeCode: closeCode, reason: reason) + } +} + +#endif + +// MARK: URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, + totalBytesExpectedToWrite: expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + + guard let request = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + let (destination, options): (URL, DownloadRequest.Options) + if let response = request.response { + (destination, options) = request.destination(location, response) + } else { + // If there's no response this is likely a local file download, so generate the temporary URL directly. + (destination, options) = (DownloadRequest.defaultDestinationURL(location), []) + } + + eventMonitor?.request(request, didCreateDestinationURL: destination) + + do { + if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { + try fileManager.removeItem(at: destination) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try fileManager.moveItem(at: location, to: destination) + + request.didFinishDownloading(using: downloadTask, with: .success(destination)) + } catch { + request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, + source: location, + destination: destination))) + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/URLConvertible+URLRequestConvertible.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 00000000..de62531d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/URLConvertible+URLRequestConvertible.swift @@ -0,0 +1,105 @@ +// +// URLConvertible+URLRequestConvertible.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct +/// `URLRequest`s. +public protocol URLConvertible: Sendable { + /// Returns a `URL` from the conforming instance or throws. + /// + /// - Returns: The `URL` created from the instance. + /// - Throws: Any error thrown while creating the `URL`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. + /// + /// - Returns: The `URL` initialized with `self`. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + + return url + } +} + +extension URL: URLConvertible { + /// Returns `self`. + public func asURL() throws -> URL { self } +} + +extension URLComponents: URLConvertible { + /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. + /// + /// - Returns: The `URL` from the `url` property. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url else { throw AFError.invalidURL(url: self) } + + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s. +public protocol URLRequestConvertible: Sendable { + /// Returns a `URLRequest` or throws if an `Error` was encountered. + /// + /// - Returns: A `URLRequest`. + /// - Throws: Any error thrown while constructing the `URLRequest`. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The `URLRequest` returned by discarding any `Error` encountered. + public var urlRequest: URLRequest? { try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns `self`. + public func asURLRequest() throws -> URLRequest { self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `url`, `method`, and `headers`. + /// + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. + public init(url: any URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + allHTTPHeaderFields = headers?.dictionary + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/UploadRequest.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/UploadRequest.swift new file mode 100644 index 00000000..62c01e83 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/UploadRequest.swift @@ -0,0 +1,174 @@ +// +// UploadRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. +public final class UploadRequest: DataRequest, @unchecked Sendable { + /// Type describing the origin of the upload, whether `Data`, file, or stream. + public enum Uploadable: @unchecked Sendable { // Must be @unchecked Sendable due to InputStream. + /// Upload from the provided `Data` value. + case data(Data) + /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be + /// automatically removed once uploaded. + case file(URL, shouldRemove: Bool) + /// Upload from the provided `InputStream`. + case stream(InputStream) + } + + // MARK: Initial State + + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: any UploadableConvertible + + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager + + // MARK: Mutable State + + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? + + /// Creates an `UploadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form + /// encoded payloads written to disk. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: any UploadConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: (any EventMonitor)?, + interceptor: (any RequestInterceptor)?, + fileManager: FileManager, + delegate: any RequestDelegate) { + upload = convertible + self.fileManager = fileManager + + super.init(id: id, + convertible: convertible, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + /// Called when the `Uploadable` value has been created from the `UploadConvertible`. + /// + /// - Parameter uploadable: The `Uploadable` that was created. + func didCreateUploadable(_ uploadable: Uploadable) { + self.uploadable = uploadable + + eventMonitor?.request(self, didCreateUploadable: uploadable) + } + + /// Called when the `Uploadable` value could not be created. + /// + /// - Parameter error: `AFError` produced by the failure. + func didFailToCreateUploadable(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateUploadableWithError: error) + + retryOrFinish(error: error) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + guard let uploadable else { + fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") + } + + switch uploadable { + case let .data(data): return session.uploadTask(with: request, from: data) + case let .file(url, _): return session.uploadTask(with: request, fromFile: url) + case .stream: return session.uploadTask(withStreamedRequest: request) + } + } + + override func reset() { + // Uploadable must be recreated on every retry. + uploadable = nil + + super.reset() + } + + /// Produces the `InputStream` from `uploadable`, if it can. + /// + /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. + /// + /// - Returns: The `InputStream`. + func inputStream() -> InputStream { + guard let uploadable else { + fatalError("Attempting to access the input stream but the uploadable doesn't exist.") + } + + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") + } + + eventMonitor?.request(self, didProvideInputStream: stream) + + return stream + } + + override public func cleanup() { + defer { super.cleanup() } + + guard + let uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } + + try? fileManager.removeItem(at: url) + } +} + +/// A type that can produce an `UploadRequest.Uploadable` value. +public protocol UploadableConvertible: Sendable { + /// Produces an `UploadRequest.Uploadable` value from the instance. + /// + /// - Returns: The `UploadRequest.Uploadable`. + /// - Throws: Any `Error` produced during creation. + func createUploadable() throws -> UploadRequest.Uploadable +} + +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + self + } +} + +/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. +public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/WebSocketRequest.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/WebSocketRequest.swift new file mode 100644 index 00000000..c835b940 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Core/WebSocketRequest.swift @@ -0,0 +1,568 @@ +// +// WebSocketRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask. + +import Foundation + +/// `Request` subclass which manages a WebSocket connection using `URLSessionWebSocketTask`. +/// +/// - Note: This type is currently experimental. There will be breaking changes before the final public release, +/// especially around adoption of the typed throws feature in Swift 6. Please report any missing features or +/// bugs to https://github.com/Alamofire/Alamofire/issues. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@_spi(WebSocket) public final class WebSocketRequest: Request, @unchecked Sendable { + enum IncomingEvent { + case connected(protocol: String?) + case receivedMessage(URLSessionWebSocketTask.Message) + case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) + case completed(Completion) + } + + public struct Event: Sendable { + public enum Kind: Sendable { + case connected(protocol: String?) + case receivedMessage(Success) + case serializerFailed(Failure) + // Only received if the server disconnects or we cancel with code, not if we do a simple cancel or error. + case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) + case completed(Completion) + } + + weak var socket: WebSocketRequest? + + public let kind: Kind + public var message: Success? { + guard case let .receivedMessage(message) = kind else { return nil } + + return message + } + + init(socket: WebSocketRequest, kind: Kind) { + self.socket = socket + self.kind = kind + } + + public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) { + socket?.close(sending: closeCode, reason: reason) + } + + public func cancel() { + socket?.cancel() + } + + public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping @Sendable (PingResponse) -> Void) { + socket?.sendPing(respondingOn: queue, onResponse: onResponse) + } + } + + public struct Completion: Sendable { + /// Last `URLRequest` issued by the instance. + public let request: URLRequest? + /// Last `HTTPURLResponse` received by the instance. + public let response: HTTPURLResponse? + /// Last `URLSessionTaskMetrics` produced for the instance. + public let metrics: URLSessionTaskMetrics? + /// `AFError` produced for the instance, if any. + public let error: AFError? + } + + public struct Configuration { + public static var `default`: Self { Self() } + + public static func `protocol`(_ protocol: String) -> Self { + Self(protocol: `protocol`) + } + + public static func maximumMessageSize(_ maximumMessageSize: Int) -> Self { + Self(maximumMessageSize: maximumMessageSize) + } + + public static func pingInterval(_ pingInterval: TimeInterval) -> Self { + Self(pingInterval: pingInterval) + } + + public let `protocol`: String? + public let maximumMessageSize: Int + public let pingInterval: TimeInterval? + + init(protocol: String? = nil, maximumMessageSize: Int = 1_048_576, pingInterval: TimeInterval? = nil) { + self.protocol = `protocol` + self.maximumMessageSize = maximumMessageSize + self.pingInterval = pingInterval + } + } + + /// Response to a sent ping. + public enum PingResponse: Sendable { + public struct Pong: Sendable { + let start: Date + let end: Date + let latency: TimeInterval + } + + /// Received a pong with the associated state. + case pong(Pong) + /// Received an error. + case error(any Error) + /// Did not send the ping, the request is cancelled or suspended. + case unsent + } + + struct SocketMutableState { + var enqueuedSends: [(message: URLSessionWebSocketTask.Message, + queue: DispatchQueue, + completionHandler: @Sendable (Result) -> Void)] = [] + var handlers: [(queue: DispatchQueue, handler: (_ event: IncomingEvent) -> Void)] = [] + var pingTimerItem: DispatchWorkItem? + } + + let socketMutableState = Protected(SocketMutableState()) + + var socket: URLSessionWebSocketTask? { + task as? URLSessionWebSocketTask + } + + public let convertible: any URLRequestConvertible + public let configuration: Configuration + + init(id: UUID = UUID(), + convertible: any URLRequestConvertible, + configuration: Configuration, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: (any EventMonitor)?, + interceptor: (any RequestInterceptor)?, + delegate: any RequestDelegate) { + self.convertible = convertible + self.configuration = configuration + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + var copiedRequest = request + let task: URLSessionWebSocketTask + if let `protocol` = configuration.protocol { + copiedRequest.headers.update(.websocketProtocol(`protocol`)) + task = session.webSocketTask(with: copiedRequest) + } else { + task = session.webSocketTask(with: copiedRequest) + } + task.maximumMessageSize = configuration.maximumMessageSize + + return task + } + + override func didCreateTask(_ task: URLSessionTask) { + super.didCreateTask(task) + + guard let webSocketTask = task as? URLSessionWebSocketTask else { + fatalError("Invalid task of type \(task.self) created for WebSocketRequest.") + } + // TODO: What about the any old tasks? Reset their receive? + listen(to: webSocketTask) + + // Empty pending messages. + socketMutableState.write { state in + guard !state.enqueuedSends.isEmpty else { return } + + let sends = state.enqueuedSends + self.underlyingQueue.async { + for send in sends { + webSocketTask.send(send.message) { error in + send.queue.async { + send.completionHandler(Result(value: (), error: error)) + } + } + } + } + + state.enqueuedSends = [] + } + } + + func didClose() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { mutableState in + // Check whether error is cancellation or other websocket closing error. + // If so, remove it. + // Otherwise keep it. + if case let .sessionTaskFailed(error) = mutableState.error, (error as? URLError)?.code == .cancelled { + mutableState.error = nil + } + } + + // TODO: Still issue this event? + eventMonitor?.requestDidCancel(self) + } + + @discardableResult + public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) -> Self { + cancelAutomaticPing() + + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didClose() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + // Cast from state directly, not the property, otherwise the lock is recursive. + (mutableState.tasks.last as? URLSessionWebSocketTask)?.cancel(with: closeCode, reason: reason) + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + @discardableResult + override public func cancel() -> Self { + cancelAutomaticPing() + + return super.cancel() + } + + func didConnect(protocol: String?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + socketMutableState.read { state in + // TODO: Capture HTTPURLResponse here too? + for handler in state.handlers { + // Saved handler calls out to serializationQueue immediately, then to handler's queue. + handler.handler(.connected(protocol: `protocol`)) + } + } + + if let pingInterval = configuration.pingInterval { + startAutomaticPing(every: pingInterval) + } + } + + @preconcurrency + public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping @Sendable (PingResponse) -> Void) { + guard isResumed else { + queue.async { onResponse(.unsent) } + return + } + + let start = Date() + let startTimestamp = ProcessInfo.processInfo.systemUptime + socket?.sendPing { error in + // Calls back on delegate queue / rootQueue / underlyingQueue + if let error { + queue.async { + onResponse(.error(error)) + } + // TODO: What to do with failed ping? Configure for failure, auto retry, or stop pinging? + } else { + let end = Date() + let endTimestamp = ProcessInfo.processInfo.systemUptime + let pong = PingResponse.Pong(start: start, end: end, latency: endTimestamp - startTimestamp) + + queue.async { + onResponse(.pong(pong)) + } + } + } + } + + func startAutomaticPing(every pingInterval: TimeInterval) { + socketMutableState.write { mutableState in + guard isResumed else { + // Defer out of lock. + defer { cancelAutomaticPing() } + return + } + + let item = DispatchWorkItem { [weak self] in + guard let self, isResumed else { return } + + sendPing(respondingOn: underlyingQueue) { response in + guard case .pong = response else { return } + + self.startAutomaticPing(every: pingInterval) + } + } + + mutableState.pingTimerItem = item + underlyingQueue.asyncAfter(deadline: .now() + pingInterval, execute: item) + } + } + + @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) + func startAutomaticPing(every duration: Duration) { + let interval = TimeInterval(duration.components.seconds) + (Double(duration.components.attoseconds) / 1e18) + startAutomaticPing(every: interval) + } + + func cancelAutomaticPing() { + socketMutableState.write { mutableState in + mutableState.pingTimerItem?.cancel() + mutableState.pingTimerItem = nil + } + } + + func didDisconnect(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + cancelAutomaticPing() + socketMutableState.read { state in + for handler in state.handlers { + // Saved handler calls out to serializationQueue immediately, then to handler's queue. + handler.handler(.disconnected(closeCode: closeCode, reason: reason)) + } + } + } + + private func listen(to task: URLSessionWebSocketTask) { + // TODO: Do we care about the cycle while receiving? + task.receive { result in + switch result { + case let .success(message): + self.socketMutableState.read { state in + for handler in state.handlers { + // Saved handler calls out to serializationQueue immediately, then to handler's queue. + handler.handler(.receivedMessage(message)) + } + } + + self.listen(to: task) + case .failure: + // It doesn't seem like any relevant errors are received here, just incorrect garbage, like errors when + // the socket disconnects. + break + } + } + } + + @preconcurrency + @discardableResult + public func streamSerializer( + _ serializer: Serializer, + on queue: DispatchQueue = .main, + handler: @escaping @Sendable (_ event: Event) -> Void + ) -> Self where Serializer: WebSocketMessageSerializer, Serializer.Failure == any Error { + forIncomingEvent(on: queue) { incomingEvent in + let event: Event + switch incomingEvent { + case let .connected(`protocol`): + event = .init(socket: self, kind: .connected(protocol: `protocol`)) + case let .receivedMessage(message): + do { + let serializedMessage = try serializer.decode(message) + event = .init(socket: self, kind: .receivedMessage(serializedMessage)) + } catch { + event = .init(socket: self, kind: .serializerFailed(error)) + } + case let .disconnected(closeCode, reason): + event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason)) + case let .completed(completion): + event = .init(socket: self, kind: .completed(completion)) + } + + queue.async { handler(event) } + } + } + + @preconcurrency + @discardableResult + public func streamDecodableEvents( + _ type: Value.Type = Value.self, + on queue: DispatchQueue = .main, + using decoder: any DataDecoder = JSONDecoder(), + handler: @escaping @Sendable (_ event: Event) -> Void + ) -> Self where Value: Decodable { + streamSerializer(DecodableWebSocketMessageDecoder(decoder: decoder), on: queue, handler: handler) + } + + @preconcurrency + @discardableResult + public func streamDecodable( + _ type: Value.Type = Value.self, + on queue: DispatchQueue = .main, + using decoder: any DataDecoder = JSONDecoder(), + handler: @escaping @Sendable (_ value: Value) -> Void + ) -> Self where Value: Decodable & Sendable { + streamDecodableEvents(Value.self, on: queue) { event in + event.message.map(handler) + } + } + + @preconcurrency + @discardableResult + public func streamMessageEvents( + on queue: DispatchQueue = .main, + handler: @escaping @Sendable (_ event: Event) -> Void + ) -> Self { + forIncomingEvent(on: queue) { incomingEvent in + let event: Event = switch incomingEvent { + case let .connected(`protocol`): + .init(socket: self, kind: .connected(protocol: `protocol`)) + case let .receivedMessage(message): + .init(socket: self, kind: .receivedMessage(message)) + case let .disconnected(closeCode, reason): + .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason)) + case let .completed(completion): + .init(socket: self, kind: .completed(completion)) + } + + queue.async { handler(event) } + } + } + + @preconcurrency + @discardableResult + public func streamMessages( + on queue: DispatchQueue = .main, + handler: @escaping @Sendable (_ message: URLSessionWebSocketTask.Message) -> Void + ) -> Self { + streamMessageEvents(on: queue) { event in + event.message.map(handler) + } + } + + func forIncomingEvent(on queue: DispatchQueue, handler: @escaping @Sendable (IncomingEvent) -> Void) -> Self { + socketMutableState.write { state in + state.handlers.append((queue: queue, handler: { incomingEvent in + self.serializationQueue.async { + handler(incomingEvent) + } + })) + } + + appendResponseSerializer { + self.responseSerializerDidComplete { + self.serializationQueue.async { + handler(.completed(.init(request: self.request, + response: self.response, + metrics: self.metrics, + error: self.error))) + } + } + } + + return self + } + + @preconcurrency + public func send(_ message: URLSessionWebSocketTask.Message, + queue: DispatchQueue = .main, + completionHandler: @escaping @Sendable (Result) -> Void) { + guard !(isCancelled || isFinished) else { return } + + guard let socket else { + // URLSessionWebSocketTask not created yet, enqueue the send. + socketMutableState.write { mutableState in + mutableState.enqueuedSends.append((message, queue, completionHandler)) + } + + return + } + + socket.send(message) { error in + queue.async { + completionHandler(Result(value: (), error: error)) + } + } + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public protocol WebSocketMessageSerializer: Sendable { + associatedtype Output: Sendable + associatedtype Failure: Error = any Error + + func decode(_ message: URLSessionWebSocketTask.Message) throws -> Output +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension WebSocketMessageSerializer { + public static func json( + decoding _: Value.Type = Value.self, + using decoder: JSONDecoder = JSONDecoder() + ) -> DecodableWebSocketMessageDecoder where Self == DecodableWebSocketMessageDecoder { + Self(decoder: decoder) + } + + static var passthrough: PassthroughWebSocketMessageDecoder { + PassthroughWebSocketMessageDecoder() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer { + public typealias Failure = Never + + public func decode(_ message: URLSessionWebSocketTask.Message) -> URLSessionWebSocketTask.Message { + message + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DecodableWebSocketMessageDecoder: WebSocketMessageSerializer { + public enum Error: Swift.Error { + case decoding(any Swift.Error) + case unknownMessage(description: String) + } + + public let decoder: any DataDecoder + + public init(decoder: any DataDecoder) { + self.decoder = decoder + } + + public func decode(_ message: URLSessionWebSocketTask.Message) throws -> Value { + let data: Data + switch message { + case let .data(messageData): + data = messageData + case let .string(string): + data = Data(string.utf8) + @unknown default: + throw Error.unknownMessage(description: String(describing: message)) + } + + do { + return try decoder.decode(Value.self, from: data) + } catch { + throw Error.decoding(error) + } + } +} + +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/DispatchQueue+Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/DispatchQueue+Alamofire.swift new file mode 100644 index 00000000..132ca938 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + /// Execute the provided closure after a `TimeInterval`. + /// + /// - Parameters: + /// - delay: `TimeInterval` to delay execution. + /// - closure: Closure to execute. + func after(_ delay: TimeInterval, execute closure: @escaping @Sendable () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/OperationQueue+Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/OperationQueue+Alamofire.swift new file mode 100644 index 00000000..b06a0ccc --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/OperationQueue+Alamofire.swift @@ -0,0 +1,49 @@ +// +// OperationQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension OperationQueue { + /// Creates an instance using the provided parameters. + /// + /// - Parameters: + /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. + /// - maxConcurrentOperationCount: Maximum concurrent operations. + /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. + /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. + /// - name: Name for the queue. `nil` by default. + /// - startSuspended: Whether the queue starts suspended. `false` by default. + convenience init(qualityOfService: QualityOfService = .default, + maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, + underlyingQueue: DispatchQueue? = nil, + name: String? = nil, + startSuspended: Bool = false) { + self.init() + self.qualityOfService = qualityOfService + self.maxConcurrentOperationCount = maxConcurrentOperationCount + self.underlyingQueue = underlyingQueue + self.name = name + isSuspended = startSuspended + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/Result+Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/Result+Alamofire.swift new file mode 100644 index 00000000..4444db49 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/Result+Alamofire.swift @@ -0,0 +1,120 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFResult = Result + +// MARK: - Internal APIs + +extension Result { + /// Returns whether the instance is `.success`. + var isSuccess: Bool { + guard case .success = self else { return false } + return true + } + + /// Returns whether the instance is `.failure`. + var isFailure: Bool { + !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + var success: Success? { + guard case let .success(value) = self else { return nil } + return value + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + var failure: Failure? { + guard case let .failure(error) = self else { return nil } + return error + } + + /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. + /// + /// - Parameters: + /// - value: A value. + /// - error: An `Error`. + init(value: Success, error: Failure?) { + if let error { + self = .failure(error) + } else { + self = .success(value) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { + switch self { + case let .success(value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case let .failure(error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same success. + func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { + switch self { + case let .failure(error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case let .success(value): + return .success(value) + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/StringEncoding+Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/StringEncoding+Alamofire.swift new file mode 100644 index 00000000..8fa61333 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/StringEncoding+Alamofire.swift @@ -0,0 +1,55 @@ +// +// StringEncoding+Alamofire.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension String.Encoding { + /// Creates an encoding from the IANA charset name. + /// + /// - Notes: These mappings match those [provided by CoreFoundation](https://opensource.apple.com/source/CF/CF-476.18/CFStringUtilities.c.auto.html) + /// + /// - Parameter name: IANA charset name. + init?(ianaCharsetName name: String) { + switch name.lowercased() { + case "utf-8": + self = .utf8 + case "iso-8859-1": + self = .isoLatin1 + case "unicode-1-1", "iso-10646-ucs-2", "utf-16": + self = .utf16 + case "utf-16be": + self = .utf16BigEndian + case "utf-16le": + self = .utf16LittleEndian + case "utf-32": + self = .utf32 + case "utf-32be": + self = .utf32BigEndian + case "utf-32le": + self = .utf32LittleEndian + default: + return nil + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/URLRequest+Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/URLRequest+Alamofire.swift new file mode 100644 index 00000000..ab72fb53 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/URLRequest+Alamofire.swift @@ -0,0 +1,39 @@ +// +// URLRequest+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLRequest { + /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. + public var method: HTTPMethod? { + get { httpMethod.map(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue } + } + + public func validate() throws { + if method == .get, let bodyData = httpBody { + throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/URLSessionConfiguration+Alamofire.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 00000000..292a8fe7 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Extensions/URLSessionConfiguration+Alamofire.swift @@ -0,0 +1,46 @@ +// +// URLSessionConfiguration+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLSessionConfiguration: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: URLSessionConfiguration { + /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default + /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. + public static var `default`: URLSessionConfiguration { + let configuration = URLSessionConfiguration.default + configuration.headers = .default + + return configuration + } + + /// `.ephemeral` configuration with Alamofire's default `Accept-Language`, `Accept-Encoding`, and `User-Agent` + /// headers. + public static var ephemeral: URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.headers = .default + + return configuration + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/AlamofireExtended.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/AlamofireExtended.swift new file mode 100644 index 00000000..280c6de9 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/AlamofireExtended.swift @@ -0,0 +1,61 @@ +// +// AlamofireExtended.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type that acts as a generic extension point for all `AlamofireExtended` types. +public struct AlamofireExtension { + /// Stores the type or meta-type of any extended type. + public private(set) var type: ExtendedType + + /// Create an instance from the provided value. + /// + /// - Parameter type: Instance being extended. + public init(_ type: ExtendedType) { + self.type = type + } +} + +/// Protocol describing the `af` extension points for Alamofire extended types. +public protocol AlamofireExtended { + /// Type being extended. + associatedtype ExtendedType + + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { get set } + /// Instance Alamofire extension point. + var af: AlamofireExtension { get set } +} + +extension AlamofireExtended { + /// Static Alamofire extension point. + public static var af: AlamofireExtension.Type { + get { AlamofireExtension.self } + set {} + } + + /// Instance Alamofire extension point. + public var af: AlamofireExtension { + get { AlamofireExtension(self) } + set {} + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/AuthenticationInterceptor.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/AuthenticationInterceptor.swift new file mode 100644 index 00000000..44900f90 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/AuthenticationInterceptor.swift @@ -0,0 +1,402 @@ +// +// AuthenticationInterceptor.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s. +/// +/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to +/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes +/// which will then require a refresh of the credential using the refresh token to generate a new access token. +public protocol AuthenticationCredential { + /// Whether the credential requires a refresh. This property should always return `true` when the credential is + /// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or + /// minutes depending on the expiration window of the credential. + /// + /// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the + /// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed + /// around backend services. + var requiresRefresh: Bool { get } +} + +// MARK: - + +/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an +/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required. +public protocol Authenticator: AnyObject, Sendable { + /// The type of credential associated with the `Authenticator` instance. + associatedtype Credential: AuthenticationCredential & Sendable + + /// Applies the `Credential` to the `URLRequest`. + /// + /// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer + /// token to the `Authorization` header. + /// + /// - Parameters: + /// - credential: The `Credential`. + /// - urlRequest: The `URLRequest`. + func apply(_ credential: Credential, to urlRequest: inout URLRequest) + + /// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete. + /// + /// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to + /// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also + /// be triggered by a failed `Request` where the authentication server denied access due to an expired or + /// invalidated access token. + /// + /// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new + /// `Credential` using the authentication service. Once complete, the `completion` closure should be called with + /// the new `Credential`, or the error that occurred. + /// + /// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401), + /// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases, + /// you will need to reauthenticate the user with their username / password. + /// + /// Please note, these are just general examples of common use cases. They are not meant to solve your specific + /// authentication server challenges. Please work with your authentication server team to ensure your + /// `Authenticator` logic matches their expectations. + /// + /// - Parameters: + /// - credential: The `Credential` to refresh. + /// - session: The `Session` requiring the refresh. + /// - completion: The closure to be executed once the refresh is complete. + func refresh(_ credential: Credential, for session: Session, completion: @escaping @Sendable (Result) -> Void) + + /// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you + /// will need to work with your authentication server team to understand how to identify when this occurs. + /// + /// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the + /// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication + /// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred. + /// + /// It is very important to understand how your authentication server works to be able to implement this correctly. + /// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream + /// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer + /// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication + /// server is actually the layer rejecting the request. Again, work with your authentication server team to understand + /// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - response: The `HTTPURLResponse`. + /// - error: The `Error`. + /// + /// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise. + func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: any Error) -> Bool + + /// Determines whether the `URLRequest` is authenticated with the `Credential`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then + /// read on. + /// + /// When an authentication server can invalidate credentials, it means that you may have a non-expired credential + /// that appears to be valid, but will be rejected by the authentication server when used. Generally when this + /// happens, a number of requests are all sent when the application is foregrounded, and all of them will be + /// rejected by the authentication server in the order they are received. The first failed request will trigger a + /// refresh internally, which will update the credential, and then retry all the queued requests with the new + /// credential. However, it is possible that some of the original requests will not return from the authentication + /// server until the refresh has completed. This is where this method comes in. + /// + /// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the + /// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an + /// additional refresh. If it hasn't refreshed, then we need to refresh. + /// + /// Now that it is understood how the result of this method is used in the refresh lifecycle, let's walk through how + /// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that + /// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the + /// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we + /// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token + /// did not match the access token, then you should return `false`. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - credential: The `Credential`. + /// + /// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise. + func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool +} + +// MARK: - + +/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are +/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within +/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases. +public enum AuthenticationError: Error { + /// The credential was missing so the request could not be authenticated. + case missingCredential + /// The credential was refreshed too many times within the `RefreshWindow`. + case excessiveRefresh +} + +// MARK: - + +/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests. +/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh. +public final class AuthenticationInterceptor: RequestInterceptor, Sendable where AuthenticatorType: Authenticator { + // MARK: Typealiases + + /// Type of credential used to authenticate requests. + public typealias Credential = AuthenticatorType.Credential + + // MARK: Helper Types + + /// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a + /// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the + /// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is + /// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown. + public struct RefreshWindow { + /// `TimeInterval` defining the duration of the time window before the current time in which the number of + /// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the + /// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than + /// `maximumAttempts`, an `.excessiveRefresh` error will be thrown. + public let interval: TimeInterval + + /// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error. + public let maximumAttempts: Int + + /// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`. + /// + /// - Parameters: + /// - interval: `TimeInterval` defining the duration of the time window before the current time. + /// - maximumAttempts: The maximum attempts allowed within the `TimeInterval`. + public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) { + self.interval = interval + self.maximumAttempts = maximumAttempts + } + } + + private struct AdaptOperation { + let urlRequest: URLRequest + let session: Session + let completion: @Sendable (Result) -> Void + } + + private enum AdaptResult { + case adapt(Credential) + case doNotAdapt(AuthenticationError) + case adaptDeferred + } + + private struct MutableState { + var credential: Credential? + + var isRefreshing = false + var refreshTimestamps: [TimeInterval] = [] + var refreshWindow: RefreshWindow? + + var adaptOperations: [AdaptOperation] = [] + var requestsToRetry: [@Sendable (RetryResult) -> Void] = [] + } + + // MARK: Properties + + /// The `Credential` used to authenticate requests. + public var credential: Credential? { + get { mutableState.credential } + set { mutableState.credential = newValue } + } + + let authenticator: AuthenticatorType + let queue = DispatchQueue(label: "org.alamofire.authentication.inspector") + + private let mutableState: Protected + + // MARK: Initialization + + /// Creates an `AuthenticationInterceptor` instance from the specified parameters. + /// + /// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls. + /// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles. + /// + /// - Parameters: + /// - authenticator: The `Authenticator` type. + /// - credential: The `Credential` if it exists. `nil` by default. + /// - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default. + public init(authenticator: AuthenticatorType, + credential: Credential? = nil, + refreshWindow: RefreshWindow? = RefreshWindow()) { + self.authenticator = authenticator + mutableState = Protected(MutableState(credential: credential, refreshWindow: refreshWindow)) + } + + // MARK: Adapt + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping @Sendable (Result) -> Void) { + let adaptResult: AdaptResult = mutableState.write { mutableState in + // Queue the adapt operation if a refresh is already in place. + guard !mutableState.isRefreshing else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + return .adaptDeferred + } + + // Throw missing credential error is the credential is missing. + guard let credential = mutableState.credential else { + let error = AuthenticationError.missingCredential + return .doNotAdapt(error) + } + + // Queue the adapt operation and trigger refresh operation if credential requires refresh. + guard !credential.requiresRefresh else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + refresh(credential, for: session, insideLock: &mutableState) + return .adaptDeferred + } + + return .adapt(credential) + } + + switch adaptResult { + case let .adapt(credential): + var authenticatedRequest = urlRequest + authenticator.apply(credential, to: &authenticatedRequest) + completion(.success(authenticatedRequest)) + + case let .doNotAdapt(adaptError): + completion(.failure(adaptError)) + + case .adaptDeferred: + // No-op: adapt operation captured during refresh. + break + } + } + + // MARK: Retry + + public func retry(_ request: Request, for session: Session, dueTo error: any Error, completion: @escaping @Sendable (RetryResult) -> Void) { + // Do not attempt retry if there was not an original request and response from the server. + guard let urlRequest = request.request, let response = request.response else { + completion(.doNotRetry) + return + } + + // Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code). + guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else { + completion(.doNotRetry) + return + } + + // Do not attempt retry if there is no credential. + guard let credential else { + let error = AuthenticationError.missingCredential + completion(.doNotRetryWithError(error)) + return + } + + // Retry the request if the `Authenticator` verifies it was authenticated with a previous credential. + guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else { + completion(.retry) + return + } + + mutableState.write { mutableState in + mutableState.requestsToRetry.append(completion) + + guard !mutableState.isRefreshing else { return } + + refresh(credential, for: session, insideLock: &mutableState) + } + } + + // MARK: Refresh + + private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) { + guard !isRefreshExcessive(insideLock: &mutableState) else { + let error = AuthenticationError.excessiveRefresh + handleRefreshFailure(error, insideLock: &mutableState) + return + } + + mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime) + mutableState.isRefreshing = true + + // Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously. + queue.async { + self.authenticator.refresh(credential, for: session) { result in + self.mutableState.write { mutableState in + switch result { + case let .success(credential): + self.handleRefreshSuccess(credential, insideLock: &mutableState) + case let .failure(error): + self.handleRefreshFailure(error, insideLock: &mutableState) + } + } + } + } + } + + private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool { + guard let refreshWindow = mutableState.refreshWindow else { return false } + + let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval + + let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in + guard refreshWindowMin <= refreshTimestamp else { return } + attempts += 1 + } + + let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts + + return isRefreshExcessive + } + + private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) { + mutableState.credential = credential + + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) } + requestsToRetry.forEach { $0(.retry) } + } + } + + private func handleRefreshFailure(_ error: any Error, insideLock mutableState: inout MutableState) { + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { $0.completion(.failure(error)) } + requestsToRetry.forEach { $0(.doNotRetryWithError(error)) } + } + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/CachedResponseHandler.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/CachedResponseHandler.swift new file mode 100644 index 00000000..c31f4b42 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/CachedResponseHandler.swift @@ -0,0 +1,107 @@ +// +// CachedResponseHandler.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles whether the data task should store the HTTP response in the cache. +public protocol CachedResponseHandler: Sendable { + /// Determines whether the HTTP response should be stored in the cache. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The cached response provided by the server (this is the most common use case). + /// 2. A modified version of the cached response (you may want to modify it in some way before caching). + /// 3. A `nil` value to prevent the cached response from being stored in the cache. + /// + /// - Parameters: + /// - task: The data task whose request resulted in the cached response. + /// - response: The cached response to potentially store in the cache. + /// - completion: The closure to execute containing cached response, a modified response, or `nil`. + func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) +} + +// MARK: - + +/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached +/// response. +public struct ResponseCacher { + /// Defines the behavior of the `ResponseCacher` type. + public enum Behavior: Sendable { + /// Stores the cached response in the cache. + case cache + /// Prevents the cached response from being stored in the cache. + case doNotCache + /// Modifies the cached response before storing it in the cache. + case modify(@Sendable (_ task: URLSessionDataTask, _ cachedResponse: CachedURLResponse) -> CachedURLResponse?) + } + + /// Returns a `ResponseCacher` with a `.cache` `Behavior`. + public static let cache = ResponseCacher(behavior: .cache) + /// Returns a `ResponseCacher` with a `.doNotCache` `Behavior`. + public static let doNotCache = ResponseCacher(behavior: .doNotCache) + + /// The `Behavior` of the `ResponseCacher`. + public let behavior: Behavior + + /// Creates a `ResponseCacher` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +extension ResponseCacher: CachedResponseHandler { + public func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) { + switch behavior { + case .cache: + completion(response) + case .doNotCache: + completion(nil) + case let .modify(closure): + let response = closure(task, response) + completion(response) + } + } +} + +extension CachedResponseHandler where Self == ResponseCacher { + /// Provides a `ResponseCacher` which caches the response, if allowed. Equivalent to `ResponseCacher.cache`. + public static var cache: ResponseCacher { .cache } + + /// Provides a `ResponseCacher` which does not cache the response. Equivalent to `ResponseCacher.doNotCache`. + public static var doNotCache: ResponseCacher { .doNotCache } + + /// Creates a `ResponseCacher` which modifies the proposed `CachedURLResponse` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the `CachedURLResponse`. + /// - Returns: The `ResponseCacher`. + public static func modify(using closure: @escaping (@Sendable (URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)) -> ResponseCacher { + ResponseCacher(behavior: .modify(closure)) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Combine.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Combine.swift new file mode 100644 index 00000000..d48610a9 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Combine.swift @@ -0,0 +1,652 @@ +// +// Combine.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !((os(iOS) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux) || os(Android)) + +import Combine +import Dispatch +import Foundation + +// MARK: - DataRequest / UploadRequest + +/// A Combine `Publisher` that publishes the `DataResponse` of the provided `DataRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataResponsePublisher: Publisher { + public typealias Output = DataResponse + public typealias Failure = Never + + private typealias Handler = (@escaping @Sendable (_ response: DataResponse) -> Void) -> DataRequest + + private let request: DataRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DataResponse`. + public init(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`. + public init(_ request: DataRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DataResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber & Sendable, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + private let downstream: Protected + private let request: DataRequest + private let responseHandler: Handler + + init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = Protected(downstream) + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream.read({ $0 }) else { return } + + self.downstream.write(nil) + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream.write(nil) + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DataResponsePublisher where Value == Data? { + /// Creates an instance which publishes a `DataResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DataRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DataRequest { + /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize response `Data`. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher + where Serializer.SerializedObject == T { + DataResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by + /// default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher { + DataResponsePublisher(self, queue: queue) + } +} + +// A Combine `Publisher` that publishes a sequence of `Stream` values received by the provided `DataStreamRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataStreamPublisher: Publisher { + public typealias Output = DataStreamRequest.Stream + public typealias Failure = Never + + private typealias Handler = (@escaping DataStreamRequest.Handler) -> DataStreamRequest + + private let request: DataStreamRequest + private let streamHandler: Handler + + /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `Stream` values will be published. `.main` by + /// default. + /// - serializer: `DataStreamSerializer` used to produce the published `Stream` values. + public init(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) } + } + + /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + compactMap { stream in + switch stream.event { + case let .stream(result): + result + // If the stream has completed with an error, send the error value downstream as a `.failure`. + case let .complete(completion): + completion.error.map(Result.failure) + } + } + .eraseToAnyPublisher() + } + + /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the + /// `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + result().setFailureType(to: AFError.self).flatMap(\.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber & Sendable, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + streamHandler: streamHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + private let downstream: Protected + private let request: DataStreamRequest + private let streamHandler: Handler + + init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.streamHandler = streamHandler + self.downstream = Protected(downstream) + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream.read({ $0 }) else { return } + + self.downstream.write(nil) + streamHandler { stream in + _ = downstream.receive(stream) + if case .complete = stream.event { + downstream.receive(completion: .finished) + } + }.resume() + } + + func cancel() { + request.cancel() + downstream.write(nil) + } + } +} + +extension DataStreamRequest { + /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishStream(using serializer: Serializer, + on queue: DispatchQueue = .main) -> DataStreamPublisher { + DataStreamPublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data` + /// unserialized. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: PassthroughStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream + /// `Data` values into `String` values. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: StringStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided + /// parameters to serialize stream `Data` values into the provided type. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default. + /// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: any DataDecoder = JSONDecoder(), + preprocessor: any DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher { + publishStream(using: DecodableStreamSerializer(decoder: decoder, + dataPreprocessor: preprocessor), + on: queue) + } +} + +/// A Combine `Publisher` that publishes the `DownloadResponse` of the provided `DownloadRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DownloadResponsePublisher: Publisher { + public typealias Output = DownloadResponse + public typealias Failure = Never + + private typealias Handler = (@escaping @Sendable (_ response: DownloadResponse) -> Void) -> DownloadRequest + + private let request: DownloadRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`. + public init(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DownloadResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber & Sendable, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + private let downstream: Protected + private let request: DownloadRequest + private let responseHandler: Handler + + init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = Protected(downstream) + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream.read({ $0 }) else { return } + + self.downstream.write(nil) + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream.write(nil) + } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and + /// `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the + /// response. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher { + publishResponse(using: URLResponseSerializer(), on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize + /// the response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless + /// of status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DownloadResponsePublisher where Value == URL? { + /// Creates an instance which publishes a `DownloadResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher { + DownloadResponsePublisher(self, queue: queue) + } +} + +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Concurrency.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Concurrency.swift new file mode 100644 index 00000000..262fdd1c --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Concurrency.swift @@ -0,0 +1,962 @@ +// +// Concurrency.swift +// +// Copyright (c) 2021 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(_Concurrency) + +import Foundation + +// MARK: - Request Event Streams + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension Request { + /// Creates a `StreamOf` for the instance's upload progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func uploadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + uploadProgress(queue: underlyingQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the instance's download progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func downloadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + downloadProgress(queue: underlyingQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the `URLRequest`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlRequests(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLRequestCreation(on: underlyingQueue) { request in + continuation.yield(request) + } + } + } + + /// Creates a `StreamOf` for the `URLSessionTask`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlSessionTasks(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLSessionTaskCreation(on: underlyingQueue) { task in + continuation.yield(task) + } + } + } + + /// Creates a `StreamOf` for the cURL descriptions produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func cURLDescriptions(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + cURLDescription(on: underlyingQueue) { description in + continuation.yield(description) + } + } + } + + fileprivate func stream(of type: T.Type = T.self, + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded, + yielder: @escaping (StreamOf.Continuation) -> Void) -> StreamOf { + StreamOf(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + yielder(continuation) + // Must come after serializers run in order to catch retry progress. + onFinish { + continuation.finish() + } + } + } +} + +// MARK: - DataTask + +/// Value used to `await` a `DataResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataTask: Sendable where Value: Sendable { + /// `DataResponse` produced by the `DataRequest` and its response handler. + public var response: DataResponse { + get async { + if shouldAutomaticallyCancel { + await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let request: DataRequest + private let task: Task, Never> + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DataRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DataRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DataRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataRequest { + /// Creates a `StreamOf` for the instance's responses. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onHTTPResponse(on: underlyingQueue) { response in + continuation.yield(response) + } + } + } + + /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataRequest` produces an + /// `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a + /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as + /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, + /// so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> ResponseDisposition + ) -> Self { + onHTTPResponse(on: underlyingQueue) { response, completionHandler in + Task { + let disposition = await handler(response) + completionHandler(disposition) + } + } + + return self + } + + /// Sets an async closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an + /// arbitrary thread, so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> Void) -> Self { + onHTTPResponse { response in + await handler(response) + return .allow + } + + return self + } + + /// Creates a `DataTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `Decodable` value. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance. + /// + /// - Parameters: + /// - serializer: `DataResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func dataTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @Sendable @escaping (@escaping @Sendable (DataResponse) -> Void) -> Void) + -> DataTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DataTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DownloadTask + +/// Value used to `await` a `DownloadResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DownloadTask: Sendable where Value: Sendable { + /// `DownloadResponse` produced by the `DownloadRequest` and its response handler. + public var response: DownloadResponse { + get async { + if shouldAutomaticallyCancel { + await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let task: Task, Never> + private let request: DownloadRequest + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DownloadRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DownloadRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DownloadRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DownloadRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DownloadRequest { + /// Creates a `DownloadTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value. + /// + /// - Note: This serializer reads the entire response into memory before parsing. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = true) -> DownloadTask { + serializingDownload(using: URLResponseSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// serializer. `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol` + /// instance. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func downloadTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @Sendable @escaping (@escaping @Sendable (DownloadResponse) -> Void) -> Void) + -> DownloadTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DownloadTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DataStreamTask + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataStreamTask: Sendable { + // Type of created streams. + public typealias Stream = StreamOf> + + private let request: DataStreamRequest + + fileprivate init(request: DataStreamRequest) { + self.request = request + } + + /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// - Returns: + public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - type: `Decodable` type to be serialized from stream payloads. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingDecodables(_ type: T.Type = T.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream where T: Decodable & Sendable { + streamingResponses(serializedUsing: DecodableStreamSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy) + } + + /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` to use to serialize incoming `Data`. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingResponses(serializedUsing serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(using: serializer, + on: .streamCompletionQueue(forRequestID: request.id), + stream: onStream) + } + } + + private func createStream(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded, + forResponse onResponse: @Sendable @escaping (@escaping @Sendable (DataStreamRequest.Stream) -> Void) -> Void) + -> Stream { + StreamOf(bufferingPolicy: bufferingPolicy) { + guard shouldAutomaticallyCancel, + request.isInitialized || request.isResumed || request.isSuspended else { return } + + cancel() + } builder: { continuation in + onResponse { stream in + continuation.yield(stream) + if case .complete = stream.event { + continuation.finish() + } + } + } + } + + /// Cancel the underlying `DataStreamRequest`. + public func cancel() { + request.cancel() + } + + /// Resume the underlying `DataStreamRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataStreamRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataStreamRequest { + /// Creates a `StreamOf` for the instance's responses. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onHTTPResponse(on: underlyingQueue) { response in + continuation.yield(response) + } + } + } + + /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataStreamRequest` + /// produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a + /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as + /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, + /// so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> ResponseDisposition) -> Self { + onHTTPResponse(on: underlyingQueue) { response, completionHandler in + Task { + let disposition = await handler(response) + completionHandler(disposition) + } + } + + return self + } + + /// Sets an async closure called whenever the `DataStreamRequest` produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an + /// arbitrary thread, so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> Void) -> Self { + onHTTPResponse { response in + await handler(response) + return .allow + } + + return self + } + + /// Creates a `DataStreamTask` used to `await` streams of serialized values. + /// + /// - Returns: The `DataStreamTask`. + public func streamTask() -> DataStreamTask { + DataStreamTask(request: self) + } +} + +#if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask. +// - MARK: WebSocketTask + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@_spi(WebSocket) public struct WebSocketTask: Sendable { + private let request: WebSocketRequest + + fileprivate init(request: WebSocketRequest) { + self.request = request + } + + public typealias EventStreamOf = StreamOf> + + public func streamingMessageEvents( + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: EventStreamOf.BufferingPolicy = .unbounded + ) -> EventStreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0 }) { onEvent in + request.streamMessageEvents(on: .streamCompletionQueue(forRequestID: request.id), handler: onEvent) + } + } + + public func streamingMessages( + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded + ) -> StreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0.message }) { onEvent in + request.streamMessageEvents(on: .streamCompletionQueue(forRequestID: request.id), handler: onEvent) + } + } + + public func streamingDecodableEvents( + _ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + using decoder: any DataDecoder = JSONDecoder(), + bufferingPolicy: EventStreamOf.BufferingPolicy = .unbounded + ) -> EventStreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0 }) { onEvent in + request.streamDecodableEvents(Value.self, + on: .streamCompletionQueue(forRequestID: request.id), + using: decoder, + handler: onEvent) + } + } + + public func streamingDecodable( + _ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + using decoder: any DataDecoder = JSONDecoder(), + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded + ) -> StreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0.message }) { onEvent in + request.streamDecodableEvents(Value.self, + on: .streamCompletionQueue(forRequestID: request.id), + using: decoder, + handler: onEvent) + } + } + + private func createStream( + automaticallyCancelling shouldAutomaticallyCancel: Bool, + bufferingPolicy: StreamOf.BufferingPolicy, + transform: @escaping @Sendable (WebSocketRequest.Event) -> Value?, + forResponse onResponse: @Sendable @escaping (@escaping @Sendable (WebSocketRequest.Event) -> Void) -> Void + ) -> StreamOf { + StreamOf(bufferingPolicy: bufferingPolicy) { + guard shouldAutomaticallyCancel, + request.isInitialized || request.isResumed || request.isSuspended else { return } + + cancel() + } builder: { continuation in + onResponse { event in + if let value = transform(event) { + continuation.yield(value) + } + + if case .completed = event.kind { + continuation.finish() + } + } + } + } + + /// Send a `URLSessionWebSocketTask.Message`. + /// + /// - Parameter message: The `Message`. + /// + public func send(_ message: URLSessionWebSocketTask.Message) async throws { + try await withCheckedThrowingContinuation { continuation in + request.send(message, queue: .streamCompletionQueue(forRequestID: request.id)) { result in + continuation.resume(with: result) + } + } + } + + /// Close the underlying `WebSocketRequest`. + public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) { + request.close(sending: closeCode, reason: reason) + } + + /// Cancel the underlying `WebSocketRequest`. + /// + /// Cancellation will produce an `AFError.explicitlyCancelled` instance. + public func cancel() { + request.cancel() + } + + /// Resume the underlying `WebSocketRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `WebSocketRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension WebSocketRequest { + public func webSocketTask() -> WebSocketTask { + WebSocketTask(request: self) + } +} +#endif + +extension DispatchQueue { + fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue", + attributes: .concurrent) + + fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue { + DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue) + } +} + +/// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct StreamOf: AsyncSequence { + public typealias AsyncIterator = Iterator + public typealias BufferingPolicy = AsyncStream.Continuation.BufferingPolicy + fileprivate typealias Continuation = AsyncStream.Continuation + + private let bufferingPolicy: BufferingPolicy + private let onTermination: (() -> Void)? + private let builder: (Continuation) -> Void + + fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded, + onTermination: (() -> Void)? = nil, + builder: @escaping (Continuation) -> Void) { + self.bufferingPolicy = bufferingPolicy + self.onTermination = onTermination + self.builder = builder + } + + public func makeAsyncIterator() -> Iterator { + var continuation: AsyncStream.Continuation? + let stream = AsyncStream(bufferingPolicy: bufferingPolicy) { innerContinuation in + continuation = innerContinuation + builder(innerContinuation) + } + + return Iterator(iterator: stream.makeAsyncIterator()) { + continuation?.finish() + onTermination?() + } + } + + public struct Iterator: AsyncIteratorProtocol { + private final class Token { + private let onDeinit: () -> Void + + init(onDeinit: @escaping () -> Void) { + self.onDeinit = onDeinit + } + + deinit { + onDeinit() + } + } + + private var iterator: AsyncStream.AsyncIterator + private let token: Token + + init(iterator: AsyncStream.AsyncIterator, onCancellation: @escaping () -> Void) { + self.iterator = iterator + token = Token(onDeinit: onCancellation) + } + + public mutating func next() async -> Element? { + await iterator.next() + } + } +} + +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/EventMonitor.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/EventMonitor.swift new file mode 100644 index 00000000..875aeeb2 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/EventMonitor.swift @@ -0,0 +1,909 @@ +// +// EventMonitor.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various +/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. +public protocol EventMonitor: Sendable { + /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. + var queue: DispatchQueue { get } + + // MARK: - URLSession Events + + // MARK: URLSessionDelegate Events + + /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) + + // MARK: URLSessionTaskDelegate Events + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. + func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. + func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) + + // MARK: URLSessionDataDelegate Events + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) + + // MARK: URLSessionDownloadDelegate Events + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) + + // MARK: - Request Events + + /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the + /// `URLRequest` will be adapted before being issued. + func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) + + /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. + func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) + + /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. + func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) + + /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. + func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) + + /// Event called when a final `URLRequest` is created for a `Request`. + func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) + + /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. + func request(_ request: Request, didCreateTask task: URLSessionTask) + + /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. + func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) + + /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. + func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) + + /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event + /// multiple times if it is retried. + func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) + + /// Event called when a `Request` is about to be retried. + func requestIsRetrying(_ request: Request) + + /// Event called when a `Request` finishes and response serializers are being called. + func requestDidFinish(_ request: Request) + + /// Event called when a `Request` receives a `resume` call. + func requestDidResume(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is resumed. + func request(_ request: Request, didResumeTask task: URLSessionTask) + + /// Event called when a `Request` receives a `suspend` call. + func requestDidSuspend(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is suspended. + func request(_ request: Request, didSuspendTask task: URLSessionTask) + + /// Event called when a `Request` receives a `cancel` call. + func requestDidCancel(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. + func request(_ request: Request, didCancelTask task: URLSessionTask) + + // MARK: DataRequest Events + + /// Event called when a `DataRequest` calls a `Validation`. + func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) + + /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + // MARK: DataStreamRequest Events + + /// Event called when a `DataStreamRequest` calls a `Validation` closure. + /// + /// - Parameters: + /// - request: `DataStreamRequest` which is calling the `Validation`. + /// - urlRequest: `URLRequest` of the request being validated. + /// - response: `HTTPURLResponse` of the request being validated. + /// - result: Produced `ValidationResult`. + func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) + + /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which the value was serialized. + /// - result: `Result` of the serialization attempt. + func request(_ request: DataStreamRequest, didParseStream result: Result) + + // MARK: UploadRequest Events + + /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. + func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) + + /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. + func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) + + /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if + /// the `InputStream` does not wrap a `Data` value or file `URL`. + func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) + + // MARK: DownloadRequest Events + + /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. + func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) + + /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the + /// downloaded file will be moved to. + func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) + + /// Event called when a `DownloadRequest` calls a `Validation`. + func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) + + /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) + + /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) +} + +extension EventMonitor { + /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. + public var queue: DispatchQueue { .main } + + // MARK: Default Implementations + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) {} + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didFinishCollecting metrics: URLSessionTaskMetrics) {} + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {} + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) {} + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} + public func request(_ request: Request, + didAdaptInitialRequest initialRequest: URLRequest, + to adaptedRequest: URLRequest) {} + public func request(_ request: Request, + didFailToAdaptURLRequest initialRequest: URLRequest, + withError error: AFError) {} + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didCreateTask task: URLSessionTask) {} + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} + public func requestIsRetrying(_ request: Request) {} + public func requestDidFinish(_ request: Request) {} + public func requestDidResume(_ request: Request) {} + public func request(_ request: Request, didResumeTask task: URLSessionTask) {} + public func requestDidSuspend(_ request: Request) {} + public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} + public func requestDidCancel(_ request: Request) {} + public func request(_ request: Request, didCancelTask task: URLSessionTask) {} + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataStreamRequest, didParseStream result: Result) {} + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} +} + +/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. +public final class CompositeEventMonitor: EventMonitor { + public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor") + + let monitors: Protected<[any EventMonitor]> + + init(monitors: [any EventMonitor]) { + self.monitors = Protected(monitors) + } + + func performEvent(_ event: @escaping @Sendable (any EventMonitor) -> Void) { + queue.async { + self.monitors.read { monitors in + for monitor in monitors { + monitor.queue.async { event(monitor) } + } + } + } + } + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) { + performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) { + performEvent { $0.urlSession(session, task: task, didReceive: challenge) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + performEvent { + $0.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + } + + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + performEvent { + $0.urlSession(session, taskNeedsNewBodyStream: task) + } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + performEvent { + $0.urlSession(session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request) + } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) { + performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: response) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } + } + + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) { + performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } + } + + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } + } + + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } + } + + public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } + } + + public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } + } + + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateURLRequest: urlRequest) } + } + + public func request(_ request: Request, didCreateTask task: URLSessionTask) { + performEvent { $0.request(request, didCreateTask: task) } + } + + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + performEvent { $0.request(request, didGatherMetrics: metrics) } + } + + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + performEvent { $0.request(request, didCompleteTask: task, with: error) } + } + + public func requestIsRetrying(_ request: Request) { + performEvent { $0.requestIsRetrying(request) } + } + + public func requestDidFinish(_ request: Request) { + performEvent { $0.requestDidFinish(request) } + } + + public func requestDidResume(_ request: Request) { + performEvent { $0.requestDidResume(request) } + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + performEvent { $0.request(request, didResumeTask: task) } + } + + public func requestDidSuspend(_ request: Request) { + performEvent { $0.requestDidSuspend(request) } + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + performEvent { $0.request(request, didSuspendTask: task) } + } + + public func requestDidCancel(_ request: Request) { + performEvent { $0.requestDidCancel(request) } + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + performEvent { $0.request(request, didCancelTask: task) } + } + + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + data: data, + withResult: result) + } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + withResult: result) + } + } + + public func request(_ request: DataStreamRequest, didParseStream result: Result) { + performEvent { $0.request(request, didParseStream: result) } + } + + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + performEvent { $0.request(request, didCreateUploadable: uploadable) } + } + + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } + } + + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + performEvent { $0.request(request, didProvideInputStream: stream) } + } + + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } + } + + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + performEvent { $0.request(request, didCreateDestinationURL: url) } + } + + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + fileURL: fileURL, + withResult: result) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } +} + +/// `EventMonitor` that allows optional closures to be set to receive events. +open class ClosureEventMonitor: EventMonitor, @unchecked Sendable { + /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. + open var sessionDidBecomeInvalidWithError: ((URLSession, (any Error)?) -> Void)? + + /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? + + /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? + + /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. + open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. + open var taskDidComplete: ((URLSession, URLSessionTask, (any Error)?) -> Void)? + + /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. + open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:didReceive:completionHandler:)` event. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> Void)? + + /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` + /// event. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: - Request Events + + /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. + open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. + open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? + + /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. + open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. + open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didCreateURLRequest:)` event. + open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didCreateTask:)` event. + open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didGatherMetrics:)` event. + open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. + open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? + + /// Closure called on the `request(_:didCompleteTask:with:)` event. + open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? + + /// Closure called on the `requestIsRetrying(_:)` event. + open var requestIsRetrying: ((Request) -> Void)? + + /// Closure called on the `requestDidFinish(_:)` event. + open var requestDidFinish: ((Request) -> Void)? + + /// Closure called on the `requestDidResume(_:)` event. + open var requestDidResume: ((Request) -> Void)? + + /// Closure called on the `request(_:didResumeTask:)` event. + open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidSuspend(_:)` event. + open var requestDidSuspend: ((Request) -> Void)? + + /// Closure called on the `request(_:didSuspendTask:)` event. + open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidCancel(_:)` event. + open var requestDidCancel: ((Request) -> Void)? + + /// Closure called on the `request(_:didCancelTask:)` event. + open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. + open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event. + open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didCreateUploadable:)` event. + open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? + + /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. + open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didProvideInputStream:)` event. + open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? + + /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. + open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? + + /// Closure called on the `request(_:didCreateDestinationURL:)` event. + open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. + open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? + + public let queue: DispatchQueue + + /// Creates an instance using the provided queue. + /// + /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. + public init(queue: DispatchQueue = .main) { + self.queue = queue + } + + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { + taskDidReceiveChallenge?(session, task, challenge) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + taskNeedNewBodyStream?(session, task) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + taskWillPerformHTTPRedirection?(session, task, response, request) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + taskDidFinishCollectingMetrics?(session, task, metrics) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) { + taskDidComplete?(session, task, error) + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + taskIsWaitingForConnectivity?(session, task) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { + dataTaskDidReceiveResponse?(session, dataTask, response) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + dataTaskDidReceiveData?(session, dataTask, data) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { + dataTaskWillCacheResponse?(session, dataTask, proposedResponse) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) + } + + // MARK: Request Events + + open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + requestDidCreateInitialURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + requestDidFailToCreateURLRequestWithError?(request, error) + } + + open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) + } + + open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) + } + + open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + requestDidCreateURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didCreateTask task: URLSessionTask) { + requestDidCreateTask?(request, task) + } + + open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + requestDidGatherMetrics?(request, metrics) + } + + open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + requestDidFailTaskEarlyWithError?(request, task, error) + } + + open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + requestDidCompleteTaskWithError?(request, task, error) + } + + open func requestIsRetrying(_ request: Request) { + requestIsRetrying?(request) + } + + open func requestDidFinish(_ request: Request) { + requestDidFinish?(request) + } + + open func requestDidResume(_ request: Request) { + requestDidResume?(request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + requestDidResumeTask?(request, task) + } + + open func requestDidSuspend(_ request: Request) { + requestDidSuspend?(request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + requestDidSuspendTask?(request, task) + } + + open func requestDidCancel(_ request: Request) { + requestDidCancel?(request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + requestDidCancelTask?(request, task) + } + + open func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) + } + + open func request(_ request: DataRequest, didParseResponse response: DataResponse) { + requestDidParseResponse?(request, response) + } + + public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result) + } + + open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + requestDidCreateUploadable?(request, uploadable) + } + + open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + requestDidFailToCreateUploadableWithError?(request, error) + } + + open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + requestDidProvideInputStream?(request, stream) + } + + open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) + } + + open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + requestDidCreateDestinationURL?(request, url) + } + + open func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseFileURLWithResult?(request, + urlRequest, + response, + fileURL, + result) + } + + open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + requestDidParseDownloadResponse?(request, response) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/MultipartFormData.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/MultipartFormData.swift new file mode 100644 index 00000000..7cc5e13d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/MultipartFormData.swift @@ -0,0 +1,585 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if canImport(MobileCoreServices) +import MobileCoreServices +#elseif canImport(CoreServices) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + // MARK: - Helper Types + + enum EncodingCharacters { + static let crlf = "\r\n" + } + + enum BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + let first = UInt32.random(in: UInt32.min...UInt32.max) + let second = UInt32.random(in: UInt32.min...UInt32.max) + + return String(format: "alamofire.boundary.%08x%08x", first, second) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText = switch boundaryType { + case .initial: + "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return Data(boundaryText.utf8) + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// Default memory threshold used when encoding `MultipartFormData`, in bytes. + public static let encodingMemoryThreshold: UInt64 = 10_000_000 + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + let fileManager: FileManager + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates an instance. + /// + /// - Parameters: + /// - fileManager: `FileManager` to use for file operations, if needed. + /// - boundary: Boundary `String` used to separate body parts. + public init(fileManager: FileManager = .default, boundary: String? = nil) { + self.fileManager = fileManager + self.boundary = boundary ?? BoundaryGenerator.randomBoundary() + bodyParts = [] + + // + // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + // information, please refer to the following article: + // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + // + streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - data: `Data` to encoding into the instance. + /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + #if !(os(Linux) || os(Windows) || os(Android)) + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + #endif + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append(_ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the stream, length, and headers and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - headers: `HTTPHeaders` for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all appended body parts into a single `Data` value. + /// + /// - Note: This method will load all the appended body parts into memory all at the same time. This method should + /// only be used when the encoded data will have a small memory footprint. For large data cases, please use + /// the `writeEncodedData(to:))` method. + /// + /// - Returns: The encoded `Data`, if encoding is successful. + /// - Throws: An `AFError` if encoding encounters an error. + public func encode() throws -> Data { + if let bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes all appended body parts to the given file `URL`. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - Parameter fileURL: File `URL` to which to write the form data. + /// - Throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError { + throw bodyPartError + } + + if fileManager.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } + .joined() + + EncodingCharacters.crlf + + return Data(headerText.utf8) + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + guard UInt64(encoded.count) == bodyPart.bodyContentLength else { + let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength, + bytesRead: UInt64(encoded.count)) + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + var bytesLeftToRead = bodyPart.bodyContentLength + while inputStream.hasBytesAvailable && bytesLeftToRead > 0 { + let bufferSize = min(streamBufferSize, Int(bytesLeftToRead)) + var buffer = [UInt8](repeating: 0, count: bufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: bufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. HTTPHeaders { + var disposition = "form-data; name=\"\(name)\"" + if let fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers: HTTPHeaders = [.contentDisposition(disposition)] + if let mimeType { headers.add(.contentType(mimeType)) } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} + +#if canImport(UniformTypeIdentifiers) +import UniformTypeIdentifiers + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { + return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } else { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + + return "application/octet-stream" + } + } +} + +#else + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + #if canImport(CoreServices) || canImport(MobileCoreServices) + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + #endif + + return "application/octet-stream" + } +} + +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/MultipartUpload.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/MultipartUpload.swift new file mode 100644 index 00000000..ae768a38 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/MultipartUpload.swift @@ -0,0 +1,99 @@ +// +// MultipartUpload.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Internal type which encapsulates a `MultipartFormData` upload. +final class MultipartUpload: @unchecked Sendable { // Must be @unchecked due to FileManager not being properly Sendable. + private let _result = Protected?>(nil) + var result: Result { + if let value = _result.read({ $0 }) { + return value + } else { + let result = Result { try build() } + _result.write(result) + + return result + } + } + + private let multipartFormData: Protected + + let encodingMemoryThreshold: UInt64 + let request: any URLRequestConvertible + let fileManager: FileManager + + init(encodingMemoryThreshold: UInt64, + request: any URLRequestConvertible, + multipartFormData: MultipartFormData) { + self.encodingMemoryThreshold = encodingMemoryThreshold + self.request = request + fileManager = multipartFormData.fileManager + self.multipartFormData = Protected(multipartFormData) + } + + func build() throws -> UploadRequest.Uploadable { + let uploadable: UploadRequest.Uploadable + if multipartFormData.contentLength < encodingMemoryThreshold { + let data = try multipartFormData.read { try $0.encode() } + + uploadable = .data(data) + } else { + let tempDirectoryURL = fileManager.temporaryDirectory + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + + do { + try multipartFormData.read { try $0.writeEncodedData(to: fileURL) } + } catch { + // Cleanup after attempted write if it fails. + try? fileManager.removeItem(at: fileURL) + throw error + } + + uploadable = .file(fileURL, shouldRemove: true) + } + + return uploadable + } +} + +extension MultipartUpload: UploadConvertible { + func asURLRequest() throws -> URLRequest { + var urlRequest = try request.asURLRequest() + + multipartFormData.read { multipartFormData in + urlRequest.headers.add(.contentType(multipartFormData.contentType)) + } + + return urlRequest + } + + func createUploadable() throws -> UploadRequest.Uploadable { + try result.get() + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/NetworkReachabilityManager.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/NetworkReachabilityManager.swift new file mode 100644 index 00000000..bee946eb --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/NetworkReachabilityManager.swift @@ -0,0 +1,293 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(SystemConfiguration) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +open class NetworkReachabilityManager: @unchecked Sendable { + /// Defines the various states of network reachability. + public enum NetworkReachabilityStatus: Sendable { + /// It is unknown whether the network is reachable. + case unknown + /// The network is not reachable. + case notReachable + /// The network is reachable on the associated `ConnectionType`. + case reachable(ConnectionType) + + init(_ flags: SCNetworkReachabilityFlags) { + guard flags.isActuallyReachable else { self = .notReachable; return } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + if flags.isCellular { networkStatus = .reachable(.cellular) } + + self = networkStatus + } + + /// Defines the various connection types detected by reachability flags. + public enum ConnectionType: Sendable { + /// The connection type is either over Ethernet or WiFi. + case ethernetOrWiFi + /// The connection type is a cellular connection. + case cellular + } + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = @Sendable (NetworkReachabilityStatus) -> Void + + /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. + public static let `default` = NetworkReachabilityManager() + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the cellular interface. + /// + /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. + /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. + /// + open var isReachableOnCellular: Bool { status == .reachable(.cellular) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) } + + /// `DispatchQueue` on which reachability will update. + public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") + + /// Flags of the current reachability type, if any. + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + return SCNetworkReachabilityGetFlags(reachability, &flags) ? flags : nil + } + + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + flags.map(NetworkReachabilityStatus.init) ?? .unknown + } + + /// Mutable state storage. + struct MutableState { + /// A closure executed when the network reachability status changes. + var listener: Listener? + /// `DispatchQueue` on which listeners will be called. + var listenerQueue: DispatchQueue? + /// Previously calculated status. + var previousStatus: NetworkReachabilityStatus? + } + + /// `SCNetworkReachability` instance providing notifications. + private let reachability: SCNetworkReachability + + /// Protected storage for mutable state. + private let mutableState = Protected(MutableState()) + + // MARK: - Initialization + + /// Creates an instance with the specified host. + /// + /// - Note: The `host` value must *not* contain a scheme, just the hostname. + /// + /// - Parameters: + /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + + self.init(reachability: reachability) + } + + /// Creates an instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + public convenience init?() { + var zero = sockaddr() + zero.sa_len = UInt8(MemoryLayout.size) + zero.sa_family = sa_family_t(AF_INET) + + guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - Note: Stops and removes any existing listener. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. + /// - listener: `Listener` closure called when reachability changes. + /// + /// - Returns: `true` if listening was started successfully, `false` otherwise. + @preconcurrency + @discardableResult + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() + + mutableState.write { state in + state.listenerQueue = queue + state.listener = listener + } + + let weakManager = WeakManager(manager: self) + + var context = SCNetworkReachabilityContext( + version: 0, + info: Unmanaged.passUnretained(weakManager).toOpaque(), + retain: { info in + let unmanaged = Unmanaged.fromOpaque(info) + _ = unmanaged.retain() + + return UnsafeRawPointer(unmanaged.toOpaque()) + }, + release: { info in + let unmanaged = Unmanaged.fromOpaque(info) + unmanaged.release() + }, + copyDescription: { info in + let unmanaged = Unmanaged.fromOpaque(info) + let weakManager = unmanaged.takeUnretainedValue() + let description = weakManager.manager?.flags?.readableDescription ?? "nil" + + return Unmanaged.passRetained(description as CFString) + } + ) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info else { return } + + let weakManager = Unmanaged.fromOpaque(info).takeUnretainedValue() + weakManager.manager?.notifyListener(flags) + } + + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) + + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } + } + + return callbackAdded && queueAdded + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + mutableState.write { state in + state.listener = nil + state.listenerQueue = nil + state.previousStatus = nil + } + } + + // MARK: - Internal - Listener Notification + + /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. + /// + /// - Note: Should only be called from the `reachabilityQueue`. + /// + /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + let newStatus = NetworkReachabilityStatus(flags) + + mutableState.write { [newStatus] state in + guard state.previousStatus != newStatus else { return } + + state.previousStatus = newStatus + + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } + } + + private final class WeakManager { + weak var manager: NetworkReachabilityManager? + + init(manager: NetworkReachabilityManager?) { + self.manager = manager + } + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +extension SCNetworkReachabilityFlags { + var isReachable: Bool { contains(.reachable) } + var isConnectionRequired: Bool { contains(.connectionRequired) } + var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) } + var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) } + var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } + var isCellular: Bool { + #if os(iOS) || os(tvOS) || (swift(>=5.9) && os(visionOS)) + return contains(.isWWAN) + #else + return false + #endif + } + + /// Human readable `String` for all states, to help with debugging. + var readableDescription: String { + let W = isCellular ? "W" : "-" + let R = isReachable ? "R" : "-" + let c = isConnectionRequired ? "c" : "-" + let t = contains(.transientConnection) ? "t" : "-" + let i = contains(.interventionRequired) ? "i" : "-" + let C = contains(.connectionOnTraffic) ? "C" : "-" + let D = contains(.connectionOnDemand) ? "D" : "-" + let l = contains(.isLocalAddress) ? "l" : "-" + let d = contains(.isDirect) ? "d" : "-" + let a = contains(.connectionAutomatic) ? "a" : "-" + + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" + } +} +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RedirectHandler.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RedirectHandler.swift new file mode 100644 index 00000000..c63219da --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RedirectHandler.swift @@ -0,0 +1,111 @@ +// +// RedirectHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request. +public protocol RedirectHandler: Sendable { + /// Determines how the HTTP redirect response should be redirected to the new request. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The new request specified by the redirect (this is the most common use case). + /// 2. A modified version of the new request (you may want to route it somewhere else). + /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. + /// + /// - Parameters: + /// - task: The `URLSessionTask` whose request resulted in a redirect. + /// - request: The `URLRequest` to the new location specified by the redirect response. + /// - response: The `HTTPURLResponse` containing the server's response to the original request. + /// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`. + func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) +} + +// MARK: - + +/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. +public struct Redirector { + /// Defines the behavior of the `Redirector` type. + public enum Behavior: Sendable { + /// Follow the redirect as defined in the response. + case follow + /// Do not follow the redirect defined in the response. + case doNotFollow + /// Modify the redirect request defined in the response. + case modify(@Sendable (_ task: URLSessionTask, _ request: URLRequest, _ response: HTTPURLResponse) -> URLRequest?) + } + + /// Returns a `Redirector` with a `.follow` `Behavior`. + public static let follow = Redirector(behavior: .follow) + /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. + public static let doNotFollow = Redirector(behavior: .doNotFollow) + + /// The `Behavior` of the `Redirector`. + public let behavior: Behavior + + /// Creates a `Redirector` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +// MARK: - + +extension Redirector: RedirectHandler { + public func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) { + switch behavior { + case .follow: + completion(request) + case .doNotFollow: + completion(nil) + case let .modify(closure): + let request = closure(task, request, response) + completion(request) + } + } +} + +extension RedirectHandler where Self == Redirector { + /// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`. + public static var follow: Redirector { .follow } + + /// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`. + public static var doNotFollow: Redirector { .doNotFollow } + + /// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the redirect. + /// - Returns: The `Redirector`. + public static func modify(using closure: @escaping @Sendable (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector { + Redirector(behavior: .modify(closure)) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RequestCompression.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RequestCompression.swift new file mode 100644 index 00000000..86335ded --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RequestCompression.swift @@ -0,0 +1,146 @@ +// +// RequestCompression.swift +// +// Copyright (c) 2023 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(zlib) && !os(Android) +import Foundation +import zlib + +/// `RequestAdapter` which compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the +/// appropriate header. +/// +/// - Note: Most requests to most APIs are small and so would only be slowed down by applying this adapter. Measure the +/// size of your request bodies and the performance impact of using this adapter before use. Using this adapter +/// with already compressed data, such as images, will, at best, have no effect. Additionally, body compression +/// is a synchronous operation, so measuring the performance impact may be important to determine whether you +/// want to use a dedicated `requestQueue` in your `Session` instance. Finally, not all servers support request +/// compression, so test with all of your server configurations before deploying. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DeflateRequestCompressor: Sendable, RequestInterceptor { + /// Type that determines the action taken when the `URLRequest` already has a `Content-Encoding` header. + public enum DuplicateHeaderBehavior: Sendable { + /// Throws a `DuplicateHeaderError`. The default. + case error + /// Replaces the existing header value with `deflate`. + case replace + /// Silently skips compression when the header exists. + case skip + } + + /// `Error` produced when the outgoing `URLRequest` already has a `Content-Encoding` header, when the instance has + /// been configured to produce an error. + public struct DuplicateHeaderError: Error {} + + /// Behavior to use when the outgoing `URLRequest` already has a `Content-Encoding` header. + public let duplicateHeaderBehavior: DuplicateHeaderBehavior + /// Closure which determines whether the outgoing body data should be compressed. + public let shouldCompressBodyData: @Sendable (_ bodyData: Data) -> Bool + + /// Creates an instance with the provided parameters. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. `.error` by default. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + public init(duplicateHeaderBehavior: DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping @Sendable (_ bodyData: Data) -> Bool = { _ in true }) { + self.duplicateHeaderBehavior = duplicateHeaderBehavior + self.shouldCompressBodyData = shouldCompressBodyData + } + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + // No need to compress unless we have body data. No support for compressing streams. + guard let bodyData = urlRequest.httpBody else { + completion(.success(urlRequest)) + return + } + + guard shouldCompressBodyData(bodyData) else { + completion(.success(urlRequest)) + return + } + + if urlRequest.headers.value(for: "Content-Encoding") != nil { + switch duplicateHeaderBehavior { + case .error: + completion(.failure(DuplicateHeaderError())) + return + case .replace: + // Header will be replaced once the body data is compressed. + break + case .skip: + completion(.success(urlRequest)) + return + } + } + + var compressedRequest = urlRequest + + do { + compressedRequest.httpBody = try deflate(bodyData) + compressedRequest.headers.update(.contentEncoding("deflate")) + completion(.success(compressedRequest)) + } catch { + completion(.failure(error)) + } + } + + func deflate(_ data: Data) throws -> Data { + var output = Data([0x78, 0x5E]) // Header + try output.append((data as NSData).compressed(using: .zlib) as Data) + var checksum = adler32Checksum(of: data).bigEndian + output.append(Data(bytes: &checksum, count: MemoryLayout.size)) + + return output + } + + func adler32Checksum(of data: Data) -> UInt32 { + data.withUnsafeBytes { buffer in + UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) + } + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension RequestInterceptor where Self == DeflateRequestCompressor { + /// Create a `DeflateRequestCompressor` with default `duplicateHeaderBehavior` and `shouldCompressBodyData` values. + public static var deflateCompressor: DeflateRequestCompressor { + DeflateRequestCompressor() + } + + /// Creates a `DeflateRequestCompressor` with the provided `DuplicateHeaderBehavior` and `shouldCompressBodyData` + /// closure. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + /// + /// - Returns: The `DeflateRequestCompressor`. + public static func deflateCompressor( + duplicateHeaderBehavior: DeflateRequestCompressor.DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping @Sendable (_ bodyData: Data) -> Bool = { _ in true } + ) -> DeflateRequestCompressor { + DeflateRequestCompressor(duplicateHeaderBehavior: duplicateHeaderBehavior, + shouldCompressBodyData: shouldCompressBodyData) + } +} +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RequestInterceptor.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RequestInterceptor.swift new file mode 100644 index 00000000..6c438c50 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RequestInterceptor.swift @@ -0,0 +1,376 @@ +// +// RequestInterceptor.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Stores all state associated with a `URLRequest` being adapted. +public struct RequestAdapterState: Sendable { + /// The `UUID` of the `Request` associated with the `URLRequest` to adapt. + public let requestID: UUID + + /// The `Session` associated with the `URLRequest` to adapt. + public let session: Session +} + +// MARK: - + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter: Sendable { + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - session: The `Session` that will execute the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping @Sendable (_ result: Result) -> Void) + + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - state: The `RequestAdapterState` associated with the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping @Sendable (_ result: Result) -> Void) +} + +extension RequestAdapter { + @preconcurrency + public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping @Sendable (_ result: Result) -> Void) { + adapt(urlRequest, for: state.session, completion: completion) + } +} + +// MARK: - + +/// Outcome of determination whether retry is necessary. +public enum RetryResult: Sendable { + /// Retry should be attempted immediately. + case retry + /// Retry should be attempted after the associated `TimeInterval`. + case retryWithDelay(TimeInterval) + /// Do not retry. + case doNotRetry + /// Do not retry due to the associated `Error`. + case doNotRetryWithError(any Error) +} + +extension RetryResult { + var retryRequired: Bool { + switch self { + case .retry, .retryWithDelay: true + default: false + } + } + + var delay: TimeInterval? { + switch self { + case let .retryWithDelay(delay): delay + default: nil + } + } + + var error: (any Error)? { + guard case let .doNotRetryWithError(error) = self else { return nil } + return error + } +} + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier: Sendable { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - session: `Session` that produced the `Request`. + /// - error: `Error` encountered while executing the `Request`. + /// - completion: Completion closure to be executed when a retry decision has been determined. + func retry(_ request: Request, for session: Session, dueTo error: any Error, completion: @escaping @Sendable (RetryResult) -> Void) +} + +// MARK: - + +/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. +public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} + +extension RequestInterceptor { + @preconcurrency + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping @Sendable (Result) -> Void) { + completion(.success(urlRequest)) + } + + @preconcurrency + public func retry(_ request: Request, + for session: Session, + dueTo error: any Error, + completion: @escaping @Sendable (RetryResult) -> Void) { + completion(.doNotRetry) + } +} + +/// `RequestAdapter` closure definition. +public typealias AdaptHandler = @Sendable (_ request: URLRequest, + _ session: Session, + _ completion: @escaping @Sendable (Result) -> Void) -> Void + +/// `RequestRetrier` closure definition. +public typealias RetryHandler = @Sendable (_ request: Request, + _ session: Session, + _ error: any Error, + _ completion: @escaping @Sendable (RetryResult) -> Void) -> Void + +// MARK: - + +/// Closure-based `RequestAdapter`. +open class Adapter: @unchecked Sendable, RequestInterceptor { + private let adaptHandler: AdaptHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. + /// + @preconcurrency + public init(_ adaptHandler: @escaping AdaptHandler) { + self.adaptHandler = adaptHandler + } + + @preconcurrency + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping @Sendable (Result) -> Void) { + adaptHandler(urlRequest, session, completion) + } + + @preconcurrency + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping @Sendable (Result) -> Void) { + adaptHandler(urlRequest, state.session, completion) + } +} + +extension RequestAdapter where Self == Adapter { + /// Creates an `Adapter` using the provided `AdaptHandler` closure. + /// + /// - Parameter closure: `AdaptHandler` to use to adapt the request. + /// - Returns: The `Adapter`. + @preconcurrency + public static func adapter(using closure: @escaping AdaptHandler) -> Adapter { + Adapter(closure) + } +} + +// MARK: - + +/// Closure-based `RequestRetrier`. +open class Retrier: @unchecked Sendable, RequestInterceptor { + private let retryHandler: RetryHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. + @preconcurrency + public init(_ retryHandler: @escaping RetryHandler) { + self.retryHandler = retryHandler + } + + @preconcurrency + open func retry(_ request: Request, + for session: Session, + dueTo error: any Error, + completion: @escaping @Sendable (RetryResult) -> Void) { + retryHandler(request, session, error, completion) + } +} + +extension RequestRetrier where Self == Retrier { + /// Creates a `Retrier` using the provided `RetryHandler` closure. + /// + /// - Parameter closure: `RetryHandler` to use to retry the request. + /// - Returns: The `Retrier`. + @preconcurrency + public static func retrier(using closure: @escaping RetryHandler) -> Retrier { + Retrier(closure) + } +} + +// MARK: - + +/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. +open class Interceptor: @unchecked Sendable, RequestInterceptor { + /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. + public let adapters: [any RequestAdapter] + /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. + public let retriers: [any RequestRetrier] + + /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adaptHandler: `AdaptHandler` closure to be used. + /// - retryHandler: `RetryHandler` closure to be used. + public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { + adapters = [Adapter(adaptHandler)] + retriers = [Retrier(retryHandler)] + } + + /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapter: `RequestAdapter` value to be used. + /// - retrier: `RequestRetrier` value to be used. + public init(adapter: any RequestAdapter, retrier: any RequestRetrier) { + adapters = [adapter] + retriers = [retrier] + } + + /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapters: `RequestAdapter` values to be used. + /// - retriers: `RequestRetrier` values to be used. + /// - interceptors: `RequestInterceptor`s to be used. + public init(adapters: [any RequestAdapter] = [], + retriers: [any RequestRetrier] = [], + interceptors: [any RequestInterceptor] = []) { + self.adapters = adapters + interceptors + self.retriers = retriers + interceptors + } + + @preconcurrency + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping @Sendable (Result) -> Void) { + adapt(urlRequest, for: session, using: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + for session: Session, + using adapters: [any RequestAdapter], + completion: @escaping @Sendable (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, for: session) { [pendingAdapters] result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + @preconcurrency + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping @Sendable (Result) -> Void) { + adapt(urlRequest, using: state, adapters: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + using state: RequestAdapterState, + adapters: [any RequestAdapter], + completion: @escaping @Sendable (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, using: state) { [pendingAdapters] result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + @preconcurrency + open func retry(_ request: Request, + for session: Session, + dueTo error: any Error, + completion: @escaping @Sendable (RetryResult) -> Void) { + retry(request, for: session, dueTo: error, using: retriers, completion: completion) + } + + private func retry(_ request: Request, + for session: Session, + dueTo error: any Error, + using retriers: [any RequestRetrier], + completion: @escaping @Sendable (RetryResult) -> Void) { + var pendingRetriers = retriers + + guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } + + let retrier = pendingRetriers.removeFirst() + + retrier.retry(request, for: session, dueTo: error) { [pendingRetriers] result in + switch result { + case .retry, .retryWithDelay, .doNotRetryWithError: + completion(result) + case .doNotRetry: + // Only continue to the next retrier if retry was not triggered and no error was encountered + self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) + } + } + } +} + +extension RequestInterceptor where Self == Interceptor { + /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adapter: `AdapterHandler`to use to adapt the request. + /// - retrier: `RetryHandler` to use to retry the request. + /// - Returns: The `Interceptor`. + @preconcurrency + public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor { + Interceptor(adaptHandler: adapter, retryHandler: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances. + /// - Parameters: + /// - adapter: `RequestAdapter` to use to adapt the request + /// - retrier: `RequestRetrier` to use to retry the request. + /// - Returns: The `Interceptor`. + @preconcurrency + public static func interceptor(adapter: any RequestAdapter, retrier: any RequestRetrier) -> Interceptor { + Interceptor(adapter: adapter, retrier: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s. + /// - Parameters: + /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails. + /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until + /// a retry is triggered. + /// - interceptors: `RequestInterceptor`s to use to intercept the request. + /// - Returns: The `Interceptor`. + @preconcurrency + public static func interceptor(adapters: [any RequestAdapter] = [], + retriers: [any RequestRetrier] = [], + interceptors: [any RequestInterceptor] = []) -> Interceptor { + Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/ResponseSerialization.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/ResponseSerialization.swift new file mode 100644 index 00000000..230780f1 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/ResponseSerialization.swift @@ -0,0 +1,532 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The type to which all data response serializers must conform in order to serialize a response. +public protocol DataResponseSerializerProtocol: Sendable { + /// The type of serialized object to be created. + associatedtype SerializedObject: Sendable + + /// Serialize the response `Data` into the provided type. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - data: `Data` returned from the server, if any. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: (any Error)?) throws -> SerializedObject +} + +/// The type to which all download response serializers must conform in order to serialize a response. +public protocol DownloadResponseSerializerProtocol: Sendable { + /// The type of serialized object to be created. + associatedtype SerializedObject: Sendable + + /// Serialize the downloaded response `Data` from disk into the provided type. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - fileURL: File `URL` to which the response data was downloaded. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: (any Error)?) throws -> SerializedObject +} + +/// A serializer that can handle both data and download responses. +public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// `DataPreprocessor` used to prepare incoming `Data` for serialization. + var dataPreprocessor: any DataPreprocessor { get } + /// `HTTPMethod`s for which empty response bodies are considered appropriate. + var emptyRequestMethods: Set { get } + /// HTTP response codes for which empty response bodies are considered appropriate. + var emptyResponseCodes: Set { get } +} + +/// Type used to preprocess `Data` before it handled by a serializer. +public protocol DataPreprocessor: Sendable { + /// Process `Data` before it's handled by a serializer. + /// - Parameter data: The raw `Data` to process. + func preprocess(_ data: Data) throws -> Data +} + +/// `DataPreprocessor` that returns passed `Data` without any transform. +public struct PassthroughPreprocessor: DataPreprocessor { + /// Creates an instance. + public init() {} + + public func preprocess(_ data: Data) throws -> Data { data } +} + +/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. +public struct GoogleXSSIPreprocessor: DataPreprocessor { + /// Creates an instance. + public init() {} + + public func preprocess(_ data: Data) throws -> Data { + (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data + } +} + +extension DataPreprocessor where Self == PassthroughPreprocessor { + /// Provides a `PassthroughPreprocessor` instance. + public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() } +} + +extension DataPreprocessor where Self == GoogleXSSIPreprocessor { + /// Provides a `GoogleXSSIPreprocessor` instance. + public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() } +} + +extension ResponseSerializer { + /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. + public static var defaultDataPreprocessor: any DataPreprocessor { PassthroughPreprocessor() } + /// Default `HTTPMethod`s for which empty response bodies are always considered appropriate. `[.head]` by default. + public static var defaultEmptyRequestMethods: Set { [.head] } + /// HTTP response codes for which empty response bodies are always considered appropriate. `[204, 205]` by default. + public static var defaultEmptyResponseCodes: Set { [204, 205] } + + public var dataPreprocessor: any DataPreprocessor { Self.defaultDataPreprocessor } + public var emptyRequestMethods: Set { Self.defaultEmptyRequestMethods } + public var emptyResponseCodes: Set { Self.defaultEmptyResponseCodes } + + /// Determines whether the `request` allows empty response bodies, if `request` exists. + /// + /// - Parameter request: `URLRequest` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. + public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { + request.flatMap(\.httpMethod) + .flatMap(HTTPMethod.init) + .map { emptyRequestMethods.contains($0) } + } + + /// Determines whether the `response` allows empty response bodies, if `response` exists. + /// + /// - Parameter response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. + public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { + response.map(\.statusCode) + .map { emptyResponseCodes.contains($0) } + } + + /// Determines whether `request` and `response` allow empty response bodies. + /// + /// - Parameters: + /// - request: `URLRequest` to evaluate. + /// - response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. + public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { + (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) + } +} + +/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds +/// the data read from disk into the data response serializer. +extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { + public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: (any Error)?) throws -> Self.SerializedObject { + guard error == nil else { throw error! } + + guard let fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch { + throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) + } + + do { + return try serialize(request: request, response: response, data: data, error: error) + } catch { + throw error + } + } +} + +// MARK: - URL + +/// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL` +/// is present. +public struct URLResponseSerializer: DownloadResponseSerializerProtocol { + /// Creates an instance. + public init() {} + + public func serializeDownload(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + error: (any Error)?) throws -> URL { + guard error == nil else { throw error! } + + guard let url = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + return url + } +} + +extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer { + /// Provides a `URLResponseSerializer` instance. + public static var url: URLResponseSerializer { URLResponseSerializer() } +} + +// MARK: - Data + +/// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a +/// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the +/// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned. +public final class DataResponseSerializer: ResponseSerializer { + public let dataPreprocessor: any DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: (any Error)?) throws -> Data { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return Data() + } + + data = try dataPreprocessor.preprocess(data) + + return data + } +} + +extension ResponseSerializer where Self == DataResponseSerializer { + /// Provides a default `DataResponseSerializer` instance. + public static var data: DataResponseSerializer { DataResponseSerializer() } + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DataResponseSerializer`. + public static func data(dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer { + DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +// MARK: - String + +/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no +/// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code +/// valid for empty responses, then an empty `String` is returned. +public final class StringResponseSerializer: ResponseSerializer { + public let dataPreprocessor: any DataPreprocessor + /// Optional string encoding used to validate the response. + public let encoding: String.Encoding? + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.encoding = encoding + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: (any Error)?) throws -> String { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return "" + } + + data = try dataPreprocessor.preprocess(data) + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName, convertedEncoding == nil { + convertedEncoding = String.Encoding(ianaCharsetName: encodingName) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + guard let string = String(data: data, encoding: actualEncoding) else { + throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) + } + + return string + } +} + +extension ResponseSerializer where Self == StringResponseSerializer { + /// Provides a default `StringResponseSerializer` instance. + public static var string: StringResponseSerializer { StringResponseSerializer() } + + /// Creates a `StringResponseSerializer` with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `StringResponseSerializer`. + public static func string(dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer { + StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +// MARK: - JSON + +/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning +/// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an +/// HTTP status code valid for empty responses, then an `NSNull` value is returned. +/// +/// - Note: This serializer is deprecated and should not be used. Instead, create concrete types conforming to +/// `Decodable` and use a `DecodableResponseSerializer`. +@available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.") +public final class JSONResponseSerializer: ResponseSerializer { + public let dataPreprocessor: any DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + /// `JSONSerialization.ReadingOptions` used when serializing a response. + public let options: JSONSerialization.ReadingOptions + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// - options: The options to use. `.allowFragments` by default. + public init(dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + self.options = options + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: (any Error)?) throws -> Any { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return NSNull() + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch { + throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) + } + } +} + +// MARK: - Empty + +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse: Sendable { + /// Empty value for the conforming type. + /// + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} + +/// Type representing an empty value. Use `Empty.value` to get the static instance. +public struct Empty: Codable, Sendable { + /// Static `Empty` instance used for all `Empty` responses. + public static let value = Empty() +} + +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + value + } +} + +// MARK: - DataDecoder Protocol + +/// Any type which can decode `Data` into a `Decodable` type. +public protocol DataDecoder: Sendable { + /// Decode `Data` into the provided type. + /// + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. + /// + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D +} + +/// `JSONDecoder` automatically conforms to `DataDecoder`. +extension JSONDecoder: DataDecoder {} +/// `PropertyListDecoder` automatically conforms to `DataDecoder`. +extension PropertyListDecoder: DataDecoder {} + +// MARK: - Decodable + +/// A `ResponseSerializer` that decodes the response data as a `Decodable` value using any decoder that conforms to +/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. +/// +/// - Note: A request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or +/// the response has an HTTP status code valid for empty responses then an empty value will be returned. If the +/// decoded type conforms to `EmptyResponse`, the type's `emptyValue()` will be returned. If the decoded type is +/// `Empty`, the `.value` instance is returned. If the decoded type *does not* conform to `EmptyResponse` and +/// isn't `Empty`, an error will be produced. +/// +/// - Note: `JSONDecoder` and `PropertyListDecoder` are not `Sendable` on Apple platforms until macOS 13+ or iOS 16+, so +/// instances passed to a serializer should not be used outside of the serializer. Additionally, ensure a new +/// serializer is created for each request, do not use a single, shared serializer, so as to ensure separate +/// decoder instances. +public final class DecodableResponseSerializer: ResponseSerializer where T: Sendable { + public let dataPreprocessor: any DataPreprocessor + /// The `DataDecoder` instance used to decode responses. + public let decoder: any DataDecoder + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using the values provided. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.decoder = decoder + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: (any Error)?) throws -> T { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + guard let emptyResponseType = T.self as? any EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { + throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) + } + + return emptyValue + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try decoder.decode(T.self, from: data) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +extension ResponseSerializer { + /// Creates a `DecodableResponseSerializer` using the values provided. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DecodableResponseSerializer`. + public static func decodable(of type: T.Type, + dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: any DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DecodableResponseSerializer where Self == DecodableResponseSerializer { + DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RetryPolicy.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RetryPolicy.swift new file mode 100644 index 00000000..972788ad --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/RetryPolicy.swift @@ -0,0 +1,430 @@ +// +// RetryPolicy.swift +// +// Copyright (c) 2019-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes +/// as well as certain types of networking errors. +open class RetryPolicy: @unchecked Sendable, RequestInterceptor { + /// The default retry limit for retry policies. + public static let defaultRetryLimit: UInt = 2 + + /// The default exponential backoff base for retry policies (must be a minimum of 2). + public static let defaultExponentialBackoffBase: UInt = 2 + + /// The default exponential backoff scale for retry policies. + public static let defaultExponentialBackoffScale: Double = 0.5 + + /// The default HTTP methods to retry. + /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. + public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent + .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent + .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent + .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent + .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent + .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent + ] + + /// The default HTTP status codes to retry. + /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. + public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) + 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) + 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) + 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) + 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) + ] + + /// The default URL error codes to retry. + public static let defaultRetryableURLErrorCodes: Set = [ // [Security] App Transport Security disallowed a connection because there is no secure network connection. + // - [Disabled] ATS settings do not change at runtime. + // .appTransportSecurityRequiresSecureConnection, + + // [System] An app or app extension attempted to connect to a background session that is already connected to a + // process. + // - [Enabled] The other process could release the background session. + .backgroundSessionInUseByAnotherProcess, + + // [System] The shared container identifier of the URL session configuration is needed but has not been set. + // - [Disabled] Cannot change at runtime. + // .backgroundSessionRequiresSharedContainer, + + // [System] The app is suspended or exits while a background data task is processing. + // - [Enabled] App can be foregrounded or launched to recover. + .backgroundSessionWasDisconnected, + + // [Network] The URL Loading system received bad data from the server. + // - [Enabled] Server could return valid data when retrying. + .badServerResponse, + + // [Resource] A malformed URL prevented a URL request from being initiated. + // - [Disabled] URL was most likely constructed incorrectly. + // .badURL, + + // [System] A connection was attempted while a phone call is active on a network that does not support + // simultaneous phone and data communication (EDGE or GPRS). + // - [Enabled] Phone call could be ended to allow request to recover. + .callIsActive, + + // [Client] An asynchronous load has been canceled. + // - [Disabled] Request was cancelled by the client. + // .cancelled, + + // [File System] A download task couldn’t close the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCloseFile, + + // [Network] An attempt to connect to a host failed. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotConnectToHost, + + // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCreateFile, + + // [Data] Content data received during a connection request had an unknown content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeContentData, + + // [Data] Content data received during a connection request could not be decoded for a known content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeRawData, + + // [Network] The host name for a URL could not be resolved. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotFindHost, + + // [Network] A request to load an item only from the cache could not be satisfied. + // - [Enabled] Cache could be populated during a retry. + .cannotLoadFromNetwork, + + // [File System] A download task was unable to move a downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotMoveFile, + + // [File System] A download task was unable to open the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotOpenFile, + + // [Data] A task could not parse a response. + // - [Disabled] Invalid response is unlikely to recover with retry. + // .cannotParseResponse, + + // [File System] A download task was unable to remove a downloaded file from disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotRemoveFile, + + // [File System] A download task was unable to write to the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotWriteToFile, + + // [Security] A client certificate was rejected. + // - [Disabled] Client certificate is unlikely to change with retry. + // .clientCertificateRejected, + + // [Security] A client certificate was required to authenticate an SSL connection during a request. + // - [Disabled] Client certificate is unlikely to be provided with retry. + // .clientCertificateRequired, + + // [Data] The length of the resource data exceeds the maximum allowed. + // - [Disabled] Resource will likely still exceed the length maximum on retry. + // .dataLengthExceedsMaximum, + + // [System] The cellular network disallowed a connection. + // - [Enabled] WiFi connection could be established during retry. + .dataNotAllowed, + + // [Network] The host address could not be found via DNS lookup. + // - [Enabled] DNS lookup could succeed during retry. + .dnsLookupFailed, + + // [Data] A download task failed to decode an encoded file during the download. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedMidStream, + + // [Data] A download task failed to decode an encoded file after downloading. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedToComplete, + + // [File System] A file does not exist. + // - [Disabled] File system error is unlikely to recover with retry. + // .fileDoesNotExist, + + // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, + // but a directory. + // - [Disabled] FTP directory is not likely to change to a file during a retry. + // .fileIsDirectory, + + // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been + // exceeded (currently 16). + // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. + // .httpTooManyRedirects, + + // [System] The attempted connection required activating a data context while roaming, but international roaming + // is disabled. + // - [Enabled] WiFi connection could be established during retry. + .internationalRoamingOff, + + // [Connectivity] A client or server connection was severed in the middle of an in-progress load. + // - [Enabled] A network connection could be established during retry. + .networkConnectionLost, + + // [File System] A resource couldn’t be read because of insufficient permissions. + // - [Disabled] Permissions are unlikely to be granted during retry. + // .noPermissionsToReadFile, + + // [Connectivity] A network resource was requested, but an internet connection has not been established and + // cannot be established automatically. + // - [Enabled] A network connection could be established during retry. + .notConnectedToInternet, + + // [Resource] A redirect was specified by way of server response code, but the server did not accompany this + // code with a redirect URL. + // - [Disabled] The redirect URL is unlikely to be supplied during a retry. + // .redirectToNonExistentLocation, + + // [Client] A body stream is needed but the client did not provide one. + // - [Disabled] The client will be unlikely to supply a body stream during retry. + // .requestBodyStreamExhausted, + + // [Resource] A requested resource couldn’t be retrieved. + // - [Disabled] The resource is unlikely to become available during the retry window. + // .resourceUnavailable, + + // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more + // specifically. + // - [Enabled] The secure connection could be established during a retry given the lack of specificity + // provided by the error. + .secureConnectionFailed, + + // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateHasBadDate, + + // [Security] A server certificate was not signed by any root server. + // - [Disabled] The server certificate is unlikely to change during the retry window. + // .serverCertificateHasUnknownRoot, + + // [Security] A server certificate is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateNotYetValid, + + // [Security] A server certificate was signed by a root server that isn’t trusted. + // - [Disabled] The server certificate is unlikely to become trusted within the retry window. + // .serverCertificateUntrusted, + + // [Network] An asynchronous operation timed out. + // - [Enabled] The request timed out for an unknown reason and should be retried. + .timedOut + + // [System] The URL Loading System encountered an error that it can’t interpret. + // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. + // .unknown, + + // [Resource] A properly formed URL couldn’t be handled by the framework. + // - [Disabled] The URL is unlikely to change during a retry. + // .unsupportedURL, + + // [Client] Authentication is required to access a resource. + // - [Disabled] The user authentication is unlikely to be provided by retrying. + // .userAuthenticationRequired, + + // [Client] An asynchronous request for authentication has been canceled by the user. + // - [Disabled] The user cancelled authentication and explicitly took action to not retry. + // .userCancelledAuthentication, + + // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection + // gracefully without sending any data. + // - [Disabled] The server is unlikely to provide data during the retry window. + // .zeroByteResource, + ] + + /// The total number of times the request is allowed to be retried. + public let retryLimit: UInt + + /// The base of the exponential backoff policy (should always be greater than or equal to 2). + public let exponentialBackoffBase: UInt + + /// The scale of the exponential backoff. + public let exponentialBackoffScale: Double + + /// The HTTP methods that are allowed to be retried. + public let retryableHTTPMethods: Set + + /// The HTTP status codes that are automatically retried by the policy. + public let retryableHTTPStatusCodes: Set + + /// The URL error codes that are automatically retried by the policy. + public let retryableURLErrorCodes: Set + + /// Creates a `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { + precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") + + self.retryLimit = retryLimit + self.exponentialBackoffBase = exponentialBackoffBase + self.exponentialBackoffScale = exponentialBackoffScale + self.retryableHTTPMethods = retryableHTTPMethods + self.retryableHTTPStatusCodes = retryableHTTPStatusCodes + self.retryableURLErrorCodes = retryableURLErrorCodes + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: any Error, + completion: @escaping (RetryResult) -> Void) { + if request.retryCount < retryLimit, shouldRetry(request: request, dueTo: error) { + completion(.retryWithDelay(pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale)) + } else { + completion(.doNotRetry) + } + } + + /// Determines whether or not to retry the provided `Request`. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - error: `Error` encountered while executing the `Request`. + /// + /// - Returns: `Bool` determining whether or not to retry the `Request`. + open func shouldRetry(request: Request, dueTo error: any Error) -> Bool { + guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false } + + if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { + return true + } else { + let errorCode = (error as? URLError)?.code + let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code + + guard let code = errorCode ?? afErrorCode else { return false } + + return retryableURLErrorCodes.contains(code) + } + } +} + +extension RequestInterceptor where Self == RetryPolicy { + /// Provides a default `RetryPolicy` instance. + public static var retryPolicy: RetryPolicy { RetryPolicy() } + + /// Creates an `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + /// + /// - Returns: The `RetryPolicy` + public static func retryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) -> RetryPolicy { + RetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: retryableHTTPStatusCodes, + retryableURLErrorCodes: retryableURLErrorCodes) + } +} + +// MARK: - + +/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more +/// information about retrying network connection lost errors, please refer to Apple's +/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). +open class ConnectionLostRetryPolicy: RetryPolicy, @unchecked Sendable { + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { + super.init(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: [], + retryableURLErrorCodes: [.networkConnectionLost]) + } +} + +extension RequestInterceptor where Self == ConnectionLostRetryPolicy { + /// Provides a default `ConnectionLostRetryPolicy` instance. + public static var connectionLostRetryPolicy: ConnectionLostRetryPolicy { ConnectionLostRetryPolicy() } + + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// + /// - Returns: The `ConnectionLostRetryPolicy`. + public static func connectionLostRetryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) -> ConnectionLostRetryPolicy { + ConnectionLostRetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/ServerTrustEvaluation.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/ServerTrustEvaluation.swift new file mode 100644 index 00000000..e290c367 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/ServerTrustEvaluation.swift @@ -0,0 +1,723 @@ +// +// ServerTrustEvaluation.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation +#if canImport(Security) +@preconcurrency import Security +#endif + +/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. +open class ServerTrustManager: @unchecked Sendable { + /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. + public let allHostsMustBeEvaluated: Bool + + /// The dictionary of policies mapped to a particular host. + public let evaluators: [String: any ServerTrustEvaluating] + + /// Initializes the `ServerTrustManager` instance with the given evaluators. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - Parameters: + /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` + /// by default. + /// - evaluators: A dictionary of evaluators mapped to hosts. + public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: any ServerTrustEvaluating]) { + self.allHostsMustBeEvaluated = allHostsMustBeEvaluated + self.evaluators = evaluators + } + + #if canImport(Security) + /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - Parameter host: The host to use when searching for a matching policy. + /// + /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. + /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching + /// evaluators are found. + open func serverTrustEvaluator(forHost host: String) throws -> (any ServerTrustEvaluating)? { + guard let evaluator = evaluators[host] else { + if allHostsMustBeEvaluated { + throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) + } + + return nil + } + + return evaluator + } + #endif +} + +/// A protocol describing the API used to evaluate server trusts. +public protocol ServerTrustEvaluating: Sendable { + #if !canImport(Security) + // Implement this once other platforms have API for evaluating server trusts. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. + func evaluate(_ trust: SecTrust, forHost host: String) throws + #endif +} + +// MARK: - Server Trust Evaluators + +#if canImport(Security) +/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the +/// host provided by the challenge. Applications are encouraged to always validate the host in production environments +/// to guarantee the validity of the server's certificate chain. +public final class DefaultTrustEvaluator: ServerTrustEvaluating { + private let validateHost: Bool + + /// Creates a `DefaultTrustEvaluator`. + /// + /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. + public init(validateHost: Bool = true) { + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if validateHost { + try trust.af.performValidation(forHost: host) + } + + try trust.af.performDefaultValidation(forHost: host) + } +} + +/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate +/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. +/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS +/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production +/// environments to guarantee the validity of the server's certificate chain. +public final class RevocationTrustEvaluator: ServerTrustEvaluating { + /// Represents the options to be use when evaluating the status of a certificate. + /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). + public struct Options: OptionSet, Sendable { + /// Perform revocation checking using the CRL (Certification Revocation List) method. + public static let crl = Options(rawValue: kSecRevocationCRLMethod) + /// Consult only locally cached replies; do not use network access. + public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) + /// Perform revocation checking using OCSP (Online Certificate Status Protocol). + public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) + /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. + public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) + /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a + /// "best attempt" basis, where failure to reach the server is not considered fatal. + public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) + /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the + /// certificate and the value of `preferCRL`. + public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) + + /// The raw value of the option. + public let rawValue: CFOptionFlags + + /// Creates an `Options` value with the given `CFOptionFlags`. + /// + /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. + public init(rawValue: CFOptionFlags) { + self.rawValue = rawValue + } + } + + private let performDefaultValidation: Bool + private let validateHost: Bool + private let options: Options + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` by + /// default. + public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + self.options = options + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + } +} + +extension ServerTrustEvaluating where Self == RevocationTrustEvaluator { + /// Provides a default `RevocationTrustEvaluator` instance. + public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() } + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` + /// by default. + /// - Returns: The `RevocationTrustEvaluator`. + public static func revocationChecking(performDefaultValidation: Bool = true, + validateHost: Bool = true, + options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator { + RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation, + validateHost: validateHost, + options: options) + } +} + +/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned +/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate +/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { + private let certificates: [SecCertificate] + private let acceptSelfSignedCertificates: Bool + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public init(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.certificates = certificates + self.acceptSelfSignedCertificates = acceptSelfSignedCertificates + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !certificates.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) + } + + if acceptSelfSignedCertificates { + try trust.af.setAnchorCertificates(certificates) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let serverCertificatesData = Set(trust.af.certificateData) + let pinnedCertificatesData = Set(certificates.af.data) + let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) + if !pinnedCertificatesInServerData { + throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, + trust: trust, + pinnedCertificates: certificates, + serverCertificates: trust.af.certificates)) + } + } +} + +extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator { + /// Provides a default `PinnedCertificatesTrustEvaluator` instance. + public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() } + + /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator { + PinnedCertificatesTrustEvaluator(certificates: certificates, + acceptSelfSignedCertificates: acceptSelfSignedCertificates, + performDefaultValidation: performDefaultValidation, + validateHost: validateHost) + } +} + +/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned +/// public keys match one of the server certificate public keys. By validating both the certificate chain and host, +/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { + private let keys: [SecKey] + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public init(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.keys = keys + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !keys.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let pinnedKeysInServerKeys: Bool = { + for serverPublicKey in trust.af.publicKeys { + if keys.contains(serverPublicKey) { + return true + } + } + return false + }() + + if !pinnedKeysInServerKeys { + throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, + trust: trust, + pinnedKeys: keys, + serverKeys: trust.af.publicKeys)) + } + } +} + +extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator { + /// Provides a default `PublicKeysTrustEvaluator` instance. + public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() } + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PublicKeysTrustEvaluator { + PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost) + } +} + +/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the +/// evaluators consider it valid. +public final class CompositeTrustEvaluator: ServerTrustEvaluating { + private let evaluators: [any ServerTrustEvaluating] + + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public init(evaluators: [any ServerTrustEvaluating]) { + self.evaluators = evaluators + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + try evaluators.evaluate(trust, forHost: host) + } +} + +extension ServerTrustEvaluating where Self == CompositeTrustEvaluator { + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public static func composite(evaluators: [any ServerTrustEvaluating]) -> CompositeTrustEvaluator { + CompositeTrustEvaluator(evaluators: evaluators) + } +} + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") +public typealias DisabledEvaluator = DisabledTrustEvaluator + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +public final class DisabledTrustEvaluator: ServerTrustEvaluating { + /// Creates an instance. + public init() {} + + public func evaluate(_ trust: SecTrust, forHost host: String) throws {} +} + +// MARK: - Extensions + +extension [ServerTrustEvaluating] { + #if os(Linux) || os(Windows) || os(Android) + // Add this same convenience method for Linux/Windows. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + for evaluator in self { + try evaluator.evaluate(trust, forHost: host) + } + } + #endif +} + +extension Bundle: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: Bundle { + /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. + public var certificates: [SecCertificate] { + paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in + guard + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } + + return certificate + } + } + + /// Returns all public keys for the valid certificates in the bundle. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// Returns all pathnames for the resources identified by the provided file extensions. + /// + /// - Parameter types: The filename extensions locate. + /// + /// - Returns: All pathnames for the given filename extensions. + public func paths(forResourcesOfTypes types: [String]) -> [String] { + Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) + } +} + +extension SecTrust: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrust { + /// Evaluates `self` after applying the `SecPolicy` value provided. + /// + /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. + /// + /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate(afterApplying policy: SecPolicy) throws { + try apply(policy: policy).af.evaluate() + } + + /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. + /// + /// - Parameters: + /// - policy: The `SecPolicy` used to evaluate `self`. + /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. + /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") + public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> any Error) throws { + try apply(policy: policy).af.validate(errorProducer: errorProducer) + } + + /// Applies a `SecPolicy` to `self`, throwing if it fails. + /// + /// - Parameter policy: The `SecPolicy`. + /// + /// - Returns: `self`, with the policy applied. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. + public func apply(policy: SecPolicy) throws -> SecTrust { + let status = SecTrustSetPolicies(type, policy) + + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, + policy: policy, + status: status)) + } + + return type + } + + /// Evaluate `self`, throwing an `Error` if evaluation fails. + /// + /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from + /// the underlying evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate() throws { + var error: CFError? + let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) + + if !evaluationSucceeded { + throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) + } + } + + /// Validate `self`, passing any failure values through `errorProducer`. + /// + /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an + /// `Error`. + /// - Throws: The `Error` produced by the `errorProducer` closure. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") + public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> any Error) throws { + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(type, &result) + + guard status.af.isSuccess && result.af.isSuccess else { + throw errorProducer(status, result) + } + } + + /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. + /// + /// - Parameter certificates: The `SecCertificate`s to add to the chain. + /// - Throws: Any error produced when applying the new certificate chain. + public func setAnchorCertificates(_ certificates: [SecCertificate]) throws { + // Add additional anchor certificates. + let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, + certificates: certificates)) + } + + // Trust only the set anchor certs. + let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true) + guard onlyStatus.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus, + certificates: certificates)) + } + } + + /// The public keys contained in `self`. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// The `SecCertificate`s contained in `self`. + public var certificates: [SecCertificate] { + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, visionOS 1, *) { + (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] + } else { + (0.. SecPolicy { + SecPolicyCreateSSL(true, hostname as CFString) + } + + /// Creates a `SecPolicy` which checks the revocation of certificates. + /// + /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. + /// + /// - Returns: The `SecPolicy`. + /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` + /// if the policy cannot be created. + public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { + guard let policy = SecPolicyCreateRevocation(options.rawValue) else { + throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) + } + + return policy + } +} + +extension Array: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == [SecCertificate] { + /// All `Data` values for the contained `SecCertificate`s. + public var data: [Data] { + type.map { SecCertificateCopyData($0) as Data } + } + + /// All public `SecKey` values for the contained `SecCertificate`s. + public var publicKeys: [SecKey] { + type.compactMap(\.af.publicKey) + } +} + +extension SecCertificate: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + /// + /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported. + /// + public var publicKey: SecKey? { + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) + + guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } + + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { + return SecTrustCopyKey(createdTrust) + } else { + return SecTrustCopyPublicKey(createdTrust) + } + } +} + +extension OSStatus: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == OSStatus { + /// Returns whether `self` is `errSecSuccess`. + public var isSuccess: Bool { type == errSecSuccess } +} + +extension SecTrustResultType: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrustResultType { + /// Returns whether `self` is `.unspecified` or `.proceed`. + public var isSuccess: Bool { + type == .unspecified || type == .proceed + } +} +#endif diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/URLEncodedFormEncoder.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/URLEncodedFormEncoder.swift new file mode 100644 index 00000000..dab6791b --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/URLEncodedFormEncoder.swift @@ -0,0 +1,1151 @@ +// +// URLEncodedFormEncoder.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An object that encodes instances into URL-encoded query strings. +/// +/// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is +/// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`. +/// +/// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used, +/// encoding `true` as `1` and `false` as `0`. +/// +/// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is +/// used, which encodes `Data` values using their default `Encodable` implementation. +/// +/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` +/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. +/// +/// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, +/// which encodes the keys directly from the `Encodable` implementation. +/// +/// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets` +/// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`. +/// +/// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding +/// is used, which drops `nil` key / value pairs from the output entirely. +/// +/// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used, +/// replacing spaces with `%20`. +/// +/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. +public final class URLEncodedFormEncoder { + /// Encoding to use for `Array` values. + public enum ArrayEncoding { + /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. + case brackets + /// No brackets are appended to the key and the key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + /// Encodes the key according to the encoding. + /// + /// - Parameters: + /// - key: The `key` to encode. + /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode. + /// + /// - Returns: The encoded key. + func encode(_ key: String, atIndex index: Int) -> String { + switch self { + case .brackets: "\(key)[]" + case .noBrackets: key + case .indexInBrackets: "\(key)[\(index)]" + case let .custom(encoding): encoding(key, index) + } + } + } + + /// Encoding to use for `Bool` values. + public enum BoolEncoding { + /// Encodes `true` as `1`, `false` as `0`. + case numeric + /// Encodes `true` as "true", `false` as "false". This is the default encoding. + case literal + + /// Encodes the given `Bool` as a `String`. + /// + /// - Parameter value: The `Bool` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ value: Bool) -> String { + switch self { + case .numeric: value ? "1" : "0" + case .literal: value ? "true" : "false" + } + } + } + + /// Encoding to use for `Data` values. + public enum DataEncoding { + /// Defers encoding to the `Data` type. + case deferredToData + /// Encodes `Data` as a Base64-encoded string. This is the default encoding. + case base64 + /// Encode the `Data` as a custom value encoded by the given closure. + case custom((Data) throws -> String) + + /// Encodes `Data` according to the encoding. + /// + /// - Parameter data: The `Data` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its + /// `Encodable` implementation. + func encode(_ data: Data) throws -> String? { + switch self { + case .deferredToData: nil + case .base64: data.base64EncodedString() + case let .custom(encoding): try encoding(data) + } + } + } + + /// Encoding to use for `Date` values. + public enum DateEncoding { + /// ISO8601 and RFC3339 formatter. + private static let iso8601Formatter = Protected({ + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }()) + + /// Defers encoding to the `Date` type. This is the default encoding. + case deferredToDate + /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. + case secondsSince1970 + /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. + case millisecondsSince1970 + /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. + case iso8601 + /// Encodes `Date`s using the given `DateFormatter`. + case formatted(DateFormatter) + /// Encodes `Date`s using the given closure. + case custom((Date) throws -> String) + + /// Encodes the date according to the encoding. + /// + /// - Parameter date: The `Date` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its + /// `Encodable` implementation. + func encode(_ date: Date) throws -> String? { + switch self { + case .deferredToDate: + nil + case .secondsSince1970: + String(date.timeIntervalSince1970) + case .millisecondsSince1970: + String(date.timeIntervalSince1970 * 1000.0) + case .iso8601: + DateEncoding.iso8601Formatter.read { $0.string(from: date) } + case let .formatted(formatter): + formatter.string(from: date) + case let .custom(closure): + try closure(date) + } + } + } + + /// Encoding to use for keys. + /// + /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) + /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). + public enum KeyEncoding { + /// Use the keys specified by each type. This is the default encoding. + case useDefaultKeys + /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. + /// + /// Capital characters are determined by testing membership in + /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` + /// (Unicode General Categories Lu and Lt). + /// The conversion to lower case uses `Locale.system`, also known as + /// the ICU "root" locale. This means the result is consistent + /// regardless of the current user's locale and language preferences. + /// + /// Converting from camel case to snake case: + /// 1. Splits words at the boundary of lower-case to upper-case + /// 2. Inserts `_` between words + /// 3. Lowercases the entire string + /// 4. Preserves starting and ending `_`. + /// + /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. + /// + /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. + case convertToSnakeCase + /// Same as convertToSnakeCase, but using `-` instead of `_`. + /// For example `oneTwoThree` becomes `one-two-three`. + case convertToKebabCase + /// Capitalize the first letter only. + /// For example `oneTwoThree` becomes `OneTwoThree`. + case capitalized + /// Uppercase all letters. + /// For example `oneTwoThree` becomes `ONETWOTHREE`. + case uppercased + /// Lowercase all letters. + /// For example `oneTwoThree` becomes `onetwothree`. + case lowercased + /// A custom encoding using the provided closure. + case custom((String) -> String) + + func encode(_ key: String) -> String { + switch self { + case .useDefaultKeys: key + case .convertToSnakeCase: convertToSnakeCase(key) + case .convertToKebabCase: convertToKebabCase(key) + case .capitalized: String(key.prefix(1).uppercased() + key.dropFirst()) + case .uppercased: key.uppercased() + case .lowercased: key.lowercased() + case let .custom(encoding): encoding(key) + } + } + + private func convertToSnakeCase(_ key: String) -> String { + convert(key, usingSeparator: "_") + } + + private func convertToKebabCase(_ key: String) -> String { + convert(key, usingSeparator: "-") + } + + private func convert(_ key: String, usingSeparator separator: String) -> String { + guard !key.isEmpty else { return key } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on + // transition from lower to upper case, then on transition of >1 + // upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = key.startIndex + var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before + // the lower case character. + let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. String + + /// Creates an instance with the encoding closure called for each sub-key in a key path. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping @Sendable (_ subkey: String) -> String) { + self.encoding = encoding + } + + func encodeKeyPath(_ keyPath: String) -> String { + encoding(keyPath) + } + } + + /// Encoding to use for `nil` values. + public struct NilEncoding: Sendable { + /// Encodes `nil` by dropping the entire key / value pair. + public static let dropKey = NilEncoding { nil } + /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`. + public static let dropValue = NilEncoding { "" } + /// Encodes `nil` as `null`. + public static let null = NilEncoding { "null" } + + private let encoding: @Sendable () -> String? + + /// Creates an instance with the encoding closure called for `nil` values. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping @Sendable () -> String?) { + self.encoding = encoding + } + + func encodeNil() -> String? { + encoding() + } + } + + /// Encoding to use for spaces. + public enum SpaceEncoding { + /// Encodes spaces using percent escaping (`%20`). + case percentEscaped + /// Encodes spaces as `+`. + case plusReplaced + + /// Encodes the string according to the encoding. + /// + /// - Parameter string: The `String` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ string: String) -> String { + switch self { + case .percentEscaped: string.replacingOccurrences(of: " ", with: "%20") + case .plusReplaced: string.replacingOccurrences(of: " ", with: "+") + } + } + } + + /// `URLEncodedFormEncoder` error. + public enum Error: Swift.Error { + /// An invalid root object was created by the encoder. Only keyed values are valid. + case invalidRootObject(String) + + var localizedDescription: String { + switch self { + case let .invalidRootObject(object): + "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." + } + } + } + + /// Whether or not to sort the encoded key value pairs. + /// + /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, + /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to + /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. + public let alphabetizeKeyValuePairs: Bool + /// The `ArrayEncoding` to use. + public let arrayEncoding: ArrayEncoding + /// The `BoolEncoding` to use. + public let boolEncoding: BoolEncoding + /// THe `DataEncoding` to use. + public let dataEncoding: DataEncoding + /// The `DateEncoding` to use. + public let dateEncoding: DateEncoding + /// The `KeyEncoding` to use. + public let keyEncoding: KeyEncoding + /// The `KeyPathEncoding` to use. + public let keyPathEncoding: KeyPathEncoding + /// The `NilEncoding` to use. + public let nilEncoding: NilEncoding + /// The `SpaceEncoding` to use. + public let spaceEncoding: SpaceEncoding + /// The `CharacterSet` of allowed (non-escaped) characters. + public var allowedCharacters: CharacterSet + + /// Creates an instance from the supplied parameters. + /// + /// - Parameters: + /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. + /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. + /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. + /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. + /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. + /// - nilEncoding: The `NilEncoding` to use. `.drop` by default. + /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. + /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by + /// default. + public init(alphabetizeKeyValuePairs: Bool = true, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric, + dataEncoding: DataEncoding = .base64, + dateEncoding: DateEncoding = .deferredToDate, + keyEncoding: KeyEncoding = .useDefaultKeys, + keyPathEncoding: KeyPathEncoding = .brackets, + nilEncoding: NilEncoding = .dropKey, + spaceEncoding: SpaceEncoding = .percentEscaped, + allowedCharacters: CharacterSet = .afURLQueryAllowed) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.nilEncoding = nilEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func encode(_ value: any Encodable) throws -> URLEncodedFormComponent { + let context = URLEncodedFormContext(.object([])) + let encoder = _URLEncodedFormEncoder(context: context, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + + return context.component + } + + /// Encodes the `value` as a URL form encoded `String`. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `String`. + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: any Encodable) throws -> String { + let component: URLEncodedFormComponent = try encode(value) + + guard case let .object(object) = component else { + throw Error.invalidRootObject("\(component)") + } + + let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, + arrayEncoding: arrayEncoding, + keyEncoding: keyEncoding, + keyPathEncoding: keyPathEncoding, + spaceEncoding: spaceEncoding, + allowedCharacters: allowedCharacters) + let query = serializer.serialize(object) + + return query + } + + /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the + /// `.utf8` data. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `Data`. + /// + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: any Encodable) throws -> Data { + let string: String = try encode(value) + + return Data(string.utf8) + } +} + +final class _URLEncodedFormEncoder { + var codingPath: [any CodingKey] + // Returns an empty dictionary, as this encoder doesn't support userInfo. + var userInfo: [CodingUserInfoKey: Any] { [:] } + + let context: URLEncodedFormContext + + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [any CodingKey] = [], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } +} + +extension _URLEncodedFormEncoder: Encoder { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> any UnkeyedEncodingContainer { + _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func singleValueContainer() -> any SingleValueEncodingContainer { + _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormContext { + var component: URLEncodedFormComponent + + init(_ component: URLEncodedFormComponent) { + self.component = component + } +} + +enum URLEncodedFormComponent { + typealias Object = [(key: String, value: URLEncodedFormComponent)] + + case string(String) + case array([URLEncodedFormComponent]) + case object(Object) + + /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. + var array: [URLEncodedFormComponent]? { + switch self { + case let .array(array): array + default: nil + } + } + + /// Converts self to an `Object` or returns `nil` if not convertible. + var object: Object? { + switch self { + case let .object(object): object + default: nil + } + } + + /// Sets self to the supplied value at a given path. + /// + /// data.set(to: "hello", at: ["path", "to", "value"]) + /// + /// - parameters: + /// - value: Value of `Self` to set at the supplied path. + /// - path: `CodingKey` path to update with the supplied value. + public mutating func set(to value: URLEncodedFormComponent, at path: [any CodingKey]) { + set(&self, to: value, at: path) + } + + /// Recursive backing method to `set(to:at:)`. + private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [any CodingKey]) { + guard !path.isEmpty else { + context = value + return + } + + let end = path[0] + var child: URLEncodedFormComponent + switch path.count { + case 1: + child = value + case 2...: + if let index = end.intValue { + let array = context.array ?? [] + if array.count > index { + child = array[index] + } else { + child = .array([]) + } + set(&child, to: value, at: Array(path[1...])) + } else { + child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) + set(&child, to: value, at: Array(path[1...])) + } + default: fatalError("Unreachable") + } + + if let index = end.intValue { + if var array = context.array { + if array.count > index { + array[index] = child + } else { + array.append(child) + } + context = .array(array) + } else { + context = .array([child]) + } + } else { + if var object = context.object { + if let index = object.firstIndex(where: { $0.key == end.stringValue }) { + object[index] = (key: end.stringValue, value: child) + } else { + object.append((key: end.stringValue, value: child)) + } + context = .object(object) + } else { + context = .object([(key: end.stringValue, value: child)]) + } + } + } +} + +struct AnyCodingKey: CodingKey, Hashable { + let stringValue: String + let intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } + + init(_ base: Key) where Key: CodingKey { + if let intValue = base.intValue { + self.init(intValue: intValue)! + } else { + self.init(stringValue: base.stringValue)! + } + } +} + +extension _URLEncodedFormEncoder { + final class KeyedContainer where Key: CodingKey { + var codingPath: [any CodingKey] + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [any CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func nestedCodingPath(for key: any CodingKey) -> [any CodingKey] { + codingPath + [key] + } + } +} + +extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { + func encodeNil(forKey key: Key) throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue, forKey: key) + } + + func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: String?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Double?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Float?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Value?, forKey key: Key) throws where Value: Encodable { + try _encodeIfPresent(value, forKey: key) + } + + func _encodeIfPresent(_ value: Value?, forKey key: Key) throws where Value: Encodable { + if let value { + try encode(value, forKey: key) + } else { + try encodeNil(forKey: key) + } + } + + func encode(_ value: T, forKey key: Key) throws where T: Encodable { + var container = nestedSingleValueEncoder(for: key) + try container.encode(value) + } + + func nestedSingleValueEncoder(for key: Key) -> any SingleValueEncodingContainer { + let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedUnkeyedContainer(forKey key: Key) -> any UnkeyedEncodingContainer { + let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> any Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder(forKey key: Key) -> any Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +extension _URLEncodedFormEncoder { + final class SingleValueContainer { + var codingPath: [any CodingKey] + + private var canEncodeNewValue = true + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [any CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func checkCanEncode(value: Any?) throws { + guard canEncodeNewValue else { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "Attempt to encode value through single value container when previously value already encoded.") + throw EncodingError.invalidValue(value as Any, context) + } + } + } +} + +extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: Bool) throws { + try encode(value, as: String(boolEncoding.encode(value))) + } + + func encode(_ value: String) throws { + try encode(value, as: value) + } + + func encode(_ value: Double) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Float) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int64) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt64) throws { + try encode(value, as: String(value)) + } + + private func encode(_ value: T, as string: String) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + context.component.set(to: .string(string), at: codingPath) + } + + func encode(_ value: T) throws where T: Encodable { + switch value { + case let date as Date: + guard let string = try dateEncoding.encode(date) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let data as Data: + guard let string = try dataEncoding.encode(data) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let decimal as Decimal: + // Decimal's `Encodable` implementation returns an object, not a single value, so override it. + try encode(value, as: String(describing: decimal)) + default: + try attemptToEncode(value) + } + } + + private func attemptToEncode(_ value: T) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + let encoder = _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + } +} + +extension _URLEncodedFormEncoder { + final class UnkeyedContainer { + var codingPath: [any CodingKey] + + var count = 0 + var nestedCodingPath: [any CodingKey] { + codingPath + [AnyCodingKey(intValue: count)!] + } + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [any CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + } +} + +extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: T) throws where T: Encodable { + var container = nestedSingleValueContainer() + try container.encode(value) + } + + func nestedSingleValueContainer() -> any SingleValueEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { + defer { count += 1 } + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder() -> any Encoder { + defer { count += 1 } + + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormSerializer { + private let alphabetizeKeyValuePairs: Bool + private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(alphabetizeKeyValuePairs: Bool, + arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func serialize(_ object: URLEncodedFormComponent.Object) -> String { + var output: [String] = [] + for (key, component) in object { + let value = serialize(component, forKey: key) + output.append(value) + } + output = alphabetizeKeyValuePairs ? output.sorted() : output + + return output.joinedWithAmpersands() + } + + func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { + switch component { + case let .string(string): "\(escape(keyEncoding.encode(key)))=\(escape(string))" + case let .array(array): serialize(array, forKey: key) + case let .object(object): serialize(object, forKey: key) + } + } + + func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { + var segments: [String] = object.map { subKey, value in + let keyPath = keyPathEncoding.encodeKeyPath(subKey) + return serialize(value, forKey: key + keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { + var segments: [String] = array.enumerated().map { index, component in + let keyPath = arrayEncoding.encode(key, atIndex: index) + return serialize(component, forKey: keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func escape(_ query: String) -> String { + var allowedCharactersWithSpace = allowedCharacters + allowedCharactersWithSpace.insert(charactersIn: " ") + let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query + let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) + + return spaceEncodedQuery + } +} + +extension [String] { + func joinedWithAmpersands() -> String { + joined(separator: "&") + } +} + +extension CharacterSet { + /// Creates a CharacterSet from RFC 3986 allowed characters. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + public static let afURLQueryAllowed: CharacterSet = { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) + }() +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Validation.swift b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Validation.swift new file mode 100644 index 00000000..8c229136 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/Features/Validation.swift @@ -0,0 +1,308 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether a validation succeeded or failed. + public typealias ValidationResult = Result + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + true + default: + false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: Range { 200..<300 } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate(statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int { + if acceptableStatusCodes.contains(response.statusCode) { + return .success(()) + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse, + isEmpty: Bool) + -> ValidationResult + where S.Iterator.Element == String { + guard !isEmpty else { return .success(()) } + + return validate(contentType: acceptableContentTypes, response: response) + } + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == String { + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted()) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(), + responseContentType: responseContentType) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = @Sendable (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int, S: Sendable { + validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @preconcurrency + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S.Iterator.Element == String, S: Sendable { + validate { [unowned self] _, response, data in + self.validate(contentType: acceptableContentTypes(), response: response, isEmpty: (data == nil || data?.isEmpty == true)) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes: @Sendable () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +extension DataStreamRequest { + /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the + /// request was valid. + public typealias Validation = @Sendable (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int, S: Sendable { + validate { [unowned self] _, response in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @preconcurrency + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S.Iterator.Element == String, S: Sendable { + validate { [unowned self] _, response in + self.validate(contentType: acceptableContentTypes(), response: response) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Returns: The instance. + @discardableResult + public func validate() -> Self { + let contentTypes: @Sendable () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = @Sendable (_ request: URLRequest?, + _ response: HTTPURLResponse, + _ fileURL: URL?) + -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @preconcurrency + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int, S: Sendable { + validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a `Content-Type` in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @preconcurrency + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S.Iterator.Element == String, S: Sendable { + validate { [unowned self] _, response, fileURL in + guard let fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let isEmpty = try (fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0 + return self.validate(contentType: acceptableContentTypes(), response: response, isEmpty: isEmpty) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: fileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes: @Sendable () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} diff --git a/src/ios/asyncgate_iOS/Pods/Alamofire/Source/PrivacyInfo.xcprivacy b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..488cbb11 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Alamofire/Source/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/KeychainAccess/LICENSE b/src/ios/asyncgate_iOS/Pods/KeychainAccess/LICENSE new file mode 100644 index 00000000..7ab2a8ee --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/KeychainAccess/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 kishikawa katsumi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/src/ios/asyncgate_iOS/Pods/KeychainAccess/Lib/KeychainAccess/Keychain.swift b/src/ios/asyncgate_iOS/Pods/KeychainAccess/Lib/KeychainAccess/Keychain.swift new file mode 100644 index 00000000..aaecf049 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/KeychainAccess/Lib/KeychainAccess/Keychain.swift @@ -0,0 +1,3074 @@ +// +// Keychain.swift +// KeychainAccess +// +// Created by kishikawa katsumi on 2014/12/24. +// Copyright (c) 2014 kishikawa katsumi. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import Security +#if os(iOS) || os(OSX) +import LocalAuthentication +#endif + +public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error" + +public enum ItemClass { + case genericPassword + case internetPassword +} + +public enum ProtocolType { + case ftp + case ftpAccount + case http + case irc + case nntp + case pop3 + case smtp + case socks + case imap + case ldap + case appleTalk + case afp + case telnet + case ssh + case ftps + case https + case httpProxy + case httpsProxy + case ftpProxy + case smb + case rtsp + case rtspProxy + case daap + case eppc + case ipp + case nntps + case ldaps + case telnetS + case imaps + case ircs + case pop3S +} + +public enum AuthenticationType { + case ntlm + case msn + case dpa + case rpa + case httpBasic + case httpDigest + case htmlForm + case `default` +} + +public enum Accessibility { + /** + Item data can only be accessed + while the device is unlocked. This is recommended for items that only + need be accesible while the application is in the foreground. Items + with this attribute will migrate to a new device when using encrypted + backups. + */ + case whenUnlocked + + /** + Item data can only be + accessed once the device has been unlocked after a restart. This is + recommended for items that need to be accesible by background + applications. Items with this attribute will migrate to a new device + when using encrypted backups. + */ + case afterFirstUnlock + + /** + Item data can always be accessed + regardless of the lock state of the device. This is not recommended + for anything except system use. Items with this attribute will migrate + to a new device when using encrypted backups. + */ + @available(macCatalyst, unavailable) + case always + + /** + Item data can + only be accessed while the device is unlocked. This class is only + available if a passcode is set on the device. This is recommended for + items that only need to be accessible while the application is in the + foreground. Items with this attribute will never migrate to a new + device, so after a backup is restored to a new device, these items + will be missing. No items can be stored in this class on devices + without a passcode. Disabling the device passcode will cause all + items in this class to be deleted. + */ + @available(iOS 8.0, OSX 10.10, *) + case whenPasscodeSetThisDeviceOnly + + /** + Item data can only + be accessed while the device is unlocked. This is recommended for items + that only need be accesible while the application is in the foreground. + Items with this attribute will never migrate to a new device, so after + a backup is restored to a new device, these items will be missing. + */ + case whenUnlockedThisDeviceOnly + + /** + Item data can + only be accessed once the device has been unlocked after a restart. + This is recommended for items that need to be accessible by background + applications. Items with this attribute will never migrate to a new + device, so after a backup is restored to a new device these items will + be missing. + */ + case afterFirstUnlockThisDeviceOnly + + /** + Item data can always + be accessed regardless of the lock state of the device. This option + is not recommended for anything except system use. Items with this + attribute will never migrate to a new device, so after a backup is + restored to a new device, these items will be missing. + */ + @available(macCatalyst, unavailable) + case alwaysThisDeviceOnly +} + +/** + Predefined item attribute constants used to get or set values + in a dictionary. The kSecUseAuthenticationUI constant is the key and its + value is one of the constants defined here. + If the key kSecUseAuthenticationUI not provided then kSecUseAuthenticationUIAllow + is used as default. + */ +public enum AuthenticationUI { + /** + Specifies that authenticate UI can appear. + */ + case allow + + /** + Specifies that the error + errSecInteractionNotAllowed will be returned if an item needs + to authenticate with UI + */ + case fail + + /** + Specifies that all items which need + to authenticate with UI will be silently skipped. This value can be used + only with SecItemCopyMatching. + */ + case skip +} + +@available(iOS 9.0, OSX 10.11, *) +extension AuthenticationUI { + public var rawValue: String { + switch self { + case .allow: + return UseAuthenticationUIAllow + case .fail: + return UseAuthenticationUIFail + case .skip: + return UseAuthenticationUISkip + } + } + + public var description: String { + switch self { + case .allow: + return "allow" + case .fail: + return "fail" + case .skip: + return "skip" + } + } +} + +public struct AuthenticationPolicy: OptionSet { + /** + User presence policy using Touch ID or Passcode. Touch ID does not + have to be available or enrolled. Item is still accessible by Touch ID + even if fingers are added or removed. + */ + @available(iOS 8.0, OSX 10.10, watchOS 2.0, tvOS 8.0, *) + public static let userPresence = AuthenticationPolicy(rawValue: 1 << 0) + + /** + Constraint: Touch ID (any finger) or Face ID. Touch ID or Face ID must be available. With Touch ID + at least one finger must be enrolled. With Face ID user has to be enrolled. Item is still accessible by Touch ID even + if fingers are added or removed. Item is still accessible by Face ID if user is re-enrolled. + */ + @available(iOS 11.3, OSX 10.13.4, watchOS 4.3, tvOS 11.3, *) + public static let biometryAny = AuthenticationPolicy(rawValue: 1 << 1) + + /** + Deprecated, please use biometryAny instead. + */ + @available(iOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryAny") + @available(OSX, introduced: 10.12.1, deprecated: 10.13.4, renamed: "biometryAny") + @available(watchOS, introduced: 2.0, deprecated: 4.3, renamed: "biometryAny") + @available(tvOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryAny") + public static let touchIDAny = AuthenticationPolicy(rawValue: 1 << 1) + + /** + Constraint: Touch ID from the set of currently enrolled fingers. Touch ID must be available and at least one finger must + be enrolled. When fingers are added or removed, the item is invalidated. When Face ID is re-enrolled this item is invalidated. + */ + @available(iOS 11.3, OSX 10.13, watchOS 4.3, tvOS 11.3, *) + public static let biometryCurrentSet = AuthenticationPolicy(rawValue: 1 << 3) + + /** + Deprecated, please use biometryCurrentSet instead. + */ + @available(iOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryCurrentSet") + @available(OSX, introduced: 10.12.1, deprecated: 10.13.4, renamed: "biometryCurrentSet") + @available(watchOS, introduced: 2.0, deprecated: 4.3, renamed: "biometryCurrentSet") + @available(tvOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryCurrentSet") + public static let touchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3) + + /** + Constraint: Device passcode + */ + @available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *) + public static let devicePasscode = AuthenticationPolicy(rawValue: 1 << 4) + + /** + Constraint: Watch + */ + @available(iOS, unavailable) + @available(OSX 10.15, *) + @available(watchOS, unavailable) + @available(tvOS, unavailable) + public static let watch = AuthenticationPolicy(rawValue: 1 << 5) + + /** + Constraint logic operation: when using more than one constraint, + at least one of them must be satisfied. + */ + @available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *) + public static let or = AuthenticationPolicy(rawValue: 1 << 14) + + /** + Constraint logic operation: when using more than one constraint, + all must be satisfied. + */ + @available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *) + public static let and = AuthenticationPolicy(rawValue: 1 << 15) + + /** + Create access control for private key operations (i.e. sign operation) + */ + @available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *) + public static let privateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30) + + /** + Security: Application provided password for data encryption key generation. + This is not a constraint but additional item encryption mechanism. + */ + @available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *) + public static let applicationPassword = AuthenticationPolicy(rawValue: 1 << 31) + + #if swift(>=2.3) + public let rawValue: UInt + + public init(rawValue: UInt) { + self.rawValue = rawValue + } + #else + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + #endif +} + +public struct Attributes { + public var `class`: String? { + return attributes[Class] as? String + } + public var data: Data? { + return attributes[ValueData] as? Data + } + public var ref: Data? { + return attributes[ValueRef] as? Data + } + public var persistentRef: Data? { + return attributes[ValuePersistentRef] as? Data + } + + public var accessible: String? { + return attributes[AttributeAccessible] as? String + } + public var accessControl: SecAccessControl? { + if #available(OSX 10.10, *) { + if let accessControl = attributes[AttributeAccessControl] { + return (accessControl as! SecAccessControl) + } + return nil + } else { + return nil + } + } + public var accessGroup: String? { + return attributes[AttributeAccessGroup] as? String + } + public var synchronizable: Bool? { + return attributes[AttributeSynchronizable] as? Bool + } + public var creationDate: Date? { + return attributes[AttributeCreationDate] as? Date + } + public var modificationDate: Date? { + return attributes[AttributeModificationDate] as? Date + } + public var attributeDescription: String? { + return attributes[AttributeDescription] as? String + } + public var comment: String? { + return attributes[AttributeComment] as? String + } + public var creator: String? { + return attributes[AttributeCreator] as? String + } + public var type: String? { + return attributes[AttributeType] as? String + } + public var label: String? { + return attributes[AttributeLabel] as? String + } + public var isInvisible: Bool? { + return attributes[AttributeIsInvisible] as? Bool + } + public var isNegative: Bool? { + return attributes[AttributeIsNegative] as? Bool + } + public var account: String? { + return attributes[AttributeAccount] as? String + } + public var service: String? { + return attributes[AttributeService] as? String + } + public var generic: Data? { + return attributes[AttributeGeneric] as? Data + } + public var securityDomain: String? { + return attributes[AttributeSecurityDomain] as? String + } + public var server: String? { + return attributes[AttributeServer] as? String + } + public var `protocol`: String? { + return attributes[AttributeProtocol] as? String + } + public var authenticationType: String? { + return attributes[AttributeAuthenticationType] as? String + } + public var port: Int? { + return attributes[AttributePort] as? Int + } + public var path: String? { + return attributes[AttributePath] as? String + } + + fileprivate let attributes: [String: Any] + + init(attributes: [String: Any]) { + self.attributes = attributes + } + + public subscript(key: String) -> Any? { + get { + return attributes[key] + } + } +} + +public final class Keychain { + public var itemClass: ItemClass { + return options.itemClass + } + + public var service: String { + return options.service + } + + // This attribute (kSecAttrAccessGroup) applies to macOS keychain items only if you also set a value of true for the + // kSecUseDataProtectionKeychain key, the kSecAttrSynchronizable key, or both. + public var accessGroup: String? { + return options.accessGroup + } + + public var server: URL { + return options.server + } + + public var protocolType: ProtocolType { + return options.protocolType + } + + public var authenticationType: AuthenticationType { + return options.authenticationType + } + + public var accessibility: Accessibility { + return options.accessibility + } + + @available(iOS 8.0, OSX 10.10, *) + @available(watchOS, unavailable) + public var authenticationPolicy: AuthenticationPolicy? { + return options.authenticationPolicy + } + + public var synchronizable: Bool { + return options.synchronizable + } + + public var label: String? { + return options.label + } + + public var comment: String? { + return options.comment + } + + @available(iOS 8.0, OSX 10.10, *) + @available(watchOS, unavailable) + public var authenticationPrompt: String? { + return options.authenticationPrompt + } + + @available(iOS 9.0, OSX 10.11, *) + public var authenticationUI: AuthenticationUI { + return options.authenticationUI ?? .allow + } + + #if os(iOS) || os(OSX) + @available(iOS 9.0, OSX 10.11, *) + public var authenticationContext: LAContext? { + return options.authenticationContext as? LAContext + } + #endif + + fileprivate let options: Options + + // MARK: + + public convenience init() { + var options = Options() + if let bundleIdentifier = Bundle.main.bundleIdentifier { + options.service = bundleIdentifier + } + self.init(options) + } + + public convenience init(service: String) { + var options = Options() + options.service = service + self.init(options) + } + + public convenience init(accessGroup: String) { + var options = Options() + if let bundleIdentifier = Bundle.main.bundleIdentifier { + options.service = bundleIdentifier + } + options.accessGroup = accessGroup + self.init(options) + } + + public convenience init(service: String, accessGroup: String) { + var options = Options() + options.service = service + options.accessGroup = accessGroup + self.init(options) + } + + public convenience init(server: String, protocolType: ProtocolType, accessGroup: String? = nil, authenticationType: AuthenticationType = .default) { + self.init(server: URL(string: server)!, protocolType: protocolType, accessGroup: accessGroup, authenticationType: authenticationType) + } + + public convenience init(server: URL, protocolType: ProtocolType, accessGroup: String? = nil, authenticationType: AuthenticationType = .default) { + var options = Options() + options.itemClass = .internetPassword + options.server = server + options.protocolType = protocolType + options.accessGroup = accessGroup + options.authenticationType = authenticationType + self.init(options) + } + + fileprivate init(_ opts: Options) { + options = opts + } + + // MARK: + + public func accessibility(_ accessibility: Accessibility) -> Keychain { + var options = self.options + options.accessibility = accessibility + return Keychain(options) + } + + @available(iOS 8.0, OSX 10.10, *) + @available(watchOS, unavailable) + public func accessibility(_ accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain { + var options = self.options + options.accessibility = accessibility + options.authenticationPolicy = authenticationPolicy + return Keychain(options) + } + + public func synchronizable(_ synchronizable: Bool) -> Keychain { + var options = self.options + options.synchronizable = synchronizable + return Keychain(options) + } + + public func label(_ label: String) -> Keychain { + var options = self.options + options.label = label + return Keychain(options) + } + + public func comment(_ comment: String) -> Keychain { + var options = self.options + options.comment = comment + return Keychain(options) + } + + public func attributes(_ attributes: [String: Any]) -> Keychain { + var options = self.options + attributes.forEach { options.attributes.updateValue($1, forKey: $0) } + return Keychain(options) + } + + @available(iOS 8.0, OSX 10.10, *) + @available(watchOS, unavailable) + public func authenticationPrompt(_ authenticationPrompt: String) -> Keychain { + var options = self.options + options.authenticationPrompt = authenticationPrompt + return Keychain(options) + } + + @available(iOS 9.0, OSX 10.11, *) + public func authenticationUI(_ authenticationUI: AuthenticationUI) -> Keychain { + var options = self.options + options.authenticationUI = authenticationUI + return Keychain(options) + } + + #if os(iOS) || os(OSX) + @available(iOS 9.0, OSX 10.11, *) + public func authenticationContext(_ authenticationContext: LAContext) -> Keychain { + var options = self.options + options.authenticationContext = authenticationContext + return Keychain(options) + } + #endif + + // MARK: + + public func get(_ key: String, ignoringAttributeSynchronizable: Bool = true) throws -> String? { + return try getString(key, ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) + } + + public func getString(_ key: String, ignoringAttributeSynchronizable: Bool = true) throws -> String? { + guard let data = try getData(key, ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) else { + return nil + } + guard let string = String(data: data, encoding: .utf8) else { + print("failed to convert data to string") + throw Status.conversionError + } + return string + } + + public func getData(_ key: String, ignoringAttributeSynchronizable: Bool = true) throws -> Data? { + var query = options.query(ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) + + query[MatchLimit] = MatchLimitOne + query[ReturnData] = kCFBooleanTrue + + query[AttributeAccount] = key + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + switch status { + case errSecSuccess: + guard let data = result as? Data else { + throw Status.unexpectedError + } + return data + case errSecItemNotFound: + return nil + default: + throw securityError(status: status) + } + } + + public func get(_ key: String, ignoringAttributeSynchronizable: Bool = true, handler: (Attributes?) -> T) throws -> T { + var query = options.query(ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) + + query[MatchLimit] = MatchLimitOne + + query[ReturnData] = kCFBooleanTrue + query[ReturnAttributes] = kCFBooleanTrue + query[ReturnRef] = kCFBooleanTrue + query[ReturnPersistentRef] = kCFBooleanTrue + + query[AttributeAccount] = key + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + switch status { + case errSecSuccess: + guard let attributes = result as? [String: Any] else { + throw Status.unexpectedError + } + return handler(Attributes(attributes: attributes)) + case errSecItemNotFound: + return handler(nil) + default: + throw securityError(status: status) + } + } + + // MARK: + + public func set(_ value: String, key: String, ignoringAttributeSynchronizable: Bool = true) throws { + guard let data = value.data(using: .utf8, allowLossyConversion: false) else { + print("failed to convert string to data") + throw Status.conversionError + } + try set(data, key: key, ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) + } + + public func set(_ value: Data, key: String, ignoringAttributeSynchronizable: Bool = true) throws { + var query = options.query(ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) + query[AttributeAccount] = key + #if os(iOS) + if #available(iOS 9.0, *) { + if let authenticationUI = options.authenticationUI { + query[UseAuthenticationUI] = authenticationUI.rawValue + } else { + query[UseAuthenticationUI] = UseAuthenticationUIFail + } + } else { + query[UseNoAuthenticationUI] = kCFBooleanTrue + } + #elseif os(OSX) + query[ReturnData] = kCFBooleanTrue + if #available(OSX 10.11, *) { + if let authenticationUI = options.authenticationUI { + query[UseAuthenticationUI] = authenticationUI.rawValue + } else { + query[UseAuthenticationUI] = UseAuthenticationUIFail + } + } + #else + if let authenticationUI = options.authenticationUI { + query[UseAuthenticationUI] = authenticationUI.rawValue + } + #endif + + var status = SecItemCopyMatching(query as CFDictionary, nil) + switch status { + case errSecSuccess, errSecInteractionNotAllowed: + var query = options.query() + query[AttributeAccount] = key + + var (attributes, error) = options.attributes(key: nil, value: value) + if let error = error { + print(error.localizedDescription) + throw error + } + + options.attributes.forEach { attributes.updateValue($1, forKey: $0) } + + #if os(iOS) + if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) { + try remove(key) + try set(value, key: key) + } else { + status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) + if status != errSecSuccess { + throw securityError(status: status) + } + } + #else + status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) + if status != errSecSuccess { + throw securityError(status: status) + } + #endif + case errSecItemNotFound: + var (attributes, error) = options.attributes(key: key, value: value) + if let error = error { + print(error.localizedDescription) + throw error + } + + options.attributes.forEach { attributes.updateValue($1, forKey: $0) } + + status = SecItemAdd(attributes as CFDictionary, nil) + if status != errSecSuccess { + throw securityError(status: status) + } + default: + throw securityError(status: status) + } + } + + public subscript(key: String) -> String? { + get { + #if swift(>=5.0) + return try? get(key) + #else + return (try? get(key)).flatMap { $0 } + #endif + } + + set { + if let value = newValue { + do { + try set(value, key: key) + } catch {} + } else { + do { + try remove(key) + } catch {} + } + } + } + + public subscript(string key: String) -> String? { + get { + return self[key] + } + + set { + self[key] = newValue + } + } + + public subscript(data key: String) -> Data? { + get { + #if swift(>=5.0) + return try? getData(key) + #else + return (try? getData(key)).flatMap { $0 } + #endif + } + + set { + if let value = newValue { + do { + try set(value, key: key) + } catch {} + } else { + do { + try remove(key) + } catch {} + } + } + } + + public subscript(attributes key: String) -> Attributes? { + get { + #if swift(>=5.0) + return try? get(key) { $0 } + #else + return (try? get(key) { $0 }).flatMap { $0 } + #endif + } + } + + // MARK: + + public func remove(_ key: String, ignoringAttributeSynchronizable: Bool = true) throws { + var query = options.query(ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) + query[AttributeAccount] = key + + let status = SecItemDelete(query as CFDictionary) + if status != errSecSuccess && status != errSecItemNotFound { + throw securityError(status: status) + } + } + + public func removeAll() throws { + var query = options.query() + #if !os(iOS) && !os(watchOS) && !os(tvOS) + query[MatchLimit] = MatchLimitAll + #endif + + let status = SecItemDelete(query as CFDictionary) + if status != errSecSuccess && status != errSecItemNotFound { + throw securityError(status: status) + } + } + + // MARK: + + public func contains(_ key: String, withoutAuthenticationUI: Bool = false) throws -> Bool { + var query = options.query() + query[AttributeAccount] = key + + if withoutAuthenticationUI { + #if os(iOS) || os(watchOS) || os(tvOS) + if #available(iOS 9.0, *) { + if let authenticationUI = options.authenticationUI { + query[UseAuthenticationUI] = authenticationUI.rawValue + } else { + query[UseAuthenticationUI] = UseAuthenticationUIFail + } + } else { + query[UseNoAuthenticationUI] = kCFBooleanTrue + } + #else + if #available(OSX 10.11, *) { + if let authenticationUI = options.authenticationUI { + query[UseAuthenticationUI] = authenticationUI.rawValue + } else { + query[UseAuthenticationUI] = UseAuthenticationUIFail + } + } else if #available(OSX 10.10, *) { + query[UseNoAuthenticationUI] = kCFBooleanTrue + } + #endif + } else { + if #available(iOS 9.0, OSX 10.11, *) { + if let authenticationUI = options.authenticationUI { + query[UseAuthenticationUI] = authenticationUI.rawValue + } + } + } + + let status = SecItemCopyMatching(query as CFDictionary, nil) + switch status { + case errSecSuccess: + return true + case errSecInteractionNotAllowed: + if withoutAuthenticationUI { + return true + } + return false + case errSecItemNotFound: + return false + default: + throw securityError(status: status) + } + } + + // MARK: + + public class func allKeys(_ itemClass: ItemClass) -> [(String, String)] { + var query = [String: Any]() + query[Class] = itemClass.rawValue + query[AttributeSynchronizable] = SynchronizableAny + query[MatchLimit] = MatchLimitAll + query[ReturnAttributes] = kCFBooleanTrue + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + switch status { + case errSecSuccess: + if let items = result as? [[String: Any]] { + return prettify(itemClass: itemClass, items: items).map { + switch itemClass { + case .genericPassword: + return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String) + case .internetPassword: + return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String) + } + } + } + case errSecItemNotFound: + return [] + default: () + } + + securityError(status: status) + return [] + } + + public func allKeys() -> [String] { + let allItems = type(of: self).prettify(itemClass: itemClass, items: items()) + let filter: ([String: Any]) -> String? = { $0["key"] as? String } + + #if swift(>=4.1) + return allItems.compactMap(filter) + #else + return allItems.flatMap(filter) + #endif + } + + public class func allItems(_ itemClass: ItemClass) -> [[String: Any]] { + var query = [String: Any]() + query[Class] = itemClass.rawValue + query[MatchLimit] = MatchLimitAll + query[ReturnAttributes] = kCFBooleanTrue + #if os(iOS) || os(watchOS) || os(tvOS) + query[ReturnData] = kCFBooleanTrue + #endif + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + switch status { + case errSecSuccess: + if let items = result as? [[String: Any]] { + return prettify(itemClass: itemClass, items: items) + } + case errSecItemNotFound: + return [] + default: () + } + + securityError(status: status) + return [] + } + + public func allItems() -> [[String: Any]] { + return type(of: self).prettify(itemClass: itemClass, items: items()) + } + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public func getSharedPassword(_ completion: @escaping (_ account: String?, _ password: String?, _ error: Error?) -> () = { account, password, error -> () in }) { + if let domain = server.host { + type(of: self).requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in + if let credential = credentials.first { + let account = credential["account"] + let password = credential["password"] + completion(account, password, error) + } else { + completion(nil, nil, error) + } + } + } else { + let error = securityError(status: Status.param.rawValue) + completion(nil, nil, error) + } + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public func getSharedPassword(_ account: String, completion: @escaping (_ password: String?, _ error: Error?) -> () = { password, error -> () in }) { + if let domain = server.host { + type(of: self).requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in + if let credential = credentials.first { + if let password = credential["password"] { + completion(password, error) + } else { + completion(nil, error) + } + } else { + completion(nil, error) + } + } + } else { + let error = securityError(status: Status.param.rawValue) + completion(nil, error) + } + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public func setSharedPassword(_ password: String, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) { + setSharedPassword(password as String?, account: account, completion: completion) + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + fileprivate func setSharedPassword(_ password: String?, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) { + if let domain = server.host { + SecAddSharedWebCredential(domain as CFString, account as CFString, password as CFString?) { error -> () in + if let error = error { + completion(error.error) + } else { + completion(nil) + } + } + } else { + let error = securityError(status: Status.param.rawValue) + completion(error) + } + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public func removeSharedPassword(_ account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) { + setSharedPassword(nil, account: account, completion: completion) + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public class func requestSharedWebCredential(_ completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) { + requestSharedWebCredential(domain: nil, account: nil, completion: completion) + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public class func requestSharedWebCredential(domain: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) { + requestSharedWebCredential(domain: domain, account: nil, completion: completion) + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + public class func requestSharedWebCredential(domain: String, account: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) { + requestSharedWebCredential(domain: Optional(domain), account: Optional(account)!, completion: completion) + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + @available(iOS 8.0, *) + fileprivate class func requestSharedWebCredential(domain: String?, account: String?, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> ()) { + SecRequestSharedWebCredential(domain as CFString?, account as CFString?) { (credentials, error) -> () in + var remoteError: NSError? + if let error = error { + remoteError = error.error + if remoteError?.code != Int(errSecItemNotFound) { + print("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)") + } + } + if let credentials = credentials { + let credentials = (credentials as NSArray).map { credentials -> [String: String] in + var credential = [String: String]() + if let credentials = credentials as? [String: String] { + if let server = credentials[AttributeServer] { + credential["server"] = server + } + if let account = credentials[AttributeAccount] { + credential["account"] = account + } + if let password = credentials[SharedPassword] { + credential["password"] = password + } + } + return credential + } + completion(credentials, remoteError) + } else { + completion([], remoteError) + } + } + } + #endif + + #if os(iOS) && !targetEnvironment(macCatalyst) + /** + @abstract Returns a randomly generated password. + @return String password in the form xxx-xxx-xxx-xxx where x is taken from the sets "abcdefghkmnopqrstuvwxy", "ABCDEFGHJKLMNPQRSTUVWXYZ", "3456789" with at least one character from each set being present. + */ + @available(iOS 8.0, *) + public class func generatePassword() -> String { + return SecCreateSharedWebCredentialPassword()! as String + } + #endif + + // MARK: + + fileprivate func items() -> [[String: Any]] { + var query = options.query() + query[MatchLimit] = MatchLimitAll + query[ReturnAttributes] = kCFBooleanTrue + #if os(iOS) || os(watchOS) || os(tvOS) + query[ReturnData] = kCFBooleanTrue + #endif + + var result: AnyObject? + let status = SecItemCopyMatching(query as CFDictionary, &result) + + switch status { + case errSecSuccess: + if let items = result as? [[String: Any]] { + return items + } + case errSecItemNotFound: + return [] + default: () + } + + securityError(status: status) + return [] + } + + fileprivate class func prettify(itemClass: ItemClass, items: [[String: Any]]) -> [[String: Any]] { + let items = items.map { attributes -> [String: Any] in + var item = [String: Any]() + + item["class"] = itemClass.description + + if let accessGroup = attributes[AttributeAccessGroup] as? String { + item["accessGroup"] = accessGroup + } + + switch itemClass { + case .genericPassword: + if let service = attributes[AttributeService] as? String { + item["service"] = service + } + case .internetPassword: + if let server = attributes[AttributeServer] as? String { + item["server"] = server + } + if let proto = attributes[AttributeProtocol] as? String { + if let protocolType = ProtocolType(rawValue: proto) { + item["protocol"] = protocolType.description + } + } + if let auth = attributes[AttributeAuthenticationType] as? String { + if let authenticationType = AuthenticationType(rawValue: auth) { + item["authenticationType"] = authenticationType.description + } + } + } + + if let key = attributes[AttributeAccount] as? String { + item["key"] = key + } + if let data = attributes[ValueData] as? Data { + if let text = String(data: data, encoding: .utf8) { + item["value"] = text + } else { + item["value"] = data + } + } + + if let accessible = attributes[AttributeAccessible] as? String { + if let accessibility = Accessibility(rawValue: accessible) { + item["accessibility"] = accessibility.description + } + } + if let synchronizable = attributes[AttributeSynchronizable] as? Bool { + item["synchronizable"] = synchronizable ? "true" : "false" + } + + return item + } + return items + } + + // MARK: + + @discardableResult + fileprivate class func securityError(status: OSStatus) -> Error { + let error = Status(status: status) + if error != .userCanceled { + print("OSStatus error:[\(error.errorCode)] \(error.description)") + } + + return error + } + + @discardableResult + fileprivate func securityError(status: OSStatus) -> Error { + return type(of: self).securityError(status: status) + } +} + +struct Options { + var itemClass: ItemClass = .genericPassword + + var service: String = "" + var accessGroup: String? = nil + + var server: URL! + var protocolType: ProtocolType! + var authenticationType: AuthenticationType = .default + + var accessibility: Accessibility = .afterFirstUnlock + var authenticationPolicy: AuthenticationPolicy? + + var synchronizable: Bool = false + + var label: String? + var comment: String? + + var authenticationPrompt: String? + var authenticationUI: AuthenticationUI? + var authenticationContext: AnyObject? + + var attributes = [String: Any]() +} + +/** Class Key Constant */ +private let Class = String(kSecClass) + +/** Attribute Key Constants */ +private let AttributeAccessible = String(kSecAttrAccessible) + +@available(iOS 8.0, OSX 10.10, *) +private let AttributeAccessControl = String(kSecAttrAccessControl) + +private let AttributeAccessGroup = String(kSecAttrAccessGroup) +private let AttributeSynchronizable = String(kSecAttrSynchronizable) +private let AttributeCreationDate = String(kSecAttrCreationDate) +private let AttributeModificationDate = String(kSecAttrModificationDate) +private let AttributeDescription = String(kSecAttrDescription) +private let AttributeComment = String(kSecAttrComment) +private let AttributeCreator = String(kSecAttrCreator) +private let AttributeType = String(kSecAttrType) +private let AttributeLabel = String(kSecAttrLabel) +private let AttributeIsInvisible = String(kSecAttrIsInvisible) +private let AttributeIsNegative = String(kSecAttrIsNegative) +private let AttributeAccount = String(kSecAttrAccount) +private let AttributeService = String(kSecAttrService) +private let AttributeGeneric = String(kSecAttrGeneric) +private let AttributeSecurityDomain = String(kSecAttrSecurityDomain) +private let AttributeServer = String(kSecAttrServer) +private let AttributeProtocol = String(kSecAttrProtocol) +private let AttributeAuthenticationType = String(kSecAttrAuthenticationType) +private let AttributePort = String(kSecAttrPort) +private let AttributePath = String(kSecAttrPath) + +private let SynchronizableAny = kSecAttrSynchronizableAny + +/** Search Constants */ +private let MatchLimit = String(kSecMatchLimit) +private let MatchLimitOne = kSecMatchLimitOne +private let MatchLimitAll = kSecMatchLimitAll + +/** Return Type Key Constants */ +private let ReturnData = String(kSecReturnData) +private let ReturnAttributes = String(kSecReturnAttributes) +private let ReturnRef = String(kSecReturnRef) +private let ReturnPersistentRef = String(kSecReturnPersistentRef) + +/** Value Type Key Constants */ +private let ValueData = String(kSecValueData) +private let ValueRef = String(kSecValueRef) +private let ValuePersistentRef = String(kSecValuePersistentRef) + +/** Other Constants */ +@available(iOS 8.0, OSX 10.10, tvOS 8.0, *) +private let UseOperationPrompt = String(kSecUseOperationPrompt) + +@available(iOS, introduced: 8.0, deprecated: 9.0, message: "Use a UseAuthenticationUI instead.") +@available(OSX, introduced: 10.10, deprecated: 10.11, message: "Use UseAuthenticationUI instead.") +@available(watchOS, introduced: 2.0, deprecated: 2.0, message: "Use UseAuthenticationUI instead.") +@available(tvOS, introduced: 8.0, deprecated: 9.0, message: "Use UseAuthenticationUI instead.") +private let UseNoAuthenticationUI = String(kSecUseNoAuthenticationUI) + +@available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *) +private let UseAuthenticationUI = String(kSecUseAuthenticationUI) + +@available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *) +private let UseAuthenticationContext = String(kSecUseAuthenticationContext) + +@available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *) +private let UseAuthenticationUIAllow = String(kSecUseAuthenticationUIAllow) + +@available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *) +private let UseAuthenticationUIFail = String(kSecUseAuthenticationUIFail) + +@available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *) +private let UseAuthenticationUISkip = String(kSecUseAuthenticationUISkip) + +#if os(iOS) && !targetEnvironment(macCatalyst) +/** Credential Key Constants */ +private let SharedPassword = String(kSecSharedPassword) +#endif + +extension Keychain: CustomStringConvertible, CustomDebugStringConvertible { + public var description: String { + let items = allItems() + if items.isEmpty { + return "[]" + } + var description = "[\n" + for item in items { + description += " " + description += "\(item)\n" + } + description += "]" + return description + } + + public var debugDescription: String { + return "\(items())" + } +} + +extension Options { + func query(ignoringAttributeSynchronizable: Bool = true) -> [String: Any] { + var query = [String: Any]() + + query[Class] = itemClass.rawValue + if let accessGroup = self.accessGroup { + query[AttributeAccessGroup] = accessGroup + } + if ignoringAttributeSynchronizable { + query[AttributeSynchronizable] = SynchronizableAny + } else { + query[AttributeSynchronizable] = synchronizable ? kCFBooleanTrue : kCFBooleanFalse + } + + switch itemClass { + case .genericPassword: + query[AttributeService] = service + case .internetPassword: + query[AttributeServer] = server.host + query[AttributePort] = server.port + query[AttributeProtocol] = protocolType.rawValue + query[AttributeAuthenticationType] = authenticationType.rawValue + } + + if #available(OSX 10.10, *) { + if authenticationPrompt != nil { + query[UseOperationPrompt] = authenticationPrompt + } + } + + #if !os(watchOS) + if #available(iOS 9.0, OSX 10.11, *) { + if authenticationContext != nil { + query[UseAuthenticationContext] = authenticationContext + } + } + #endif + + return query + } + + func attributes(key: String?, value: Data) -> ([String: Any], Error?) { + var attributes: [String: Any] + + if key != nil { + attributes = query() + attributes[AttributeAccount] = key + } else { + attributes = [String: Any]() + } + + attributes[ValueData] = value + + if label != nil { + attributes[AttributeLabel] = label + } + if comment != nil { + attributes[AttributeComment] = comment + } + + if let policy = authenticationPolicy { + if #available(OSX 10.10, *) { + var error: Unmanaged? + guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue as CFTypeRef, SecAccessControlCreateFlags(rawValue: CFOptionFlags(policy.rawValue)), &error) else { + if let error = error?.takeUnretainedValue() { + return (attributes, error.error) + } + + return (attributes, Status.unexpectedError) + } + attributes[AttributeAccessControl] = accessControl + } else { + print("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.") + } + } else { + attributes[AttributeAccessible] = accessibility.rawValue + } + + attributes[AttributeSynchronizable] = synchronizable ? kCFBooleanTrue : kCFBooleanFalse + + return (attributes, nil) + } +} + +// MARK: + +extension Attributes: CustomStringConvertible, CustomDebugStringConvertible { + public var description: String { + return "\(attributes)" + } + + public var debugDescription: String { + return description + } +} + +extension ItemClass: RawRepresentable, CustomStringConvertible { + public init?(rawValue: String) { + switch rawValue { + case String(kSecClassGenericPassword): + self = .genericPassword + case String(kSecClassInternetPassword): + self = .internetPassword + default: + return nil + } + } + + public var rawValue: String { + switch self { + case .genericPassword: + return String(kSecClassGenericPassword) + case .internetPassword: + return String(kSecClassInternetPassword) + } + } + + public var description: String { + switch self { + case .genericPassword: + return "GenericPassword" + case .internetPassword: + return "InternetPassword" + } + } +} + +extension ProtocolType: RawRepresentable, CustomStringConvertible { + public init?(rawValue: String) { + switch rawValue { + case String(kSecAttrProtocolFTP): + self = .ftp + case String(kSecAttrProtocolFTPAccount): + self = .ftpAccount + case String(kSecAttrProtocolHTTP): + self = .http + case String(kSecAttrProtocolIRC): + self = .irc + case String(kSecAttrProtocolNNTP): + self = .nntp + case String(kSecAttrProtocolPOP3): + self = .pop3 + case String(kSecAttrProtocolSMTP): + self = .smtp + case String(kSecAttrProtocolSOCKS): + self = .socks + case String(kSecAttrProtocolIMAP): + self = .imap + case String(kSecAttrProtocolLDAP): + self = .ldap + case String(kSecAttrProtocolAppleTalk): + self = .appleTalk + case String(kSecAttrProtocolAFP): + self = .afp + case String(kSecAttrProtocolTelnet): + self = .telnet + case String(kSecAttrProtocolSSH): + self = .ssh + case String(kSecAttrProtocolFTPS): + self = .ftps + case String(kSecAttrProtocolHTTPS): + self = .https + case String(kSecAttrProtocolHTTPProxy): + self = .httpProxy + case String(kSecAttrProtocolHTTPSProxy): + self = .httpsProxy + case String(kSecAttrProtocolFTPProxy): + self = .ftpProxy + case String(kSecAttrProtocolSMB): + self = .smb + case String(kSecAttrProtocolRTSP): + self = .rtsp + case String(kSecAttrProtocolRTSPProxy): + self = .rtspProxy + case String(kSecAttrProtocolDAAP): + self = .daap + case String(kSecAttrProtocolEPPC): + self = .eppc + case String(kSecAttrProtocolIPP): + self = .ipp + case String(kSecAttrProtocolNNTPS): + self = .nntps + case String(kSecAttrProtocolLDAPS): + self = .ldaps + case String(kSecAttrProtocolTelnetS): + self = .telnetS + case String(kSecAttrProtocolIMAPS): + self = .imaps + case String(kSecAttrProtocolIRCS): + self = .ircs + case String(kSecAttrProtocolPOP3S): + self = .pop3S + default: + return nil + } + } + + public var rawValue: String { + switch self { + case .ftp: + return String(kSecAttrProtocolFTP) + case .ftpAccount: + return String(kSecAttrProtocolFTPAccount) + case .http: + return String(kSecAttrProtocolHTTP) + case .irc: + return String(kSecAttrProtocolIRC) + case .nntp: + return String(kSecAttrProtocolNNTP) + case .pop3: + return String(kSecAttrProtocolPOP3) + case .smtp: + return String(kSecAttrProtocolSMTP) + case .socks: + return String(kSecAttrProtocolSOCKS) + case .imap: + return String(kSecAttrProtocolIMAP) + case .ldap: + return String(kSecAttrProtocolLDAP) + case .appleTalk: + return String(kSecAttrProtocolAppleTalk) + case .afp: + return String(kSecAttrProtocolAFP) + case .telnet: + return String(kSecAttrProtocolTelnet) + case .ssh: + return String(kSecAttrProtocolSSH) + case .ftps: + return String(kSecAttrProtocolFTPS) + case .https: + return String(kSecAttrProtocolHTTPS) + case .httpProxy: + return String(kSecAttrProtocolHTTPProxy) + case .httpsProxy: + return String(kSecAttrProtocolHTTPSProxy) + case .ftpProxy: + return String(kSecAttrProtocolFTPProxy) + case .smb: + return String(kSecAttrProtocolSMB) + case .rtsp: + return String(kSecAttrProtocolRTSP) + case .rtspProxy: + return String(kSecAttrProtocolRTSPProxy) + case .daap: + return String(kSecAttrProtocolDAAP) + case .eppc: + return String(kSecAttrProtocolEPPC) + case .ipp: + return String(kSecAttrProtocolIPP) + case .nntps: + return String(kSecAttrProtocolNNTPS) + case .ldaps: + return String(kSecAttrProtocolLDAPS) + case .telnetS: + return String(kSecAttrProtocolTelnetS) + case .imaps: + return String(kSecAttrProtocolIMAPS) + case .ircs: + return String(kSecAttrProtocolIRCS) + case .pop3S: + return String(kSecAttrProtocolPOP3S) + } + } + + public var description: String { + switch self { + case .ftp: + return "FTP" + case .ftpAccount: + return "FTPAccount" + case .http: + return "HTTP" + case .irc: + return "IRC" + case .nntp: + return "NNTP" + case .pop3: + return "POP3" + case .smtp: + return "SMTP" + case .socks: + return "SOCKS" + case .imap: + return "IMAP" + case .ldap: + return "LDAP" + case .appleTalk: + return "AppleTalk" + case .afp: + return "AFP" + case .telnet: + return "Telnet" + case .ssh: + return "SSH" + case .ftps: + return "FTPS" + case .https: + return "HTTPS" + case .httpProxy: + return "HTTPProxy" + case .httpsProxy: + return "HTTPSProxy" + case .ftpProxy: + return "FTPProxy" + case .smb: + return "SMB" + case .rtsp: + return "RTSP" + case .rtspProxy: + return "RTSPProxy" + case .daap: + return "DAAP" + case .eppc: + return "EPPC" + case .ipp: + return "IPP" + case .nntps: + return "NNTPS" + case .ldaps: + return "LDAPS" + case .telnetS: + return "TelnetS" + case .imaps: + return "IMAPS" + case .ircs: + return "IRCS" + case .pop3S: + return "POP3S" + } + } +} + +extension AuthenticationType: RawRepresentable, CustomStringConvertible { + public init?(rawValue: String) { + switch rawValue { + case String(kSecAttrAuthenticationTypeNTLM): + self = .ntlm + case String(kSecAttrAuthenticationTypeMSN): + self = .msn + case String(kSecAttrAuthenticationTypeDPA): + self = .dpa + case String(kSecAttrAuthenticationTypeRPA): + self = .rpa + case String(kSecAttrAuthenticationTypeHTTPBasic): + self = .httpBasic + case String(kSecAttrAuthenticationTypeHTTPDigest): + self = .httpDigest + case String(kSecAttrAuthenticationTypeHTMLForm): + self = .htmlForm + case String(kSecAttrAuthenticationTypeDefault): + self = .`default` + default: + return nil + } + } + + public var rawValue: String { + switch self { + case .ntlm: + return String(kSecAttrAuthenticationTypeNTLM) + case .msn: + return String(kSecAttrAuthenticationTypeMSN) + case .dpa: + return String(kSecAttrAuthenticationTypeDPA) + case .rpa: + return String(kSecAttrAuthenticationTypeRPA) + case .httpBasic: + return String(kSecAttrAuthenticationTypeHTTPBasic) + case .httpDigest: + return String(kSecAttrAuthenticationTypeHTTPDigest) + case .htmlForm: + return String(kSecAttrAuthenticationTypeHTMLForm) + case .`default`: + return String(kSecAttrAuthenticationTypeDefault) + } + } + + public var description: String { + switch self { + case .ntlm: + return "NTLM" + case .msn: + return "MSN" + case .dpa: + return "DPA" + case .rpa: + return "RPA" + case .httpBasic: + return "HTTPBasic" + case .httpDigest: + return "HTTPDigest" + case .htmlForm: + return "HTMLForm" + case .`default`: + return "Default" + } + } +} + +extension Accessibility: RawRepresentable, CustomStringConvertible { + public init?(rawValue: String) { + if #available(OSX 10.10, *) { + switch rawValue { + case String(kSecAttrAccessibleWhenUnlocked): + self = .whenUnlocked + case String(kSecAttrAccessibleAfterFirstUnlock): + self = .afterFirstUnlock + #if !targetEnvironment(macCatalyst) + case String(kSecAttrAccessibleAlways): + self = .always + #endif + case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly): + self = .whenPasscodeSetThisDeviceOnly + case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): + self = .whenUnlockedThisDeviceOnly + case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): + self = .afterFirstUnlockThisDeviceOnly + #if !targetEnvironment(macCatalyst) + case String(kSecAttrAccessibleAlwaysThisDeviceOnly): + self = .alwaysThisDeviceOnly + #endif + default: + return nil + } + } else { + switch rawValue { + case String(kSecAttrAccessibleWhenUnlocked): + self = .whenUnlocked + case String(kSecAttrAccessibleAfterFirstUnlock): + self = .afterFirstUnlock + #if !targetEnvironment(macCatalyst) + case String(kSecAttrAccessibleAlways): + self = .always + #endif + case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): + self = .whenUnlockedThisDeviceOnly + case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): + self = .afterFirstUnlockThisDeviceOnly + #if !targetEnvironment(macCatalyst) + case String(kSecAttrAccessibleAlwaysThisDeviceOnly): + self = .alwaysThisDeviceOnly + #endif + default: + return nil + } + } + } + + public var rawValue: String { + switch self { + case .whenUnlocked: + return String(kSecAttrAccessibleWhenUnlocked) + case .afterFirstUnlock: + return String(kSecAttrAccessibleAfterFirstUnlock) + #if !targetEnvironment(macCatalyst) + case .always: + return String(kSecAttrAccessibleAlways) + #endif + case .whenPasscodeSetThisDeviceOnly: + if #available(OSX 10.10, *) { + return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly) + } else { + fatalError("'Accessibility.WhenPasscodeSetThisDeviceOnly' is not available on this version of OS.") + } + case .whenUnlockedThisDeviceOnly: + return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly) + case .afterFirstUnlockThisDeviceOnly: + return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) + #if !targetEnvironment(macCatalyst) + case .alwaysThisDeviceOnly: + return String(kSecAttrAccessibleAlwaysThisDeviceOnly) + #endif + } + } + + public var description: String { + switch self { + case .whenUnlocked: + return "WhenUnlocked" + case .afterFirstUnlock: + return "AfterFirstUnlock" + #if !targetEnvironment(macCatalyst) + case .always: + return "Always" + #endif + case .whenPasscodeSetThisDeviceOnly: + return "WhenPasscodeSetThisDeviceOnly" + case .whenUnlockedThisDeviceOnly: + return "WhenUnlockedThisDeviceOnly" + case .afterFirstUnlockThisDeviceOnly: + return "AfterFirstUnlockThisDeviceOnly" + #if !targetEnvironment(macCatalyst) + case .alwaysThisDeviceOnly: + return "AlwaysThisDeviceOnly" + #endif + } + } +} + +extension CFError { + var error: NSError { + let domain = CFErrorGetDomain(self) as String + let code = CFErrorGetCode(self) + let userInfo = CFErrorCopyUserInfo(self) as! [String: Any] + + return NSError(domain: domain, code: code, userInfo: userInfo) + } +} + +public enum Status: OSStatus, Error { + case success = 0 + case unimplemented = -4 + case diskFull = -34 + case io = -36 + case opWr = -49 + case param = -50 + case wrPerm = -61 + case allocate = -108 + case userCanceled = -128 + case badReq = -909 + case internalComponent = -2070 + case notAvailable = -25291 + case readOnly = -25292 + case authFailed = -25293 + case noSuchKeychain = -25294 + case invalidKeychain = -25295 + case duplicateKeychain = -25296 + case duplicateCallback = -25297 + case invalidCallback = -25298 + case duplicateItem = -25299 + case itemNotFound = -25300 + case bufferTooSmall = -25301 + case dataTooLarge = -25302 + case noSuchAttr = -25303 + case invalidItemRef = -25304 + case invalidSearchRef = -25305 + case noSuchClass = -25306 + case noDefaultKeychain = -25307 + case interactionNotAllowed = -25308 + case readOnlyAttr = -25309 + case wrongSecVersion = -25310 + case keySizeNotAllowed = -25311 + case noStorageModule = -25312 + case noCertificateModule = -25313 + case noPolicyModule = -25314 + case interactionRequired = -25315 + case dataNotAvailable = -25316 + case dataNotModifiable = -25317 + case createChainFailed = -25318 + case invalidPrefsDomain = -25319 + case inDarkWake = -25320 + case aclNotSimple = -25240 + case policyNotFound = -25241 + case invalidTrustSetting = -25242 + case noAccessForItem = -25243 + case invalidOwnerEdit = -25244 + case trustNotAvailable = -25245 + case unsupportedFormat = -25256 + case unknownFormat = -25257 + case keyIsSensitive = -25258 + case multiplePrivKeys = -25259 + case passphraseRequired = -25260 + case invalidPasswordRef = -25261 + case invalidTrustSettings = -25262 + case noTrustSettings = -25263 + case pkcs12VerifyFailure = -25264 + case invalidCertificate = -26265 + case notSigner = -26267 + case policyDenied = -26270 + case invalidKey = -26274 + case decode = -26275 + case `internal` = -26276 + case unsupportedAlgorithm = -26268 + case unsupportedOperation = -26271 + case unsupportedPadding = -26273 + case itemInvalidKey = -34000 + case itemInvalidKeyType = -34001 + case itemInvalidValue = -34002 + case itemClassMissing = -34003 + case itemMatchUnsupported = -34004 + case useItemListUnsupported = -34005 + case useKeychainUnsupported = -34006 + case useKeychainListUnsupported = -34007 + case returnDataUnsupported = -34008 + case returnAttributesUnsupported = -34009 + case returnRefUnsupported = -34010 + case returnPersitentRefUnsupported = -34011 + case valueRefUnsupported = -34012 + case valuePersistentRefUnsupported = -34013 + case returnMissingPointer = -34014 + case matchLimitUnsupported = -34015 + case itemIllegalQuery = -34016 + case waitForCallback = -34017 + case missingEntitlement = -34018 + case upgradePending = -34019 + case mpSignatureInvalid = -25327 + case otrTooOld = -25328 + case otrIDTooNew = -25329 + case serviceNotAvailable = -67585 + case insufficientClientID = -67586 + case deviceReset = -67587 + case deviceFailed = -67588 + case appleAddAppACLSubject = -67589 + case applePublicKeyIncomplete = -67590 + case appleSignatureMismatch = -67591 + case appleInvalidKeyStartDate = -67592 + case appleInvalidKeyEndDate = -67593 + case conversionError = -67594 + case appleSSLv2Rollback = -67595 + case quotaExceeded = -67596 + case fileTooBig = -67597 + case invalidDatabaseBlob = -67598 + case invalidKeyBlob = -67599 + case incompatibleDatabaseBlob = -67600 + case incompatibleKeyBlob = -67601 + case hostNameMismatch = -67602 + case unknownCriticalExtensionFlag = -67603 + case noBasicConstraints = -67604 + case noBasicConstraintsCA = -67605 + case invalidAuthorityKeyID = -67606 + case invalidSubjectKeyID = -67607 + case invalidKeyUsageForPolicy = -67608 + case invalidExtendedKeyUsage = -67609 + case invalidIDLinkage = -67610 + case pathLengthConstraintExceeded = -67611 + case invalidRoot = -67612 + case crlExpired = -67613 + case crlNotValidYet = -67614 + case crlNotFound = -67615 + case crlServerDown = -67616 + case crlBadURI = -67617 + case unknownCertExtension = -67618 + case unknownCRLExtension = -67619 + case crlNotTrusted = -67620 + case crlPolicyFailed = -67621 + case idpFailure = -67622 + case smimeEmailAddressesNotFound = -67623 + case smimeBadExtendedKeyUsage = -67624 + case smimeBadKeyUsage = -67625 + case smimeKeyUsageNotCritical = -67626 + case smimeNoEmailAddress = -67627 + case smimeSubjAltNameNotCritical = -67628 + case sslBadExtendedKeyUsage = -67629 + case ocspBadResponse = -67630 + case ocspBadRequest = -67631 + case ocspUnavailable = -67632 + case ocspStatusUnrecognized = -67633 + case endOfData = -67634 + case incompleteCertRevocationCheck = -67635 + case networkFailure = -67636 + case ocspNotTrustedToAnchor = -67637 + case recordModified = -67638 + case ocspSignatureError = -67639 + case ocspNoSigner = -67640 + case ocspResponderMalformedReq = -67641 + case ocspResponderInternalError = -67642 + case ocspResponderTryLater = -67643 + case ocspResponderSignatureRequired = -67644 + case ocspResponderUnauthorized = -67645 + case ocspResponseNonceMismatch = -67646 + case codeSigningBadCertChainLength = -67647 + case codeSigningNoBasicConstraints = -67648 + case codeSigningBadPathLengthConstraint = -67649 + case codeSigningNoExtendedKeyUsage = -67650 + case codeSigningDevelopment = -67651 + case resourceSignBadCertChainLength = -67652 + case resourceSignBadExtKeyUsage = -67653 + case trustSettingDeny = -67654 + case invalidSubjectName = -67655 + case unknownQualifiedCertStatement = -67656 + case mobileMeRequestQueued = -67657 + case mobileMeRequestRedirected = -67658 + case mobileMeServerError = -67659 + case mobileMeServerNotAvailable = -67660 + case mobileMeServerAlreadyExists = -67661 + case mobileMeServerServiceErr = -67662 + case mobileMeRequestAlreadyPending = -67663 + case mobileMeNoRequestPending = -67664 + case mobileMeCSRVerifyFailure = -67665 + case mobileMeFailedConsistencyCheck = -67666 + case notInitialized = -67667 + case invalidHandleUsage = -67668 + case pvcReferentNotFound = -67669 + case functionIntegrityFail = -67670 + case internalError = -67671 + case memoryError = -67672 + case invalidData = -67673 + case mdsError = -67674 + case invalidPointer = -67675 + case selfCheckFailed = -67676 + case functionFailed = -67677 + case moduleManifestVerifyFailed = -67678 + case invalidGUID = -67679 + case invalidHandle = -67680 + case invalidDBList = -67681 + case invalidPassthroughID = -67682 + case invalidNetworkAddress = -67683 + case crlAlreadySigned = -67684 + case invalidNumberOfFields = -67685 + case verificationFailure = -67686 + case unknownTag = -67687 + case invalidSignature = -67688 + case invalidName = -67689 + case invalidCertificateRef = -67690 + case invalidCertificateGroup = -67691 + case tagNotFound = -67692 + case invalidQuery = -67693 + case invalidValue = -67694 + case callbackFailed = -67695 + case aclDeleteFailed = -67696 + case aclReplaceFailed = -67697 + case aclAddFailed = -67698 + case aclChangeFailed = -67699 + case invalidAccessCredentials = -67700 + case invalidRecord = -67701 + case invalidACL = -67702 + case invalidSampleValue = -67703 + case incompatibleVersion = -67704 + case privilegeNotGranted = -67705 + case invalidScope = -67706 + case pvcAlreadyConfigured = -67707 + case invalidPVC = -67708 + case emmLoadFailed = -67709 + case emmUnloadFailed = -67710 + case addinLoadFailed = -67711 + case invalidKeyRef = -67712 + case invalidKeyHierarchy = -67713 + case addinUnloadFailed = -67714 + case libraryReferenceNotFound = -67715 + case invalidAddinFunctionTable = -67716 + case invalidServiceMask = -67717 + case moduleNotLoaded = -67718 + case invalidSubServiceID = -67719 + case attributeNotInContext = -67720 + case moduleManagerInitializeFailed = -67721 + case moduleManagerNotFound = -67722 + case eventNotificationCallbackNotFound = -67723 + case inputLengthError = -67724 + case outputLengthError = -67725 + case privilegeNotSupported = -67726 + case deviceError = -67727 + case attachHandleBusy = -67728 + case notLoggedIn = -67729 + case algorithmMismatch = -67730 + case keyUsageIncorrect = -67731 + case keyBlobTypeIncorrect = -67732 + case keyHeaderInconsistent = -67733 + case unsupportedKeyFormat = -67734 + case unsupportedKeySize = -67735 + case invalidKeyUsageMask = -67736 + case unsupportedKeyUsageMask = -67737 + case invalidKeyAttributeMask = -67738 + case unsupportedKeyAttributeMask = -67739 + case invalidKeyLabel = -67740 + case unsupportedKeyLabel = -67741 + case invalidKeyFormat = -67742 + case unsupportedVectorOfBuffers = -67743 + case invalidInputVector = -67744 + case invalidOutputVector = -67745 + case invalidContext = -67746 + case invalidAlgorithm = -67747 + case invalidAttributeKey = -67748 + case missingAttributeKey = -67749 + case invalidAttributeInitVector = -67750 + case missingAttributeInitVector = -67751 + case invalidAttributeSalt = -67752 + case missingAttributeSalt = -67753 + case invalidAttributePadding = -67754 + case missingAttributePadding = -67755 + case invalidAttributeRandom = -67756 + case missingAttributeRandom = -67757 + case invalidAttributeSeed = -67758 + case missingAttributeSeed = -67759 + case invalidAttributePassphrase = -67760 + case missingAttributePassphrase = -67761 + case invalidAttributeKeyLength = -67762 + case missingAttributeKeyLength = -67763 + case invalidAttributeBlockSize = -67764 + case missingAttributeBlockSize = -67765 + case invalidAttributeOutputSize = -67766 + case missingAttributeOutputSize = -67767 + case invalidAttributeRounds = -67768 + case missingAttributeRounds = -67769 + case invalidAlgorithmParms = -67770 + case missingAlgorithmParms = -67771 + case invalidAttributeLabel = -67772 + case missingAttributeLabel = -67773 + case invalidAttributeKeyType = -67774 + case missingAttributeKeyType = -67775 + case invalidAttributeMode = -67776 + case missingAttributeMode = -67777 + case invalidAttributeEffectiveBits = -67778 + case missingAttributeEffectiveBits = -67779 + case invalidAttributeStartDate = -67780 + case missingAttributeStartDate = -67781 + case invalidAttributeEndDate = -67782 + case missingAttributeEndDate = -67783 + case invalidAttributeVersion = -67784 + case missingAttributeVersion = -67785 + case invalidAttributePrime = -67786 + case missingAttributePrime = -67787 + case invalidAttributeBase = -67788 + case missingAttributeBase = -67789 + case invalidAttributeSubprime = -67790 + case missingAttributeSubprime = -67791 + case invalidAttributeIterationCount = -67792 + case missingAttributeIterationCount = -67793 + case invalidAttributeDLDBHandle = -67794 + case missingAttributeDLDBHandle = -67795 + case invalidAttributeAccessCredentials = -67796 + case missingAttributeAccessCredentials = -67797 + case invalidAttributePublicKeyFormat = -67798 + case missingAttributePublicKeyFormat = -67799 + case invalidAttributePrivateKeyFormat = -67800 + case missingAttributePrivateKeyFormat = -67801 + case invalidAttributeSymmetricKeyFormat = -67802 + case missingAttributeSymmetricKeyFormat = -67803 + case invalidAttributeWrappedKeyFormat = -67804 + case missingAttributeWrappedKeyFormat = -67805 + case stagedOperationInProgress = -67806 + case stagedOperationNotStarted = -67807 + case verifyFailed = -67808 + case querySizeUnknown = -67809 + case blockSizeMismatch = -67810 + case publicKeyInconsistent = -67811 + case deviceVerifyFailed = -67812 + case invalidLoginName = -67813 + case alreadyLoggedIn = -67814 + case invalidDigestAlgorithm = -67815 + case invalidCRLGroup = -67816 + case certificateCannotOperate = -67817 + case certificateExpired = -67818 + case certificateNotValidYet = -67819 + case certificateRevoked = -67820 + case certificateSuspended = -67821 + case insufficientCredentials = -67822 + case invalidAction = -67823 + case invalidAuthority = -67824 + case verifyActionFailed = -67825 + case invalidCertAuthority = -67826 + case invaldCRLAuthority = -67827 + case invalidCRLEncoding = -67828 + case invalidCRLType = -67829 + case invalidCRL = -67830 + case invalidFormType = -67831 + case invalidID = -67832 + case invalidIdentifier = -67833 + case invalidIndex = -67834 + case invalidPolicyIdentifiers = -67835 + case invalidTimeString = -67836 + case invalidReason = -67837 + case invalidRequestInputs = -67838 + case invalidResponseVector = -67839 + case invalidStopOnPolicy = -67840 + case invalidTuple = -67841 + case multipleValuesUnsupported = -67842 + case notTrusted = -67843 + case noDefaultAuthority = -67844 + case rejectedForm = -67845 + case requestLost = -67846 + case requestRejected = -67847 + case unsupportedAddressType = -67848 + case unsupportedService = -67849 + case invalidTupleGroup = -67850 + case invalidBaseACLs = -67851 + case invalidTupleCredendtials = -67852 + case invalidEncoding = -67853 + case invalidValidityPeriod = -67854 + case invalidRequestor = -67855 + case requestDescriptor = -67856 + case invalidBundleInfo = -67857 + case invalidCRLIndex = -67858 + case noFieldValues = -67859 + case unsupportedFieldFormat = -67860 + case unsupportedIndexInfo = -67861 + case unsupportedLocality = -67862 + case unsupportedNumAttributes = -67863 + case unsupportedNumIndexes = -67864 + case unsupportedNumRecordTypes = -67865 + case fieldSpecifiedMultiple = -67866 + case incompatibleFieldFormat = -67867 + case invalidParsingModule = -67868 + case databaseLocked = -67869 + case datastoreIsOpen = -67870 + case missingValue = -67871 + case unsupportedQueryLimits = -67872 + case unsupportedNumSelectionPreds = -67873 + case unsupportedOperator = -67874 + case invalidDBLocation = -67875 + case invalidAccessRequest = -67876 + case invalidIndexInfo = -67877 + case invalidNewOwner = -67878 + case invalidModifyMode = -67879 + case missingRequiredExtension = -67880 + case extendedKeyUsageNotCritical = -67881 + case timestampMissing = -67882 + case timestampInvalid = -67883 + case timestampNotTrusted = -67884 + case timestampServiceNotAvailable = -67885 + case timestampBadAlg = -67886 + case timestampBadRequest = -67887 + case timestampBadDataFormat = -67888 + case timestampTimeNotAvailable = -67889 + case timestampUnacceptedPolicy = -67890 + case timestampUnacceptedExtension = -67891 + case timestampAddInfoNotAvailable = -67892 + case timestampSystemFailure = -67893 + case signingTimeMissing = -67894 + case timestampRejection = -67895 + case timestampWaiting = -67896 + case timestampRevocationWarning = -67897 + case timestampRevocationNotification = -67898 + case unexpectedError = -99999 +} + +extension Status: RawRepresentable, CustomStringConvertible { + + public init(status: OSStatus) { + if let mappedStatus = Status(rawValue: status) { + self = mappedStatus + } else { + self = .unexpectedError + } + } + + public var description: String { + switch self { + case .success: + return "No error." + case .unimplemented: + return "Function or operation not implemented." + case .diskFull: + return "The disk is full." + case .io: + return "I/O error (bummers)" + case .opWr: + return "file already open with with write permission" + case .param: + return "One or more parameters passed to a function were not valid." + case .wrPerm: + return "write permissions error" + case .allocate: + return "Failed to allocate memory." + case .userCanceled: + return "User canceled the operation." + case .badReq: + return "Bad parameter or invalid state for operation." + case .internalComponent: + return "" + case .notAvailable: + return "No keychain is available. You may need to restart your computer." + case .readOnly: + return "This keychain cannot be modified." + case .authFailed: + return "The user name or passphrase you entered is not correct." + case .noSuchKeychain: + return "The specified keychain could not be found." + case .invalidKeychain: + return "The specified keychain is not a valid keychain file." + case .duplicateKeychain: + return "A keychain with the same name already exists." + case .duplicateCallback: + return "The specified callback function is already installed." + case .invalidCallback: + return "The specified callback function is not valid." + case .duplicateItem: + return "The specified item already exists in the keychain." + case .itemNotFound: + return "The specified item could not be found in the keychain." + case .bufferTooSmall: + return "There is not enough memory available to use the specified item." + case .dataTooLarge: + return "This item contains information which is too large or in a format that cannot be displayed." + case .noSuchAttr: + return "The specified attribute does not exist." + case .invalidItemRef: + return "The specified item is no longer valid. It may have been deleted from the keychain." + case .invalidSearchRef: + return "Unable to search the current keychain." + case .noSuchClass: + return "The specified item does not appear to be a valid keychain item." + case .noDefaultKeychain: + return "A default keychain could not be found." + case .interactionNotAllowed: + return "User interaction is not allowed." + case .readOnlyAttr: + return "The specified attribute could not be modified." + case .wrongSecVersion: + return "This keychain was created by a different version of the system software and cannot be opened." + case .keySizeNotAllowed: + return "This item specifies a key size which is too large." + case .noStorageModule: + return "A required component (data storage module) could not be loaded. You may need to restart your computer." + case .noCertificateModule: + return "A required component (certificate module) could not be loaded. You may need to restart your computer." + case .noPolicyModule: + return "A required component (policy module) could not be loaded. You may need to restart your computer." + case .interactionRequired: + return "User interaction is required, but is currently not allowed." + case .dataNotAvailable: + return "The contents of this item cannot be retrieved." + case .dataNotModifiable: + return "The contents of this item cannot be modified." + case .createChainFailed: + return "One or more certificates required to validate this certificate cannot be found." + case .invalidPrefsDomain: + return "The specified preferences domain is not valid." + case .inDarkWake: + return "In dark wake, no UI possible" + case .aclNotSimple: + return "The specified access control list is not in standard (simple) form." + case .policyNotFound: + return "The specified policy cannot be found." + case .invalidTrustSetting: + return "The specified trust setting is invalid." + case .noAccessForItem: + return "The specified item has no access control." + case .invalidOwnerEdit: + return "Invalid attempt to change the owner of this item." + case .trustNotAvailable: + return "No trust results are available." + case .unsupportedFormat: + return "Import/Export format unsupported." + case .unknownFormat: + return "Unknown format in import." + case .keyIsSensitive: + return "Key material must be wrapped for export." + case .multiplePrivKeys: + return "An attempt was made to import multiple private keys." + case .passphraseRequired: + return "Passphrase is required for import/export." + case .invalidPasswordRef: + return "The password reference was invalid." + case .invalidTrustSettings: + return "The Trust Settings Record was corrupted." + case .noTrustSettings: + return "No Trust Settings were found." + case .pkcs12VerifyFailure: + return "MAC verification failed during PKCS12 import (wrong password?)" + case .invalidCertificate: + return "This certificate could not be decoded." + case .notSigner: + return "A certificate was not signed by its proposed parent." + case .policyDenied: + return "The certificate chain was not trusted due to a policy not accepting it." + case .invalidKey: + return "The provided key material was not valid." + case .decode: + return "Unable to decode the provided data." + case .`internal`: + return "An internal error occurred in the Security framework." + case .unsupportedAlgorithm: + return "An unsupported algorithm was encountered." + case .unsupportedOperation: + return "The operation you requested is not supported by this key." + case .unsupportedPadding: + return "The padding you requested is not supported." + case .itemInvalidKey: + return "A string key in dictionary is not one of the supported keys." + case .itemInvalidKeyType: + return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." + case .itemInvalidValue: + return "A value in a dictionary is an invalid (or unsupported) CF type." + case .itemClassMissing: + return "No kSecItemClass key was specified in a dictionary." + case .itemMatchUnsupported: + return "The caller passed one or more kSecMatch keys to a function which does not support matches." + case .useItemListUnsupported: + return "The caller passed in a kSecUseItemList key to a function which does not support it." + case .useKeychainUnsupported: + return "The caller passed in a kSecUseKeychain key to a function which does not support it." + case .useKeychainListUnsupported: + return "The caller passed in a kSecUseKeychainList key to a function which does not support it." + case .returnDataUnsupported: + return "The caller passed in a kSecReturnData key to a function which does not support it." + case .returnAttributesUnsupported: + return "The caller passed in a kSecReturnAttributes key to a function which does not support it." + case .returnRefUnsupported: + return "The caller passed in a kSecReturnRef key to a function which does not support it." + case .returnPersitentRefUnsupported: + return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." + case .valueRefUnsupported: + return "The caller passed in a kSecValueRef key to a function which does not support it." + case .valuePersistentRefUnsupported: + return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." + case .returnMissingPointer: + return "The caller passed asked for something to be returned but did not pass in a result pointer." + case .matchLimitUnsupported: + return "The caller passed in a kSecMatchLimit key to a call which does not support limits." + case .itemIllegalQuery: + return "The caller passed in a query which contained too many keys." + case .waitForCallback: + return "This operation is incomplete, until the callback is invoked (not an error)." + case .missingEntitlement: + return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." + case .upgradePending: + return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." + case .mpSignatureInvalid: + return "Signature invalid on MP message" + case .otrTooOld: + return "Message is too old to use" + case .otrIDTooNew: + return "Key ID is too new to use! Message from the future?" + case .serviceNotAvailable: + return "The required service is not available." + case .insufficientClientID: + return "The client ID is not correct." + case .deviceReset: + return "A device reset has occurred." + case .deviceFailed: + return "A device failure has occurred." + case .appleAddAppACLSubject: + return "Adding an application ACL subject failed." + case .applePublicKeyIncomplete: + return "The public key is incomplete." + case .appleSignatureMismatch: + return "A signature mismatch has occurred." + case .appleInvalidKeyStartDate: + return "The specified key has an invalid start date." + case .appleInvalidKeyEndDate: + return "The specified key has an invalid end date." + case .conversionError: + return "A conversion error has occurred." + case .appleSSLv2Rollback: + return "A SSLv2 rollback error has occurred." + case .quotaExceeded: + return "The quota was exceeded." + case .fileTooBig: + return "The file is too big." + case .invalidDatabaseBlob: + return "The specified database has an invalid blob." + case .invalidKeyBlob: + return "The specified database has an invalid key blob." + case .incompatibleDatabaseBlob: + return "The specified database has an incompatible blob." + case .incompatibleKeyBlob: + return "The specified database has an incompatible key blob." + case .hostNameMismatch: + return "A host name mismatch has occurred." + case .unknownCriticalExtensionFlag: + return "There is an unknown critical extension flag." + case .noBasicConstraints: + return "No basic constraints were found." + case .noBasicConstraintsCA: + return "No basic CA constraints were found." + case .invalidAuthorityKeyID: + return "The authority key ID is not valid." + case .invalidSubjectKeyID: + return "The subject key ID is not valid." + case .invalidKeyUsageForPolicy: + return "The key usage is not valid for the specified policy." + case .invalidExtendedKeyUsage: + return "The extended key usage is not valid." + case .invalidIDLinkage: + return "The ID linkage is not valid." + case .pathLengthConstraintExceeded: + return "The path length constraint was exceeded." + case .invalidRoot: + return "The root or anchor certificate is not valid." + case .crlExpired: + return "The CRL has expired." + case .crlNotValidYet: + return "The CRL is not yet valid." + case .crlNotFound: + return "The CRL was not found." + case .crlServerDown: + return "The CRL server is down." + case .crlBadURI: + return "The CRL has a bad Uniform Resource Identifier." + case .unknownCertExtension: + return "An unknown certificate extension was encountered." + case .unknownCRLExtension: + return "An unknown CRL extension was encountered." + case .crlNotTrusted: + return "The CRL is not trusted." + case .crlPolicyFailed: + return "The CRL policy failed." + case .idpFailure: + return "The issuing distribution point was not valid." + case .smimeEmailAddressesNotFound: + return "An email address mismatch was encountered." + case .smimeBadExtendedKeyUsage: + return "The appropriate extended key usage for SMIME was not found." + case .smimeBadKeyUsage: + return "The key usage is not compatible with SMIME." + case .smimeKeyUsageNotCritical: + return "The key usage extension is not marked as critical." + case .smimeNoEmailAddress: + return "No email address was found in the certificate." + case .smimeSubjAltNameNotCritical: + return "The subject alternative name extension is not marked as critical." + case .sslBadExtendedKeyUsage: + return "The appropriate extended key usage for SSL was not found." + case .ocspBadResponse: + return "The OCSP response was incorrect or could not be parsed." + case .ocspBadRequest: + return "The OCSP request was incorrect or could not be parsed." + case .ocspUnavailable: + return "OCSP service is unavailable." + case .ocspStatusUnrecognized: + return "The OCSP server did not recognize this certificate." + case .endOfData: + return "An end-of-data was detected." + case .incompleteCertRevocationCheck: + return "An incomplete certificate revocation check occurred." + case .networkFailure: + return "A network failure occurred." + case .ocspNotTrustedToAnchor: + return "The OCSP response was not trusted to a root or anchor certificate." + case .recordModified: + return "The record was modified." + case .ocspSignatureError: + return "The OCSP response had an invalid signature." + case .ocspNoSigner: + return "The OCSP response had no signer." + case .ocspResponderMalformedReq: + return "The OCSP responder was given a malformed request." + case .ocspResponderInternalError: + return "The OCSP responder encountered an internal error." + case .ocspResponderTryLater: + return "The OCSP responder is busy, try again later." + case .ocspResponderSignatureRequired: + return "The OCSP responder requires a signature." + case .ocspResponderUnauthorized: + return "The OCSP responder rejected this request as unauthorized." + case .ocspResponseNonceMismatch: + return "The OCSP response nonce did not match the request." + case .codeSigningBadCertChainLength: + return "Code signing encountered an incorrect certificate chain length." + case .codeSigningNoBasicConstraints: + return "Code signing found no basic constraints." + case .codeSigningBadPathLengthConstraint: + return "Code signing encountered an incorrect path length constraint." + case .codeSigningNoExtendedKeyUsage: + return "Code signing found no extended key usage." + case .codeSigningDevelopment: + return "Code signing indicated use of a development-only certificate." + case .resourceSignBadCertChainLength: + return "Resource signing has encountered an incorrect certificate chain length." + case .resourceSignBadExtKeyUsage: + return "Resource signing has encountered an error in the extended key usage." + case .trustSettingDeny: + return "The trust setting for this policy was set to Deny." + case .invalidSubjectName: + return "An invalid certificate subject name was encountered." + case .unknownQualifiedCertStatement: + return "An unknown qualified certificate statement was encountered." + case .mobileMeRequestQueued: + return "The MobileMe request will be sent during the next connection." + case .mobileMeRequestRedirected: + return "The MobileMe request was redirected." + case .mobileMeServerError: + return "A MobileMe server error occurred." + case .mobileMeServerNotAvailable: + return "The MobileMe server is not available." + case .mobileMeServerAlreadyExists: + return "The MobileMe server reported that the item already exists." + case .mobileMeServerServiceErr: + return "A MobileMe service error has occurred." + case .mobileMeRequestAlreadyPending: + return "A MobileMe request is already pending." + case .mobileMeNoRequestPending: + return "MobileMe has no request pending." + case .mobileMeCSRVerifyFailure: + return "A MobileMe CSR verification failure has occurred." + case .mobileMeFailedConsistencyCheck: + return "MobileMe has found a failed consistency check." + case .notInitialized: + return "A function was called without initializing CSSM." + case .invalidHandleUsage: + return "The CSSM handle does not match with the service type." + case .pvcReferentNotFound: + return "A reference to the calling module was not found in the list of authorized callers." + case .functionIntegrityFail: + return "A function address was not within the verified module." + case .internalError: + return "An internal error has occurred." + case .memoryError: + return "A memory error has occurred." + case .invalidData: + return "Invalid data was encountered." + case .mdsError: + return "A Module Directory Service error has occurred." + case .invalidPointer: + return "An invalid pointer was encountered." + case .selfCheckFailed: + return "Self-check has failed." + case .functionFailed: + return "A function has failed." + case .moduleManifestVerifyFailed: + return "A module manifest verification failure has occurred." + case .invalidGUID: + return "An invalid GUID was encountered." + case .invalidHandle: + return "An invalid handle was encountered." + case .invalidDBList: + return "An invalid DB list was encountered." + case .invalidPassthroughID: + return "An invalid passthrough ID was encountered." + case .invalidNetworkAddress: + return "An invalid network address was encountered." + case .crlAlreadySigned: + return "The certificate revocation list is already signed." + case .invalidNumberOfFields: + return "An invalid number of fields were encountered." + case .verificationFailure: + return "A verification failure occurred." + case .unknownTag: + return "An unknown tag was encountered." + case .invalidSignature: + return "An invalid signature was encountered." + case .invalidName: + return "An invalid name was encountered." + case .invalidCertificateRef: + return "An invalid certificate reference was encountered." + case .invalidCertificateGroup: + return "An invalid certificate group was encountered." + case .tagNotFound: + return "The specified tag was not found." + case .invalidQuery: + return "The specified query was not valid." + case .invalidValue: + return "An invalid value was detected." + case .callbackFailed: + return "A callback has failed." + case .aclDeleteFailed: + return "An ACL delete operation has failed." + case .aclReplaceFailed: + return "An ACL replace operation has failed." + case .aclAddFailed: + return "An ACL add operation has failed." + case .aclChangeFailed: + return "An ACL change operation has failed." + case .invalidAccessCredentials: + return "Invalid access credentials were encountered." + case .invalidRecord: + return "An invalid record was encountered." + case .invalidACL: + return "An invalid ACL was encountered." + case .invalidSampleValue: + return "An invalid sample value was encountered." + case .incompatibleVersion: + return "An incompatible version was encountered." + case .privilegeNotGranted: + return "The privilege was not granted." + case .invalidScope: + return "An invalid scope was encountered." + case .pvcAlreadyConfigured: + return "The PVC is already configured." + case .invalidPVC: + return "An invalid PVC was encountered." + case .emmLoadFailed: + return "The EMM load has failed." + case .emmUnloadFailed: + return "The EMM unload has failed." + case .addinLoadFailed: + return "The add-in load operation has failed." + case .invalidKeyRef: + return "An invalid key was encountered." + case .invalidKeyHierarchy: + return "An invalid key hierarchy was encountered." + case .addinUnloadFailed: + return "The add-in unload operation has failed." + case .libraryReferenceNotFound: + return "A library reference was not found." + case .invalidAddinFunctionTable: + return "An invalid add-in function table was encountered." + case .invalidServiceMask: + return "An invalid service mask was encountered." + case .moduleNotLoaded: + return "A module was not loaded." + case .invalidSubServiceID: + return "An invalid subservice ID was encountered." + case .attributeNotInContext: + return "An attribute was not in the context." + case .moduleManagerInitializeFailed: + return "A module failed to initialize." + case .moduleManagerNotFound: + return "A module was not found." + case .eventNotificationCallbackNotFound: + return "An event notification callback was not found." + case .inputLengthError: + return "An input length error was encountered." + case .outputLengthError: + return "An output length error was encountered." + case .privilegeNotSupported: + return "The privilege is not supported." + case .deviceError: + return "A device error was encountered." + case .attachHandleBusy: + return "The CSP handle was busy." + case .notLoggedIn: + return "You are not logged in." + case .algorithmMismatch: + return "An algorithm mismatch was encountered." + case .keyUsageIncorrect: + return "The key usage is incorrect." + case .keyBlobTypeIncorrect: + return "The key blob type is incorrect." + case .keyHeaderInconsistent: + return "The key header is inconsistent." + case .unsupportedKeyFormat: + return "The key header format is not supported." + case .unsupportedKeySize: + return "The key size is not supported." + case .invalidKeyUsageMask: + return "The key usage mask is not valid." + case .unsupportedKeyUsageMask: + return "The key usage mask is not supported." + case .invalidKeyAttributeMask: + return "The key attribute mask is not valid." + case .unsupportedKeyAttributeMask: + return "The key attribute mask is not supported." + case .invalidKeyLabel: + return "The key label is not valid." + case .unsupportedKeyLabel: + return "The key label is not supported." + case .invalidKeyFormat: + return "The key format is not valid." + case .unsupportedVectorOfBuffers: + return "The vector of buffers is not supported." + case .invalidInputVector: + return "The input vector is not valid." + case .invalidOutputVector: + return "The output vector is not valid." + case .invalidContext: + return "An invalid context was encountered." + case .invalidAlgorithm: + return "An invalid algorithm was encountered." + case .invalidAttributeKey: + return "A key attribute was not valid." + case .missingAttributeKey: + return "A key attribute was missing." + case .invalidAttributeInitVector: + return "An init vector attribute was not valid." + case .missingAttributeInitVector: + return "An init vector attribute was missing." + case .invalidAttributeSalt: + return "A salt attribute was not valid." + case .missingAttributeSalt: + return "A salt attribute was missing." + case .invalidAttributePadding: + return "A padding attribute was not valid." + case .missingAttributePadding: + return "A padding attribute was missing." + case .invalidAttributeRandom: + return "A random number attribute was not valid." + case .missingAttributeRandom: + return "A random number attribute was missing." + case .invalidAttributeSeed: + return "A seed attribute was not valid." + case .missingAttributeSeed: + return "A seed attribute was missing." + case .invalidAttributePassphrase: + return "A passphrase attribute was not valid." + case .missingAttributePassphrase: + return "A passphrase attribute was missing." + case .invalidAttributeKeyLength: + return "A key length attribute was not valid." + case .missingAttributeKeyLength: + return "A key length attribute was missing." + case .invalidAttributeBlockSize: + return "A block size attribute was not valid." + case .missingAttributeBlockSize: + return "A block size attribute was missing." + case .invalidAttributeOutputSize: + return "An output size attribute was not valid." + case .missingAttributeOutputSize: + return "An output size attribute was missing." + case .invalidAttributeRounds: + return "The number of rounds attribute was not valid." + case .missingAttributeRounds: + return "The number of rounds attribute was missing." + case .invalidAlgorithmParms: + return "An algorithm parameters attribute was not valid." + case .missingAlgorithmParms: + return "An algorithm parameters attribute was missing." + case .invalidAttributeLabel: + return "A label attribute was not valid." + case .missingAttributeLabel: + return "A label attribute was missing." + case .invalidAttributeKeyType: + return "A key type attribute was not valid." + case .missingAttributeKeyType: + return "A key type attribute was missing." + case .invalidAttributeMode: + return "A mode attribute was not valid." + case .missingAttributeMode: + return "A mode attribute was missing." + case .invalidAttributeEffectiveBits: + return "An effective bits attribute was not valid." + case .missingAttributeEffectiveBits: + return "An effective bits attribute was missing." + case .invalidAttributeStartDate: + return "A start date attribute was not valid." + case .missingAttributeStartDate: + return "A start date attribute was missing." + case .invalidAttributeEndDate: + return "An end date attribute was not valid." + case .missingAttributeEndDate: + return "An end date attribute was missing." + case .invalidAttributeVersion: + return "A version attribute was not valid." + case .missingAttributeVersion: + return "A version attribute was missing." + case .invalidAttributePrime: + return "A prime attribute was not valid." + case .missingAttributePrime: + return "A prime attribute was missing." + case .invalidAttributeBase: + return "A base attribute was not valid." + case .missingAttributeBase: + return "A base attribute was missing." + case .invalidAttributeSubprime: + return "A subprime attribute was not valid." + case .missingAttributeSubprime: + return "A subprime attribute was missing." + case .invalidAttributeIterationCount: + return "An iteration count attribute was not valid." + case .missingAttributeIterationCount: + return "An iteration count attribute was missing." + case .invalidAttributeDLDBHandle: + return "A database handle attribute was not valid." + case .missingAttributeDLDBHandle: + return "A database handle attribute was missing." + case .invalidAttributeAccessCredentials: + return "An access credentials attribute was not valid." + case .missingAttributeAccessCredentials: + return "An access credentials attribute was missing." + case .invalidAttributePublicKeyFormat: + return "A public key format attribute was not valid." + case .missingAttributePublicKeyFormat: + return "A public key format attribute was missing." + case .invalidAttributePrivateKeyFormat: + return "A private key format attribute was not valid." + case .missingAttributePrivateKeyFormat: + return "A private key format attribute was missing." + case .invalidAttributeSymmetricKeyFormat: + return "A symmetric key format attribute was not valid." + case .missingAttributeSymmetricKeyFormat: + return "A symmetric key format attribute was missing." + case .invalidAttributeWrappedKeyFormat: + return "A wrapped key format attribute was not valid." + case .missingAttributeWrappedKeyFormat: + return "A wrapped key format attribute was missing." + case .stagedOperationInProgress: + return "A staged operation is in progress." + case .stagedOperationNotStarted: + return "A staged operation was not started." + case .verifyFailed: + return "A cryptographic verification failure has occurred." + case .querySizeUnknown: + return "The query size is unknown." + case .blockSizeMismatch: + return "A block size mismatch occurred." + case .publicKeyInconsistent: + return "The public key was inconsistent." + case .deviceVerifyFailed: + return "A device verification failure has occurred." + case .invalidLoginName: + return "An invalid login name was detected." + case .alreadyLoggedIn: + return "The user is already logged in." + case .invalidDigestAlgorithm: + return "An invalid digest algorithm was detected." + case .invalidCRLGroup: + return "An invalid CRL group was detected." + case .certificateCannotOperate: + return "The certificate cannot operate." + case .certificateExpired: + return "An expired certificate was detected." + case .certificateNotValidYet: + return "The certificate is not yet valid." + case .certificateRevoked: + return "The certificate was revoked." + case .certificateSuspended: + return "The certificate was suspended." + case .insufficientCredentials: + return "Insufficient credentials were detected." + case .invalidAction: + return "The action was not valid." + case .invalidAuthority: + return "The authority was not valid." + case .verifyActionFailed: + return "A verify action has failed." + case .invalidCertAuthority: + return "The certificate authority was not valid." + case .invaldCRLAuthority: + return "The CRL authority was not valid." + case .invalidCRLEncoding: + return "The CRL encoding was not valid." + case .invalidCRLType: + return "The CRL type was not valid." + case .invalidCRL: + return "The CRL was not valid." + case .invalidFormType: + return "The form type was not valid." + case .invalidID: + return "The ID was not valid." + case .invalidIdentifier: + return "The identifier was not valid." + case .invalidIndex: + return "The index was not valid." + case .invalidPolicyIdentifiers: + return "The policy identifiers are not valid." + case .invalidTimeString: + return "The time specified was not valid." + case .invalidReason: + return "The trust policy reason was not valid." + case .invalidRequestInputs: + return "The request inputs are not valid." + case .invalidResponseVector: + return "The response vector was not valid." + case .invalidStopOnPolicy: + return "The stop-on policy was not valid." + case .invalidTuple: + return "The tuple was not valid." + case .multipleValuesUnsupported: + return "Multiple values are not supported." + case .notTrusted: + return "The trust policy was not trusted." + case .noDefaultAuthority: + return "No default authority was detected." + case .rejectedForm: + return "The trust policy had a rejected form." + case .requestLost: + return "The request was lost." + case .requestRejected: + return "The request was rejected." + case .unsupportedAddressType: + return "The address type is not supported." + case .unsupportedService: + return "The service is not supported." + case .invalidTupleGroup: + return "The tuple group was not valid." + case .invalidBaseACLs: + return "The base ACLs are not valid." + case .invalidTupleCredendtials: + return "The tuple credentials are not valid." + case .invalidEncoding: + return "The encoding was not valid." + case .invalidValidityPeriod: + return "The validity period was not valid." + case .invalidRequestor: + return "The requestor was not valid." + case .requestDescriptor: + return "The request descriptor was not valid." + case .invalidBundleInfo: + return "The bundle information was not valid." + case .invalidCRLIndex: + return "The CRL index was not valid." + case .noFieldValues: + return "No field values were detected." + case .unsupportedFieldFormat: + return "The field format is not supported." + case .unsupportedIndexInfo: + return "The index information is not supported." + case .unsupportedLocality: + return "The locality is not supported." + case .unsupportedNumAttributes: + return "The number of attributes is not supported." + case .unsupportedNumIndexes: + return "The number of indexes is not supported." + case .unsupportedNumRecordTypes: + return "The number of record types is not supported." + case .fieldSpecifiedMultiple: + return "Too many fields were specified." + case .incompatibleFieldFormat: + return "The field format was incompatible." + case .invalidParsingModule: + return "The parsing module was not valid." + case .databaseLocked: + return "The database is locked." + case .datastoreIsOpen: + return "The data store is open." + case .missingValue: + return "A missing value was detected." + case .unsupportedQueryLimits: + return "The query limits are not supported." + case .unsupportedNumSelectionPreds: + return "The number of selection predicates is not supported." + case .unsupportedOperator: + return "The operator is not supported." + case .invalidDBLocation: + return "The database location is not valid." + case .invalidAccessRequest: + return "The access request is not valid." + case .invalidIndexInfo: + return "The index information is not valid." + case .invalidNewOwner: + return "The new owner is not valid." + case .invalidModifyMode: + return "The modify mode is not valid." + case .missingRequiredExtension: + return "A required certificate extension is missing." + case .extendedKeyUsageNotCritical: + return "The extended key usage extension was not marked critical." + case .timestampMissing: + return "A timestamp was expected but was not found." + case .timestampInvalid: + return "The timestamp was not valid." + case .timestampNotTrusted: + return "The timestamp was not trusted." + case .timestampServiceNotAvailable: + return "The timestamp service is not available." + case .timestampBadAlg: + return "An unrecognized or unsupported Algorithm Identifier in timestamp." + case .timestampBadRequest: + return "The timestamp transaction is not permitted or supported." + case .timestampBadDataFormat: + return "The timestamp data submitted has the wrong format." + case .timestampTimeNotAvailable: + return "The time source for the Timestamp Authority is not available." + case .timestampUnacceptedPolicy: + return "The requested policy is not supported by the Timestamp Authority." + case .timestampUnacceptedExtension: + return "The requested extension is not supported by the Timestamp Authority." + case .timestampAddInfoNotAvailable: + return "The additional information requested is not available." + case .timestampSystemFailure: + return "The timestamp request cannot be handled due to system failure." + case .signingTimeMissing: + return "A signing time was expected but was not found." + case .timestampRejection: + return "A timestamp transaction was rejected." + case .timestampWaiting: + return "A timestamp transaction is waiting." + case .timestampRevocationWarning: + return "A timestamp authority revocation warning was issued." + case .timestampRevocationNotification: + return "A timestamp authority revocation notification was issued." + case .unexpectedError: + return "Unexpected error has occurred." + } + } +} + +extension Status: CustomNSError { + public static let errorDomain = KeychainAccessErrorDomain + + public var errorCode: Int { + return Int(rawValue) + } + + public var errorUserInfo: [String : Any] { + return [NSLocalizedDescriptionKey: description] + } +} diff --git a/src/ios/asyncgate_iOS/Pods/KeychainAccess/README.md b/src/ios/asyncgate_iOS/Pods/KeychainAccess/README.md new file mode 100644 index 00000000..71259219 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/KeychainAccess/README.md @@ -0,0 +1,635 @@ +# KeychainAccess +[![CI Status](http://img.shields.io/travis/kishikawakatsumi/KeychainAccess.svg)](https://travis-ci.org/kishikawakatsumi/KeychainAccess) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![SPM supported](https://img.shields.io/badge/SPM-supported-DE5C43.svg?style=flat)](https://swift.org/package-manager) +[![Version](https://img.shields.io/cocoapods/v/KeychainAccess.svg)](http://cocoadocs.org/docsets/KeychainAccess) +[![Platform](https://img.shields.io/cocoapods/p/KeychainAccess.svg)](http://cocoadocs.org/docsets/KeychainAccess) + +KeychainAccess is a simple Swift wrapper for Keychain that works on iOS and OS X. Makes using Keychain APIs extremely easy and much more palatable to use in Swift. + + + + + +## :bulb: Features + +- Simple interface +- Support access group +- [Support accessibility](#accessibility) +- [Support iCloud sharing](#icloud_sharing) +- **[Support TouchID and Keychain integration (iOS 8+)](#touch_id_integration)** +- **[Support Shared Web Credentials (iOS 8+)](#shared_web_credentials)** +- [Works on both iOS & macOS](#requirements) +- [watchOS and tvOS are supported](#requirements) +- **[Mac Catalyst is supported](#requirements)** +- **[Swift 3, 4 and 5 compatible](#requirements)** + +## :book: Usage + +##### :eyes: See also: +- [:link: iOS Example Project](https://github.com/kishikawakatsumi/KeychainAccess/tree/master/Examples/Example-iOS) + +### :key: Basics + +#### Saving Application Password + +```swift +let keychain = Keychain(service: "com.example.github-token") +keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +#### Saving Internet Password + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https) +keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +### :key: Instantiation + +#### Create Keychain for Application Password + +```swift +let keychain = Keychain(service: "com.example.github-token") +``` + +```swift +let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") +``` + +#### Create Keychain for Internet Password + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https) +``` + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https, authenticationType: .htmlForm) +``` + +### :key: Adding an item + +#### subscripting + +##### for String + +```swift +keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +```swift +keychain[string: "kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +##### for NSData + +```swift +keychain[data: "secret"] = NSData(contentsOfFile: "secret.bin") +``` + +#### set method + +```swift +keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") +``` + +#### error handling + +```swift +do { + try keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") +} +catch let error { + print(error) +} +``` + +### :key: Obtaining an item + +#### subscripting + +##### for String (If the value is NSData, attempt to convert to String) + +```swift +let token = keychain["kishikawakatsumi"] +``` + +```swift +let token = keychain[string: "kishikawakatsumi"] +``` + +##### for NSData + +```swift +let secretData = keychain[data: "secret"] +``` + +#### get methods + +##### as String + +```swift +let token = try? keychain.get("kishikawakatsumi") +``` + +```swift +let token = try? keychain.getString("kishikawakatsumi") +``` + +##### as NSData + +```swift +let data = try? keychain.getData("kishikawakatsumi") +``` + +### :key: Removing an item + +#### subscripting + +```swift +keychain["kishikawakatsumi"] = nil +``` + +#### remove method + +```swift +do { + try keychain.remove("kishikawakatsumi") +} catch let error { + print("error: \(error)") +} +``` + +### :key: Set Label and Comment + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https) +do { + try keychain + .label("github.com (kishikawakatsumi)") + .comment("github access token") + .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") +} catch let error { + print("error: \(error)") +} +``` + +### :key: Obtaining Other Attributes + +#### PersistentRef + +```swift +let keychain = Keychain() +let persistentRef = keychain[attributes: "kishikawakatsumi"]?.persistentRef +... +``` + +#### Creation Date + +```swift +let keychain = Keychain() +let creationDate = keychain[attributes: "kishikawakatsumi"]?.creationDate +... +``` + +#### All Attributes + +```swift +let keychain = Keychain() +do { + let attributes = try keychain.get("kishikawakatsumi") { $0 } + print(attributes?.comment) + print(attributes?.label) + print(attributes?.creator) + ... +} catch let error { + print("error: \(error)") +} +``` + +##### subscripting + +```swift +let keychain = Keychain() +if let attributes = keychain[attributes: "kishikawakatsumi"] { + print(attributes.comment) + print(attributes.label) + print(attributes.creator) +} +``` + +### :key: Configuration (Accessibility, Sharing, iCloud Sync) + +**Provides fluent interfaces** + +```swift +let keychain = Keychain(service: "com.example.github-token") + .label("github.com (kishikawakatsumi)") + .synchronizable(true) + .accessibility(.afterFirstUnlock) +``` + +#### Accessibility + +##### Default accessibility matches background application (=kSecAttrAccessibleAfterFirstUnlock) + +```swift +let keychain = Keychain(service: "com.example.github-token") +``` + +##### For background application + +###### Creating instance + +```swift +let keychain = Keychain(service: "com.example.github-token") + .accessibility(.afterFirstUnlock) + +keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +###### One-shot + +```swift +let keychain = Keychain(service: "com.example.github-token") + +do { + try keychain + .accessibility(.afterFirstUnlock) + .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") +} catch let error { + print("error: \(error)") +} +``` + +##### For foreground application + +###### Creating instance + +```swift +let keychain = Keychain(service: "com.example.github-token") + .accessibility(.whenUnlocked) + +keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +###### One-shot + +```swift +let keychain = Keychain(service: "com.example.github-token") + +do { + try keychain + .accessibility(.whenUnlocked) + .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") +} catch let error { + print("error: \(error)") +} +``` + +#### :couple: Sharing Keychain items + +```swift +let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") +``` + +#### :arrows_counterclockwise: Synchronizing Keychain items with iCloud + +###### Creating instance + +```swift +let keychain = Keychain(service: "com.example.github-token") + .synchronizable(true) + +keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" +``` + +###### One-shot + +```swift +let keychain = Keychain(service: "com.example.github-token") + +do { + try keychain + .synchronizable(true) + .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") +} catch let error { + print("error: \(error)") +} +``` + +### :cyclone: Touch ID (Face ID) integration + +**Any Operation that require authentication must be run in the background thread.** +**If you run in the main thread, UI thread will lock for the system to try to display the authentication dialog.** + + +**To use Face ID, add `NSFaceIDUsageDescription` key to your `Info.plist`** + +#### :closed_lock_with_key: Adding a Touch ID (Face ID) protected item + +If you want to store the Touch ID protected Keychain item, specify `accessibility` and `authenticationPolicy` attributes. + +```swift +let keychain = Keychain(service: "com.example.github-token") + +DispatchQueue.global().async { + do { + // Should be the secret invalidated when passcode is removed? If not then use `.WhenUnlocked` + try keychain + .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: .userPresence) + .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") + } catch let error { + // Error handling if needed... + } +} +``` + +#### :closed_lock_with_key: Updating a Touch ID (Face ID) protected item + +The same way as when adding. + +**Do not run in the main thread if there is a possibility that the item you are trying to add already exists, and protected.** +**Because updating protected items requires authentication.** + +Additionally, you want to show custom authentication prompt message when updating, specify an `authenticationPrompt` attribute. +If the item not protected, the `authenticationPrompt` parameter just be ignored. + +```swift +let keychain = Keychain(service: "com.example.github-token") + +DispatchQueue.global().async { + do { + // Should be the secret invalidated when passcode is removed? If not then use `.WhenUnlocked` + try keychain + .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: .userPresence) + .authenticationPrompt("Authenticate to update your access token") + .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") + } catch let error { + // Error handling if needed... + } +} +``` + +#### :closed_lock_with_key: Obtaining a Touch ID (Face ID) protected item + +The same way as when you get a normal item. It will be displayed automatically Touch ID or passcode authentication If the item you try to get is protected. +If you want to show custom authentication prompt message, specify an `authenticationPrompt` attribute. +If the item not protected, the `authenticationPrompt` parameter just be ignored. + +```swift +let keychain = Keychain(service: "com.example.github-token") + +DispatchQueue.global().async { + do { + let password = try keychain + .authenticationPrompt("Authenticate to login to server") + .get("kishikawakatsumi") + + print("password: \(password)") + } catch let error { + // Error handling if needed... + } +} +``` + +#### :closed_lock_with_key: Removing a Touch ID (Face ID) protected item + +The same way as when you remove a normal item. +There is no way to show Touch ID or passcode authentication when removing Keychain items. + +```swift +let keychain = Keychain(service: "com.example.github-token") + +do { + try keychain.remove("kishikawakatsumi") +} catch let error { + // Error handling if needed... +} +``` + +### :key: Shared Web Credentials + +> Shared web credentials is a programming interface that enables native iOS apps to share credentials with their website counterparts. For example, a user may log in to a website in Safari, entering a user name and password, and save those credentials using the iCloud Keychain. Later, the user may run a native app from the same developer, and instead of the app requiring the user to reenter a user name and password, shared web credentials gives it access to the credentials that were entered earlier in Safari. The user can also create new accounts, update passwords, or delete her account from within the app. These changes are then saved and used by Safari. + + + +```swift +let keychain = Keychain(server: "https://www.kishikawakatsumi.com", protocolType: .HTTPS) + +let username = "kishikawakatsumi@mac.com" + +// First, check the credential in the app's Keychain +if let password = try? keychain.get(username) { + // If found password in the Keychain, + // then log into the server +} else { + // If not found password in the Keychain, + // try to read from Shared Web Credentials + keychain.getSharedPassword(username) { (password, error) -> () in + if password != nil { + // If found password in the Shared Web Credentials, + // then log into the server + // and save the password to the Keychain + + keychain[username] = password + } else { + // If not found password either in the Keychain also Shared Web Credentials, + // prompt for username and password + + // Log into server + + // If the login is successful, + // save the credentials to both the Keychain and the Shared Web Credentials. + + keychain[username] = inputPassword + keychain.setSharedPassword(inputPassword, account: username) + } + } +} +``` + +#### Request all associated domain's credentials + +```swift +Keychain.requestSharedWebCredential { (credentials, error) -> () in + +} +``` + +#### Generate strong random password + +Generate strong random password that is in the same format used by Safari autofill (xxx-xxx-xxx-xxx). + +```swift +let password = Keychain.generatePassword() // => Nhu-GKm-s3n-pMx +``` + +#### How to set up Shared Web Credentials + +> 1. Add a com.apple.developer.associated-domains entitlement to your app. This entitlement must include all the domains with which you want to share credentials. +> +> 2. Add an apple-app-site-association file to your website. This file must include application identifiers for all the apps with which the site wants to share credentials, and it must be properly signed. +> +> 3. When the app is installed, the system downloads and verifies the site association file for each of its associated domains. If the verification is successful, the app is associated with the domain. + +**More details:** + + +### :mag: Debugging + +#### Display all stored items if print keychain object + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https) +print("\(keychain)") +``` + +``` +=> +[ + [authenticationType: default, key: kishikawakatsumi, server: github.com, class: internetPassword, protocol: https] + [authenticationType: default, key: hirohamada, server: github.com, class: internetPassword, protocol: https] + [authenticationType: default, key: honeylemon, server: github.com, class: internetPassword, protocol: https] +] +``` + +#### Obtaining all stored keys + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https) + +let keys = keychain.allKeys() +for key in keys { + print("key: \(key)") +} +``` + +``` +=> +key: kishikawakatsumi +key: hirohamada +key: honeylemon +``` + +#### Obtaining all stored items + +```swift +let keychain = Keychain(server: "https://github.com", protocolType: .https) + +let items = keychain.allItems() +for item in items { + print("item: \(item)") +} +``` + +``` +=> +item: [authenticationType: Default, key: kishikawakatsumi, server: github.com, class: InternetPassword, protocol: https] +item: [authenticationType: Default, key: hirohamada, server: github.com, class: InternetPassword, protocol: https] +item: [authenticationType: Default, key: honeylemon, server: github.com, class: InternetPassword, protocol: https] +``` + +## Keychain sharing capability + +If you encounter the error below, you need to add an `Keychain.entitlements`. + +``` +OSStatus error:[-34018] Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements. +``` + +Screen Shot 2019-10-27 at 8 08 50 + + + +## Requirements + +| | OS | Swift | +|------------|------------------------------------------------------------|--------------------| +| **v1.1.x** | iOS 7+, macOS 10.9+ | 1.1 | +| **v1.2.x** | iOS 7+, macOS 10.9+ | 1.2 | +| **v2.0.x** | iOS 7+, macOS 10.9+, watchOS 2+ | 2.0 | +| **v2.1.x** | iOS 7+, macOS 10.9+, watchOS 2+ | 2.0 | +| **v2.2.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 2.0, 2.1 | +| **v2.3.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 2.0, 2.1, 2.2 | +| **v2.4.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 2.2, 2.3 | +| **v3.0.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 3.x | +| **v3.1.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 4.0, 4.1, 4.2 | +| **v3.2.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 4.0, 4.1, 4.2, 5.0 | +| **v4.0.x** | iOS 8+, macOS 10.9+, watchOS 2+, tvOS 9+ | 4.0, 4.1, 4.2, 5.1 | +| **v4.1.x** | iOS 8+, macOS 10.9+, watchOS 3+, tvOS 9+, Mac Catalyst 13+ | 4.0, 4.1, 4.2, 5.1 | + +## Installation + +### CocoaPods + +KeychainAccess is available through [CocoaPods](http://cocoapods.org). To install +it, simply add the following lines to your Podfile: + +```ruby +use_frameworks! +pod 'KeychainAccess' +``` + +### Carthage + +KeychainAccess is available through [Carthage](https://github.com/Carthage/Carthage). To install +it, simply add the following line to your Cartfile: + +`github "kishikawakatsumi/KeychainAccess"` + +### Swift Package Manager + +KeychainAccess is also available through [Swift Package Manager](https://github.com/apple/swift-package-manager/). + +#### Xcode + +Select `File > Swift Packages > Add Package Dependency...`, + + + +#### CLI + +First, create `Package.swift` that its package declaration includes: + +```swift +// swift-tools-version:5.0 +import PackageDescription + +let package = Package( + name: "MyLibrary", + products: [ + .library(name: "MyLibrary", targets: ["MyLibrary"]), + ], + dependencies: [ + .package(url: "https://github.com/kishikawakatsumi/KeychainAccess.git", from: "3.0.0"), + ], + targets: [ + .target(name: "MyLibrary", dependencies: ["KeychainAccess"]), + ] +) +``` + +Then, type + +```shell +$ swift build +``` + +### To manually add to your project + +1. Add `Lib/KeychainAccess.xcodeproj` to your project +2. Link `KeychainAccess.framework` with your target +3. Add `Copy Files Build Phase` to include the framework to your application bundle + +_See [iOS Example Project](https://github.com/kishikawakatsumi/KeychainAccess/tree/master/Examples/Example-iOS) as reference._ + + + +## Author + +kishikawa katsumi, kishikawakatsumi@mac.com + +## License + +KeychainAccess is available under the MIT license. See the LICENSE file for more info. diff --git a/src/ios/asyncgate_iOS/Pods/Manifest.lock b/src/ios/asyncgate_iOS/Pods/Manifest.lock new file mode 100644 index 00000000..8e3bfa19 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Manifest.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (5.10.2) + - KeychainAccess (4.2.2) + - Starscream (4.0.8) + +DEPENDENCIES: + - Alamofire (~> 5.5) + - KeychainAccess + - Starscream (~> 4.0.6) + +SPEC REPOS: + trunk: + - Alamofire + - KeychainAccess + - Starscream + +SPEC CHECKSUMS: + Alamofire: 7193b3b92c74a07f85569e1a6c4f4237291e7496 + KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51 + Starscream: 19b5533ddb925208db698f0ac508a100b884a1b9 + +PODFILE CHECKSUM: d5b33e6604d89dac19a1810a1f3fcea6c1ea8bef + +COCOAPODS: 1.16.2 diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/project.pbxproj b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 00000000..4e9f7fd5 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1872 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 00D69AD872EF460A7A9715B345A1C31B /* Protected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56501B182412015B15854FE4EE009688 /* Protected.swift */; }; + 074387D1012BC0F5C90B358F27A1331F /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D318EE975524358AF97E39A8BFDFEB53 /* RequestCompression.swift */; }; + 07B83A2E6FCF9A05339E6974FC9D3D32 /* WebSocketServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DF9237140607B2EAE74095538F1AF70 /* WebSocketServer.swift */; }; + 083B0B494C5F6B69924BB36E3850D23E /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = E23AEA5C9C8F37B3F64A7967466DEC37 /* RequestTaskMap.swift */; }; + 0DC813E62FCEF6C6C3009180D7790BFE /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B372A845370D74FAE7284A89A6A0A19 /* Result+Alamofire.swift */; }; + 1313426F64905A867293DAA192DDAB28 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EF6C82979E6D0782061E25E13C86AA9 /* URLEncodedFormEncoder.swift */; }; + 132F780E43E12D7EDADAA2AD29A012AA /* Starscream-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 19E3FE8288594C25E977930430174E76 /* Starscream-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 142CEF997CA8B1AB5F1063FBD3FB6C79 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */; }; + 1E3E2F1DF5E1C8D27447FCF94D111167 /* FoundationHTTPServerHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FCC08BF4ABA45FE59D07DCC47558068 /* FoundationHTTPServerHandler.swift */; }; + 20988E7C942B437989E7A7BF1F8E9136 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14CF6ABDCF4456D79AFC88BE1D70741D /* DispatchQueue+Alamofire.swift */; }; + 20D8D2C1254B0DCF38CD4E3F0997E52A /* KeychainAccess-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 306D250C8B87CD2B6D01ADF130299BEE /* KeychainAccess-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 21A5D9EBAC5FED24E7FE77087A33B645 /* Framer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70CDDA8308544DFFCAA532E9241712EC /* Framer.swift */; }; + 2558B9A09FEC5710F7D00DD5E3E053C5 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB9D381B829BDAC063D7E5DC775AD8C2 /* Request.swift */; }; + 31E77D0FAC67DCFEE1F3173E441C67D6 /* Security.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61FE945A3F79F87A400FA85D992A8ED3 /* Security.swift */; }; + 39D449220194AE1CD884069FBF6F735D /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8400561C73BEB7F341F42652BC804BB2 /* URLSessionConfiguration+Alamofire.swift */; }; + 3BCAE7843A2516EBA64768CC0CD79988 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCA05E2A928D7750E0E6A7C071A2AD1E /* ParameterEncoder.swift */; }; + 3CFB26DFC9AC8164AEC49CD75577C535 /* FoundationHTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFEC30BB665B463B67F87FFB74C48E3C /* FoundationHTTPHandler.swift */; }; + 422D446AE9FFA55420A3F5286C016FB9 /* Pods-asyncgate_iOS-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 326C2A2838401B445A4346952D0855D0 /* Pods-asyncgate_iOS-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 43FE097FBE9B5568B702545F99072CFB /* FoundationTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = A23FB1A6A1EF670C42ACA4D2EC8F4A90 /* FoundationTransport.swift */; }; + 453CB5E8B81F432DBD99BD674E41F79F /* Keychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 173489F92BAFC8AF0D2EF2E9DE661AA3 /* Keychain.swift */; }; + 47FBA86C15EC8060331926C9A8D54BB1 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3F9A5AE06B856BADA4B2CE447D2522E4 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4816EF150D924B1987414B356C7AB77E /* FrameCollector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 432D68A6A34F1069B1520610788AF8B9 /* FrameCollector.swift */; }; + 4AC4E87A3CB2C676949C33E78E64BA93 /* Starscream-Starscream_Privacy in Resources */ = {isa = PBXBuildFile; fileRef = 90DF440CB562947BB255E9A3E9B29568 /* Starscream-Starscream_Privacy */; }; + 4C5BB45AFA17EE49908EEE4B8163EF76 /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = 364CDE104597AA95F84250D3D193B9F0 /* Server.swift */; }; + 4D9E593DECA015D410984C771CCFDD12 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 71720BABA2A8C553D17D506249671632 /* Alamofire-dummy.m */; }; + 524EA7DEF50C0D0FDB5A171360D97946 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8486B4F5DF5836AA960DA124537F0E04 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 54A45AF20BFF99BA20B15AF09AC4901C /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFEF43FFBEFC92E576A2E5200BDE8C60 /* Notifications.swift */; }; + 55DAC2E8DC333019B6C1D70EC91B0A22 /* WSCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 606F9261E693AC537944C7315B5E1246 /* WSCompression.swift */; }; + 5746320BBB67E457AF4C4EE5A2D32799 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D2541F01CEDC5D06D49EFF897D9CFFD /* Validation.swift */; }; + 5ABDF47FC0D60B701B5A8E767DC1314F /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC98A8215F9B5ECC4F661CA10787E827 /* EventMonitor.swift */; }; + 5CD127F101529C336A07D45CE1106A54 /* Alamofire-Alamofire in Resources */ = {isa = PBXBuildFile; fileRef = 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */; }; + 6158EE4029691FD08F12BCF76999F060 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */; }; + 66F024DCBE9C5AE50FD48FE6876D5DEB /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 423128D2D8E40498722E267B615BB555 /* ResponseSerialization.swift */; }; + 69111C8CB8268AAD6DD50A84B22944EE /* FoundationSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6206F9EB1D0F54EF06820D9530C8FF2 /* FoundationSecurity.swift */; }; + 6D3071F804219E6A520372754BA9F09C /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32C129E4D16FF427E2AF39FD3B4FF4F0 /* URLConvertible+URLRequestConvertible.swift */; }; + 72F899A56B333FDAA44453342ED56E7F /* Pods-asyncgate_iOSTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CDEF61AE77DFB5689BFCBB5B07F3AB47 /* Pods-asyncgate_iOSTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7933EDD15F245D28BE5D99E203E9BD1F /* DataStreamRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3EE7229C9B0BC3C7947D5B93F157181 /* DataStreamRequest.swift */; }; + 7A232A8D5C0D06F3CE373E1B46422118 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11519F969AC6A764F3FCA32D9F510165 /* AFError.swift */; }; + 849FF90CD07B763B0D53DD4656BDED61 /* DownloadRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FF1969E881F4F66EA0D543A6BC69C67 /* DownloadRequest.swift */; }; + 85F55FDAED763889D7DADACE5DC5C567 /* WSEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8030BC39B02644EB1D64B8659592EB22 /* WSEngine.swift */; }; + 8904ED8DEB77CA657A4EED2F86EB961A /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33929497CE40CE557C84DC9D0D428DC8 /* AlamofireExtended.swift */; }; + 8A472901A6A0E2D7231E376832198241 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C9A9DB3D00A80D8201500A3CB7DCDE5 /* WebSocket.swift */; }; + 8D3627F773DB54051EAC3F81DB267696 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = E454599A11BB5BF371C1B427F7607DA3 /* PrivacyInfo.xcprivacy */; }; + 8D51421FF478040E6383D24254900967 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F5F67A24F91CF1ED218D2C72FDF144D /* CFNetwork.framework */; }; + 8DF169B3ADBCBA100BE5D2CA34EDC31A /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7102AD45CADE73C3525FBB8FA577FC3A /* Combine.swift */; }; + 8F4AC5455CDD202655025DE431360AEE /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E74677F64BF1B0ABEE7A723EE59B7090 /* ParameterEncoding.swift */; }; + 9815712350A1C2F91A5CFD84FDD9B391 /* Pods-asyncgate_iOS-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6072F76F5C28A1115E013DA132C1B0F9 /* Pods-asyncgate_iOS-dummy.m */; }; + 9C89110A7C655E5C39B3135E9020CBF7 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA82622E9B6B642D8590A735D2FB851E /* Alamofire.swift */; }; + 9CE2B0DEBE0178D7BCA89AD9A7F0BFDF /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = C29E4BA2F835BA91E8628C453EC2F442 /* MultipartFormData.swift */; }; + 9D46306826317C2783B0A8255691E035 /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4771B27E03FD30154D6D0BCE2F00370 /* StringEncoding+Alamofire.swift */; }; + 9E06B7BFED7A03866DA9B65A1F82D185 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */; }; + A017485C3C202ADD0A059DFCCDA5D14D /* Starscream-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FF81CF9512C7A5C10A53FCB0FF24A688 /* Starscream-dummy.m */; }; + A0A17B87EE7B5E97A88DAB84B7DF3649 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */; }; + A698A792F293BA997FE75C70CD18B022 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDF105515A2E151D36F33D2250A834E /* OperationQueue+Alamofire.swift */; }; + A8437EFD962B3A3F812B756C76ADD87B /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D95261CDCE4725F0494D77CEBB11BFD /* HTTPMethod.swift */; }; + A8960279BB85041C12ADB3A704754B7F /* Pods-asyncgate_iOSTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 30653AD134C54DDDF2BAFC1D728082E9 /* Pods-asyncgate_iOSTests-dummy.m */; }; + A9B0233F2C7CD6365526CA2178F9215F /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C190A553320271C09E65CF3B99386D52 /* URLRequest+Alamofire.swift */; }; + B1EDE680CB2182C3B4900E1945783F9B /* NativeEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0132DD6BC218430E4129462F65D66870 /* NativeEngine.swift */; }; + B23B20F1C3E3BA41870F9137074F1AEE /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DB2F08D4E65A2892A448E6443982A56 /* MultipartUpload.swift */; }; + B2593CE3DA0E29BD821FF0C0860447B4 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B42C29B6A8503798566194B3B07CEE83 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m */; }; + B32BC6D67438172D5B58955EAB85D802 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */; }; + B3EC2DE8A5B6FAF5ED30071E4A3D9BE7 /* DataRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B46F59305E50B334650CAB878B972F /* DataRequest.swift */; }; + BACE03596343C2C83670A3996164D2F0 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = D78391C81FB7A4E5B9A8CEC48868A925 /* RetryPolicy.swift */; }; + BECD28904453E5C00C66B51D37CAD433 /* Transport.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF29040AF8733F5855A98D1E891A7A1E /* Transport.swift */; }; + C27AC4CF7DC6EEF22BE5CF742C34BF1B /* Data+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8516A00B772EF9696377A430B9F72BF /* Data+Extensions.swift */; }; + C437FA9AF753C87C55F0849F7E1E176E /* UploadRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B7D4E16F72F7A5F4E7BAAC6D9914466 /* UploadRequest.swift */; }; + C48A9E2CABF2ABD7D954BC1FBB6D3C77 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = F04FDCB40B6ED3C4357E3C78095985EE /* RedirectHandler.swift */; }; + C6E542DE6D61F7CD41340049F2D8FFDE /* AuthenticationInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0E44801C91E1BE06FE49B0DBB45B611 /* AuthenticationInterceptor.swift */; }; + C6E71C71E4833389B33C0199196A5E13 /* Engine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F850E07328C30D60F3882C04C09A388 /* Engine.swift */; }; + CDF42ED6AF2C0252840DF2A724375380 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F537DDC82AA2136183F14734E6E333AF /* SessionDelegate.swift */; }; + CECA8162BFE05143ECD1DE4225B82B9C /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAD7866CF0C10DE9FE698015834F1687 /* CachedResponseHandler.swift */; }; + CFDB27ACA68B4C18C6DC1E51998D7623 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F8B98826CB69D713D1B7EC87D001CD3 /* HTTPHeaders.swift */; }; + D2854184492AB0652C029448967FE129 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ED337B10DDA1941E08A3EA9ACCA1594 /* ServerTrustEvaluation.swift */; }; + D5A2B190C4A0490CAACAD3C4FC76531D /* Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C18DD7A782E9D6D2D8A5A1DB6112634 /* Concurrency.swift */; }; + D6102474025E613F9F8D98EFB708CEC6 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 827EF1A98D3F1D2A504A325F539D3640 /* Compression.swift */; }; + D8D51B6D3248D9CEA719A66A2ABC7319 /* StringHTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C881398D265BA12E076C400F85F6E31 /* StringHTTPHandler.swift */; }; + DC116AC0C3BC808A198B9C1704FA8C84 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CF178A4B8DD96FF0E6A97B9E2C17B88 /* RequestInterceptor.swift */; }; + DC2BE589B1C5A65E08CA6D9D7C319E17 /* HTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6AB11C2577C761A2A57C0D79F717C0B /* HTTPHandler.swift */; }; + E2A136B54D170407827AF6AD3901960A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */; }; + E4180B507E0C530F0D7CAEFA1FAEA06F /* KeychainAccess-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 67FDF22EDED932BE7B1562C5DB126A77 /* KeychainAccess-dummy.m */; }; + E4BEE8283802F8F8B17F1A1BBBD3CDE4 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A3930860F22B0DB2936489D3F682149 /* Session.swift */; }; + ECBB9D041E2943036EFF0AD5B7E63B4C /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FFABBC947F0F16AA011FF708C7E6502 /* Response.swift */; }; + EDD1F4A31BC9F0816F25B14E0B4B89B5 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF6F94774D0D1EDA63FE4BD5DDFC146F /* NetworkReachabilityManager.swift */; }; + FAB703884AC7E3E527AB50FB9001276B /* WebSocketRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 977A6AD416738296B5DBB41F6DB9E5ED /* WebSocketRequest.swift */; }; + FD8A6F93705C4B172C32D52D17B2B5DC /* TCPTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85784B520B446895DEFF6C56E422E600 /* TCPTransport.swift */; }; + FFA11505FB1BAD600F090D2646DCB86D /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = D9A84671C2C86C5AB3421D1721840512 /* PrivacyInfo.xcprivacy */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 093776EEE352BBC2B73D6A22F0FD40A7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 03F6734F0758DC338768C753B543BAB5; + remoteInfo = "Pods-asyncgate_iOS"; + }; + 1260E37E9610D031695C30D81FAAC442 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 2D8C78DCB11EC8D20D81661A874CF54A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 615C831BCE925ED486B225B87E44926D; + remoteInfo = KeychainAccess; + }; + 6DD1B3E04383EDDFC1798398CC60D01E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + 933191256C2E9E2BB3B96DC7B7AA47FA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + A47C07C96A5D7FFEC6DAF2ACDBEF7311 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 615C831BCE925ED486B225B87E44926D; + remoteInfo = KeychainAccess; + }; + A9E290F5AC68E340303DC0860B4EBB51 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 976126A1CE06DC6E162563800E1BDF14; + remoteInfo = "Alamofire-Alamofire"; + }; + B1D08E7283ABA142CF92D0B04EA7AED5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + D9E1591248FD4E00439C8F8C71B51FF9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 771210E06FA095D070EFB58429312B8F; + remoteInfo = "Starscream-Starscream_Privacy"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0132DD6BC218430E4129462F65D66870 /* NativeEngine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NativeEngine.swift; path = Sources/Engine/NativeEngine.swift; sourceTree = ""; }; + 077D03A597F60886A9E36B659F1ECA0B /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; + 0856604687003A2D412CAA80F7A8F686 /* Pods-asyncgate_iOS-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-asyncgate_iOS-frameworks.sh"; sourceTree = ""; }; + 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "Alamofire-Alamofire"; path = Alamofire.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 096AD6DD2651B388B8AD33D52C0F1E3B /* Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig"; sourceTree = ""; }; + 0972289B7EBCD71C4C1D5116EE3AACE6 /* Starscream.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.release.xcconfig; sourceTree = ""; }; + 0FCC08BF4ABA45FE59D07DCC47558068 /* FoundationHTTPServerHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationHTTPServerHandler.swift; path = Sources/Framer/FoundationHTTPServerHandler.swift; sourceTree = ""; }; + 11519F969AC6A764F3FCA32D9F510165 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/Core/AFError.swift; sourceTree = ""; }; + 129210C02226E114925FA3984D355E82 /* Alamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.release.xcconfig; sourceTree = ""; }; + 14CF6ABDCF4456D79AFC88BE1D70741D /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/Extensions/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 173489F92BAFC8AF0D2EF2E9DE661AA3 /* Keychain.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Keychain.swift; path = Lib/KeychainAccess/Keychain.swift; sourceTree = ""; }; + 19E3FE8288594C25E977930430174E76 /* Starscream-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-umbrella.h"; sourceTree = ""; }; + 1C881398D265BA12E076C400F85F6E31 /* StringHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringHTTPHandler.swift; path = Sources/Framer/StringHTTPHandler.swift; sourceTree = ""; }; + 1FC42E2DD8BE25E03DE4AFB41D4C4BF5 /* Pods-asyncgate_iOSTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-asyncgate_iOSTests.debug.xcconfig"; sourceTree = ""; }; + 2D2541F01CEDC5D06D49EFF897D9CFFD /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Features/Validation.swift; sourceTree = ""; }; + 2EF6C82979E6D0782061E25E13C86AA9 /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/Features/URLEncodedFormEncoder.swift; sourceTree = ""; }; + 30653AD134C54DDDF2BAFC1D728082E9 /* Pods-asyncgate_iOSTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-asyncgate_iOSTests-dummy.m"; sourceTree = ""; }; + 306D250C8B87CD2B6D01ADF130299BEE /* KeychainAccess-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "KeychainAccess-umbrella.h"; sourceTree = ""; }; + 326C2A2838401B445A4346952D0855D0 /* Pods-asyncgate_iOS-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-asyncgate_iOS-umbrella.h"; sourceTree = ""; }; + 32C129E4D16FF427E2AF39FD3B4FF4F0 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/Core/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + 33929497CE40CE557C84DC9D0D428DC8 /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/Features/AlamofireExtended.swift; sourceTree = ""; }; + 364CDE104597AA95F84250D3D193B9F0 /* Server.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Server.swift; path = Sources/Server/Server.swift; sourceTree = ""; }; + 37259FFD60EEBA0F4DC83BE9DA044C74 /* Pods-asyncgate_iOS */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-asyncgate_iOS"; path = Pods_asyncgate_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 3756254E49A40FC70F7D70660FE613CE /* Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig"; sourceTree = ""; }; + 3A3930860F22B0DB2936489D3F682149 /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Core/Session.swift; sourceTree = ""; }; + 3B97412F84414FAB3B5F5166CABF7EEE /* Pods-asyncgate_iOSTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-asyncgate_iOSTests.release.xcconfig"; sourceTree = ""; }; + 3D95261CDCE4725F0494D77CEBB11BFD /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/Core/HTTPMethod.swift; sourceTree = ""; }; + 3DB2F08D4E65A2892A448E6443982A56 /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/Features/MultipartUpload.swift; sourceTree = ""; }; + 3DBFD164F44E23287C3D058BC4CA357F /* Pods-asyncgate_iOSTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-asyncgate_iOSTests.modulemap"; sourceTree = ""; }; + 3DF9237140607B2EAE74095538F1AF70 /* WebSocketServer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocketServer.swift; path = Sources/Server/WebSocketServer.swift; sourceTree = ""; }; + 3ED337B10DDA1941E08A3EA9ACCA1594 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/Features/ServerTrustEvaluation.swift; sourceTree = ""; }; + 3EDF105515A2E151D36F33D2250A834E /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/Extensions/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + 3F9A5AE06B856BADA4B2CE447D2522E4 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 3FF1969E881F4F66EA0D543A6BC69C67 /* DownloadRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DownloadRequest.swift; path = Source/Core/DownloadRequest.swift; sourceTree = ""; }; + 423128D2D8E40498722E267B615BB555 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/Features/ResponseSerialization.swift; sourceTree = ""; }; + 432D68A6A34F1069B1520610788AF8B9 /* FrameCollector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FrameCollector.swift; path = Sources/Framer/FrameCollector.swift; sourceTree = ""; }; + 4ACD385E36B1CECC40D2D0B2D7932DCF /* Pods-asyncgate_iOS-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-asyncgate_iOS-Info.plist"; sourceTree = ""; }; + 4FFABBC947F0F16AA011FF708C7E6502 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Core/Response.swift; sourceTree = ""; }; + 50D0189FD2A4CB9721E1DF064925DA4B /* Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.plist"; sourceTree = ""; }; + 56501B182412015B15854FE4EE009688 /* Protected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protected.swift; path = Source/Core/Protected.swift; sourceTree = ""; }; + 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 58A58C6CAF3A48C08FE8CA3C103F413B /* Pods-asyncgate_iOS-asyncgate_iOSUITests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-asyncgate_iOS-asyncgate_iOSUITests"; path = Pods_asyncgate_iOS_asyncgate_iOSUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5F5F67A24F91CF1ED218D2C72FDF144D /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 606F9261E693AC537944C7315B5E1246 /* WSCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WSCompression.swift; path = Sources/Compression/WSCompression.swift; sourceTree = ""; }; + 6072F76F5C28A1115E013DA132C1B0F9 /* Pods-asyncgate_iOS-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-asyncgate_iOS-dummy.m"; sourceTree = ""; }; + 61FE945A3F79F87A400FA85D992A8ED3 /* Security.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Security.swift; path = Sources/Security/Security.swift; sourceTree = ""; }; + 648B45D10AABAA3AB67354B4CB25F3CD /* Pods-asyncgate_iOSTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-asyncgate_iOSTests-Info.plist"; sourceTree = ""; }; + 65C2A0BE949C356C23F265F2A5822025 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap"; sourceTree = ""; }; + 67FDF22EDED932BE7B1562C5DB126A77 /* KeychainAccess-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "KeychainAccess-dummy.m"; sourceTree = ""; }; + 68688F18441D7F7414917AACD7FC927F /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + 6C9A9DB3D00A80D8201500A3CB7DCDE5 /* WebSocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Sources/Starscream/WebSocket.swift; sourceTree = ""; }; + 6CF178A4B8DD96FF0E6A97B9E2C17B88 /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/Features/RequestInterceptor.swift; sourceTree = ""; }; + 6F37FA0BDFD9023B4286F6C3A0A7AA39 /* Starscream.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Starscream.modulemap; sourceTree = ""; }; + 70CDDA8308544DFFCAA532E9241712EC /* Framer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Framer.swift; path = Sources/Framer/Framer.swift; sourceTree = ""; }; + 7102AD45CADE73C3525FBB8FA577FC3A /* Combine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Source/Features/Combine.swift; sourceTree = ""; }; + 71720BABA2A8C553D17D506249671632 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 719D50C81202E0C48D1CE45BC55F6156 /* Pods-asyncgate_iOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-asyncgate_iOS.release.xcconfig"; sourceTree = ""; }; + 798D97427BF035F3B49BBBBA845394DF /* Pods-asyncgate_iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-asyncgate_iOS.debug.xcconfig"; sourceTree = ""; }; + 7B00AA45E5870C31404FBE7FCEC794BD /* Alamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.debug.xcconfig; sourceTree = ""; }; + 7B372A845370D74FAE7284A89A6A0A19 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Extensions/Result+Alamofire.swift"; sourceTree = ""; }; + 8030BC39B02644EB1D64B8659592EB22 /* WSEngine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WSEngine.swift; path = Sources/Engine/WSEngine.swift; sourceTree = ""; }; + 827EF1A98D3F1D2A504A325F539D3640 /* Compression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Sources/Compression/Compression.swift; sourceTree = ""; }; + 8400561C73BEB7F341F42652BC804BB2 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/Extensions/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + 8486B4F5DF5836AA960DA124537F0E04 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h"; sourceTree = ""; }; + 85784B520B446895DEFF6C56E422E600 /* TCPTransport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TCPTransport.swift; path = Sources/Transport/TCPTransport.swift; sourceTree = ""; }; + 891B2270823847ED23F2ECFC28F935EC /* Starscream */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Starscream; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8B7D4E16F72F7A5F4E7BAAC6D9914466 /* UploadRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UploadRequest.swift; path = Source/Core/UploadRequest.swift; sourceTree = ""; }; + 8F8B98826CB69D713D1B7EC87D001CD3 /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/Core/HTTPHeaders.swift; sourceTree = ""; }; + 90DF440CB562947BB255E9A3E9B29568 /* Starscream-Starscream_Privacy */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "Starscream-Starscream_Privacy"; path = Starscream_Privacy.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 943E8533F71C4C73B9D2018321530DA0 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist"; sourceTree = ""; }; + 977A6AD416738296B5DBB41F6DB9E5ED /* WebSocketRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocketRequest.swift; path = Source/Core/WebSocketRequest.swift; sourceTree = ""; }; + 988CEC46F4B4E458E9AF73F19D7FA797 /* KeychainAccess-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "KeychainAccess-prefix.pch"; sourceTree = ""; }; + 9C18DD7A782E9D6D2D8A5A1DB6112634 /* Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concurrency.swift; path = Source/Features/Concurrency.swift; sourceTree = ""; }; + 9D172E58771203048A637351B914E372 /* KeychainAccess.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = KeychainAccess.debug.xcconfig; sourceTree = ""; }; + 9D83CEA5D88CA135DCC74A80FFA27C34 /* Pods-asyncgate_iOS-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-asyncgate_iOS-acknowledgements.plist"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9F850E07328C30D60F3882C04C09A388 /* Engine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Engine.swift; path = Sources/Engine/Engine.swift; sourceTree = ""; }; + A05A201DFC60A9BCBFF0934149438CAB /* Starscream.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.debug.xcconfig; sourceTree = ""; }; + A23FB1A6A1EF670C42ACA4D2EC8F4A90 /* FoundationTransport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationTransport.swift; path = Sources/Transport/FoundationTransport.swift; sourceTree = ""; }; + AFEF43FFBEFC92E576A2E5200BDE8C60 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Core/Notifications.swift; sourceTree = ""; }; + B424E5B5A71B46199522F7EB55D846F6 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh"; sourceTree = ""; }; + B42C29B6A8503798566194B3B07CEE83 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m"; sourceTree = ""; }; + B5674BD39D5A9BC5F521BFEB5AACA86E /* ResourceBundle-Starscream_Privacy-Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Starscream_Privacy-Starscream-Info.plist"; sourceTree = ""; }; + B6AB11C2577C761A2A57C0D79F717C0B /* HTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHandler.swift; path = Sources/Framer/HTTPHandler.swift; sourceTree = ""; }; + B79946132F049EEE980603C1192A34CD /* Pods-asyncgate_iOSTests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-asyncgate_iOSTests"; path = Pods_asyncgate_iOSTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BCA05E2A928D7750E0E6A7C071A2AD1E /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/Core/ParameterEncoder.swift; sourceTree = ""; }; + C190A553320271C09E65CF3B99386D52 /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/Extensions/URLRequest+Alamofire.swift"; sourceTree = ""; }; + C1B21661E5DB77628290A2F75494D97A /* KeychainAccess.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = KeychainAccess.modulemap; sourceTree = ""; }; + C29E4BA2F835BA91E8628C453EC2F442 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/Features/MultipartFormData.swift; sourceTree = ""; }; + CB6A77E51C39767E8154B4C21CF06293 /* Pods-asyncgate_iOS-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-asyncgate_iOS-acknowledgements.markdown"; sourceTree = ""; }; + CDEF61AE77DFB5689BFCBB5B07F3AB47 /* Pods-asyncgate_iOSTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-asyncgate_iOSTests-umbrella.h"; sourceTree = ""; }; + CF6F94774D0D1EDA63FE4BD5DDFC146F /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/Features/NetworkReachabilityManager.swift; sourceTree = ""; }; + D08C59680435F67642445E35B2CF9A76 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + D0E44801C91E1BE06FE49B0DBB45B611 /* AuthenticationInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationInterceptor.swift; path = Source/Features/AuthenticationInterceptor.swift; sourceTree = ""; }; + D318EE975524358AF97E39A8BFDFEB53 /* RequestCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestCompression.swift; path = Source/Features/RequestCompression.swift; sourceTree = ""; }; + D404C7E0E8F5743839286D68CE767D1A /* KeychainAccess-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "KeychainAccess-Info.plist"; sourceTree = ""; }; + D6206F9EB1D0F54EF06820D9530C8FF2 /* FoundationSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationSecurity.swift; path = Sources/Security/FoundationSecurity.swift; sourceTree = ""; }; + D78391C81FB7A4E5B9A8CEC48868A925 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/Features/RetryPolicy.swift; sourceTree = ""; }; + D8516A00B772EF9696377A430B9F72BF /* Data+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extensions.swift"; path = "Sources/DataBytes/Data+Extensions.swift"; sourceTree = ""; }; + D86737F840838377AE55ABFF0838BC83 /* Pods-asyncgate_iOS.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-asyncgate_iOS.modulemap"; sourceTree = ""; }; + D9A84671C2C86C5AB3421D1721840512 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = Sources/PrivacyInfo.xcprivacy; sourceTree = ""; }; + DA14EBD988F8B6EB5D1071C09564FF2E /* Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.markdown"; sourceTree = ""; }; + DF29040AF8733F5855A98D1E891A7A1E /* Transport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Transport.swift; path = Sources/Transport/Transport.swift; sourceTree = ""; }; + DFEC30BB665B463B67F87FFB74C48E3C /* FoundationHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationHTTPHandler.swift; path = Sources/Framer/FoundationHTTPHandler.swift; sourceTree = ""; }; + E23AEA5C9C8F37B3F64A7967466DEC37 /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/Core/RequestTaskMap.swift; sourceTree = ""; }; + E454599A11BB5BF371C1B427F7607DA3 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = Source/PrivacyInfo.xcprivacy; sourceTree = ""; }; + E4B46F59305E50B334650CAB878B972F /* DataRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataRequest.swift; path = Source/Core/DataRequest.swift; sourceTree = ""; }; + E74677F64BF1B0ABEE7A723EE59B7090 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/Core/ParameterEncoding.swift; sourceTree = ""; }; + E891D38FF1D731F19501A270D6D90CB4 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + E8EE7F078656FABB8F6821D10FF994BB /* KeychainAccess */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = KeychainAccess; path = KeychainAccess.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + EA82622E9B6B642D8590A735D2FB851E /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + EAD7866CF0C10DE9FE698015834F1687 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/Features/CachedResponseHandler.swift; sourceTree = ""; }; + F04FDCB40B6ED3C4357E3C78095985EE /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/Features/RedirectHandler.swift; sourceTree = ""; }; + F0D2BBD716215E30AA571ADCF5E2FC67 /* Pods-asyncgate_iOSTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-asyncgate_iOSTests-acknowledgements.markdown"; sourceTree = ""; }; + F2DD480099D6F2C8A8A411B2A918D535 /* ResourceBundle-Alamofire-Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Alamofire-Alamofire-Info.plist"; sourceTree = ""; }; + F3EE7229C9B0BC3C7947D5B93F157181 /* DataStreamRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataStreamRequest.swift; path = Source/Core/DataStreamRequest.swift; sourceTree = ""; }; + F4771B27E03FD30154D6D0BCE2F00370 /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "StringEncoding+Alamofire.swift"; path = "Source/Extensions/StringEncoding+Alamofire.swift"; sourceTree = ""; }; + F537DDC82AA2136183F14734E6E333AF /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/Core/SessionDelegate.swift; sourceTree = ""; }; + F9F14DB081BEE05C035DA0CE6D2DAF3D /* KeychainAccess.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = KeychainAccess.release.xcconfig; sourceTree = ""; }; + FA1B75E9FE949B48D7CF65947B8BD790 /* Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Starscream-Info.plist"; sourceTree = ""; }; + FB9D381B829BDAC063D7E5DC775AD8C2 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Core/Request.swift; sourceTree = ""; }; + FC98A8215F9B5ECC4F661CA10787E827 /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/Features/EventMonitor.swift; sourceTree = ""; }; + FEC2DCD65C5EED5926A53A89BFCD9BAC /* Pods-asyncgate_iOSTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-asyncgate_iOSTests-acknowledgements.plist"; sourceTree = ""; }; + FF81CF9512C7A5C10A53FCB0FF24A688 /* Starscream-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Starscream-dummy.m"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0A30CA377B146419DD5D6AB08A9F5677 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0FD546A70F9E3AB529847CBF744F37C1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6158EE4029691FD08F12BCF76999F060 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 58F78AC8483C8DCBD093C04D1D38E5C3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E2A136B54D170407827AF6AD3901960A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 88CA6FBB7F7F430F2FBA288A454E4858 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8D51421FF478040E6383D24254900967 /* CFNetwork.framework in Frameworks */, + B32BC6D67438172D5B58955EAB85D802 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8A09E3EB579D177793C529FC8051283A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9E06B7BFED7A03866DA9B65A1F82D185 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 90658D007F7A05D088B40B4307CCBFF6 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 142CEF997CA8B1AB5F1063FBD3FB6C79 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 92EF5BBC3EFCFE60910B74638A1755FC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A0A17B87EE7B5E97A88DAB84B7DF3649 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E15ED9E83CA09E12DF09B9452AB473EA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */ = { + isa = PBXGroup; + children = ( + E5B9A9EF2B20D59EB52F695D6D7F759D /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 2B122EA7F2359AE7F018CAF6D006420C /* Resources */ = { + isa = PBXGroup; + children = ( + D9A84671C2C86C5AB3421D1721840512 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + 2BE19BF74AA5AD60B65C95102226EEF8 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + ED2C4262C806085AFB88ADA4844F2C5C /* Pods-asyncgate_iOS */, + 865A3C6B72AD2D2B08C6F0E96AA4FF6C /* Pods-asyncgate_iOS-asyncgate_iOSUITests */, + 9D2E01C16D6E42A6986E1FE2144AF53B /* Pods-asyncgate_iOSTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 5561A6DADA7F283FFD95E05BE8917C18 /* Resources */ = { + isa = PBXGroup; + children = ( + E454599A11BB5BF371C1B427F7607DA3 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + 60DC20A010854D532D76C961D8A37CEC /* Support Files */ = { + isa = PBXGroup; + children = ( + E891D38FF1D731F19501A270D6D90CB4 /* Alamofire.modulemap */, + 71720BABA2A8C553D17D506249671632 /* Alamofire-dummy.m */, + 68688F18441D7F7414917AACD7FC927F /* Alamofire-Info.plist */, + D08C59680435F67642445E35B2CF9A76 /* Alamofire-prefix.pch */, + 3F9A5AE06B856BADA4B2CE447D2522E4 /* Alamofire-umbrella.h */, + 7B00AA45E5870C31404FBE7FCEC794BD /* Alamofire.debug.xcconfig */, + 129210C02226E114925FA3984D355E82 /* Alamofire.release.xcconfig */, + F2DD480099D6F2C8A8A411B2A918D535 /* ResourceBundle-Alamofire-Alamofire-Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 7716805D89C36863EA0F1C5234A4D455 /* Products */ = { + isa = PBXGroup; + children = ( + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */, + 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */, + E8EE7F078656FABB8F6821D10FF994BB /* KeychainAccess */, + 37259FFD60EEBA0F4DC83BE9DA044C74 /* Pods-asyncgate_iOS */, + 58A58C6CAF3A48C08FE8CA3C103F413B /* Pods-asyncgate_iOS-asyncgate_iOSUITests */, + B79946132F049EEE980603C1192A34CD /* Pods-asyncgate_iOSTests */, + 891B2270823847ED23F2ECFC28F935EC /* Starscream */, + 90DF440CB562947BB255E9A3E9B29568 /* Starscream-Starscream_Privacy */, + ); + name = Products; + sourceTree = ""; + }; + 865A3C6B72AD2D2B08C6F0E96AA4FF6C /* Pods-asyncgate_iOS-asyncgate_iOSUITests */ = { + isa = PBXGroup; + children = ( + 65C2A0BE949C356C23F265F2A5822025 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap */, + DA14EBD988F8B6EB5D1071C09564FF2E /* Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.markdown */, + 50D0189FD2A4CB9721E1DF064925DA4B /* Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.plist */, + B42C29B6A8503798566194B3B07CEE83 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m */, + B424E5B5A71B46199522F7EB55D846F6 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh */, + 943E8533F71C4C73B9D2018321530DA0 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist */, + 8486B4F5DF5836AA960DA124537F0E04 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h */, + 3756254E49A40FC70F7D70660FE613CE /* Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig */, + 096AD6DD2651B388B8AD33D52C0F1E3B /* Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig */, + ); + name = "Pods-asyncgate_iOS-asyncgate_iOSUITests"; + path = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests"; + sourceTree = ""; + }; + 9D2E01C16D6E42A6986E1FE2144AF53B /* Pods-asyncgate_iOSTests */ = { + isa = PBXGroup; + children = ( + 3DBFD164F44E23287C3D058BC4CA357F /* Pods-asyncgate_iOSTests.modulemap */, + F0D2BBD716215E30AA571ADCF5E2FC67 /* Pods-asyncgate_iOSTests-acknowledgements.markdown */, + FEC2DCD65C5EED5926A53A89BFCD9BAC /* Pods-asyncgate_iOSTests-acknowledgements.plist */, + 30653AD134C54DDDF2BAFC1D728082E9 /* Pods-asyncgate_iOSTests-dummy.m */, + 648B45D10AABAA3AB67354B4CB25F3CD /* Pods-asyncgate_iOSTests-Info.plist */, + CDEF61AE77DFB5689BFCBB5B07F3AB47 /* Pods-asyncgate_iOSTests-umbrella.h */, + 1FC42E2DD8BE25E03DE4AFB41D4C4BF5 /* Pods-asyncgate_iOSTests.debug.xcconfig */, + 3B97412F84414FAB3B5F5166CABF7EEE /* Pods-asyncgate_iOSTests.release.xcconfig */, + ); + name = "Pods-asyncgate_iOSTests"; + path = "Target Support Files/Pods-asyncgate_iOSTests"; + sourceTree = ""; + }; + A122B93FE0EB1CC338612A135F871414 /* Support Files */ = { + isa = PBXGroup; + children = ( + C1B21661E5DB77628290A2F75494D97A /* KeychainAccess.modulemap */, + 67FDF22EDED932BE7B1562C5DB126A77 /* KeychainAccess-dummy.m */, + D404C7E0E8F5743839286D68CE767D1A /* KeychainAccess-Info.plist */, + 988CEC46F4B4E458E9AF73F19D7FA797 /* KeychainAccess-prefix.pch */, + 306D250C8B87CD2B6D01ADF130299BEE /* KeychainAccess-umbrella.h */, + 9D172E58771203048A637351B914E372 /* KeychainAccess.debug.xcconfig */, + F9F14DB081BEE05C035DA0CE6D2DAF3D /* KeychainAccess.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/KeychainAccess"; + sourceTree = ""; + }; + B563E0D9BFFA897F763FDB29177769CC /* Starscream */ = { + isa = PBXGroup; + children = ( + 827EF1A98D3F1D2A504A325F539D3640 /* Compression.swift */, + D8516A00B772EF9696377A430B9F72BF /* Data+Extensions.swift */, + 9F850E07328C30D60F3882C04C09A388 /* Engine.swift */, + DFEC30BB665B463B67F87FFB74C48E3C /* FoundationHTTPHandler.swift */, + 0FCC08BF4ABA45FE59D07DCC47558068 /* FoundationHTTPServerHandler.swift */, + D6206F9EB1D0F54EF06820D9530C8FF2 /* FoundationSecurity.swift */, + A23FB1A6A1EF670C42ACA4D2EC8F4A90 /* FoundationTransport.swift */, + 432D68A6A34F1069B1520610788AF8B9 /* FrameCollector.swift */, + 70CDDA8308544DFFCAA532E9241712EC /* Framer.swift */, + B6AB11C2577C761A2A57C0D79F717C0B /* HTTPHandler.swift */, + 0132DD6BC218430E4129462F65D66870 /* NativeEngine.swift */, + 61FE945A3F79F87A400FA85D992A8ED3 /* Security.swift */, + 364CDE104597AA95F84250D3D193B9F0 /* Server.swift */, + 1C881398D265BA12E076C400F85F6E31 /* StringHTTPHandler.swift */, + 85784B520B446895DEFF6C56E422E600 /* TCPTransport.swift */, + DF29040AF8733F5855A98D1E891A7A1E /* Transport.swift */, + 6C9A9DB3D00A80D8201500A3CB7DCDE5 /* WebSocket.swift */, + 3DF9237140607B2EAE74095538F1AF70 /* WebSocketServer.swift */, + 606F9261E693AC537944C7315B5E1246 /* WSCompression.swift */, + 8030BC39B02644EB1D64B8659592EB22 /* WSEngine.swift */, + 2B122EA7F2359AE7F018CAF6D006420C /* Resources */, + E57C115E21BD9A809AC049B503E1B652 /* Support Files */, + ); + name = Starscream; + path = Starscream; + sourceTree = ""; + }; + C742DF3C28AFD0C3CBF906D7E54C7D0B /* Pods */ = { + isa = PBXGroup; + children = ( + F266AE5F8F9E83DF2AD144644C3F787F /* Alamofire */, + D2C8EFED581E790CBCDC740CD1BBB2E6 /* KeychainAccess */, + B563E0D9BFFA897F763FDB29177769CC /* Starscream */, + ); + name = Pods; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */, + C742DF3C28AFD0C3CBF906D7E54C7D0B /* Pods */, + 7716805D89C36863EA0F1C5234A4D455 /* Products */, + 2BE19BF74AA5AD60B65C95102226EEF8 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D2C8EFED581E790CBCDC740CD1BBB2E6 /* KeychainAccess */ = { + isa = PBXGroup; + children = ( + 173489F92BAFC8AF0D2EF2E9DE661AA3 /* Keychain.swift */, + A122B93FE0EB1CC338612A135F871414 /* Support Files */, + ); + name = KeychainAccess; + path = KeychainAccess; + sourceTree = ""; + }; + E57C115E21BD9A809AC049B503E1B652 /* Support Files */ = { + isa = PBXGroup; + children = ( + B5674BD39D5A9BC5F521BFEB5AACA86E /* ResourceBundle-Starscream_Privacy-Starscream-Info.plist */, + 6F37FA0BDFD9023B4286F6C3A0A7AA39 /* Starscream.modulemap */, + FF81CF9512C7A5C10A53FCB0FF24A688 /* Starscream-dummy.m */, + FA1B75E9FE949B48D7CF65947B8BD790 /* Starscream-Info.plist */, + 077D03A597F60886A9E36B659F1ECA0B /* Starscream-prefix.pch */, + 19E3FE8288594C25E977930430174E76 /* Starscream-umbrella.h */, + A05A201DFC60A9BCBFF0934149438CAB /* Starscream.debug.xcconfig */, + 0972289B7EBCD71C4C1D5116EE3AACE6 /* Starscream.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Starscream"; + sourceTree = ""; + }; + E5B9A9EF2B20D59EB52F695D6D7F759D /* iOS */ = { + isa = PBXGroup; + children = ( + 5F5F67A24F91CF1ED218D2C72FDF144D /* CFNetwork.framework */, + 574581962A29DE4FA03BAD8D30FD58FC /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + ED2C4262C806085AFB88ADA4844F2C5C /* Pods-asyncgate_iOS */ = { + isa = PBXGroup; + children = ( + D86737F840838377AE55ABFF0838BC83 /* Pods-asyncgate_iOS.modulemap */, + CB6A77E51C39767E8154B4C21CF06293 /* Pods-asyncgate_iOS-acknowledgements.markdown */, + 9D83CEA5D88CA135DCC74A80FFA27C34 /* Pods-asyncgate_iOS-acknowledgements.plist */, + 6072F76F5C28A1115E013DA132C1B0F9 /* Pods-asyncgate_iOS-dummy.m */, + 0856604687003A2D412CAA80F7A8F686 /* Pods-asyncgate_iOS-frameworks.sh */, + 4ACD385E36B1CECC40D2D0B2D7932DCF /* Pods-asyncgate_iOS-Info.plist */, + 326C2A2838401B445A4346952D0855D0 /* Pods-asyncgate_iOS-umbrella.h */, + 798D97427BF035F3B49BBBBA845394DF /* Pods-asyncgate_iOS.debug.xcconfig */, + 719D50C81202E0C48D1CE45BC55F6156 /* Pods-asyncgate_iOS.release.xcconfig */, + ); + name = "Pods-asyncgate_iOS"; + path = "Target Support Files/Pods-asyncgate_iOS"; + sourceTree = ""; + }; + F266AE5F8F9E83DF2AD144644C3F787F /* Alamofire */ = { + isa = PBXGroup; + children = ( + 11519F969AC6A764F3FCA32D9F510165 /* AFError.swift */, + EA82622E9B6B642D8590A735D2FB851E /* Alamofire.swift */, + 33929497CE40CE557C84DC9D0D428DC8 /* AlamofireExtended.swift */, + D0E44801C91E1BE06FE49B0DBB45B611 /* AuthenticationInterceptor.swift */, + EAD7866CF0C10DE9FE698015834F1687 /* CachedResponseHandler.swift */, + 7102AD45CADE73C3525FBB8FA577FC3A /* Combine.swift */, + 9C18DD7A782E9D6D2D8A5A1DB6112634 /* Concurrency.swift */, + E4B46F59305E50B334650CAB878B972F /* DataRequest.swift */, + F3EE7229C9B0BC3C7947D5B93F157181 /* DataStreamRequest.swift */, + 14CF6ABDCF4456D79AFC88BE1D70741D /* DispatchQueue+Alamofire.swift */, + 3FF1969E881F4F66EA0D543A6BC69C67 /* DownloadRequest.swift */, + FC98A8215F9B5ECC4F661CA10787E827 /* EventMonitor.swift */, + 8F8B98826CB69D713D1B7EC87D001CD3 /* HTTPHeaders.swift */, + 3D95261CDCE4725F0494D77CEBB11BFD /* HTTPMethod.swift */, + C29E4BA2F835BA91E8628C453EC2F442 /* MultipartFormData.swift */, + 3DB2F08D4E65A2892A448E6443982A56 /* MultipartUpload.swift */, + CF6F94774D0D1EDA63FE4BD5DDFC146F /* NetworkReachabilityManager.swift */, + AFEF43FFBEFC92E576A2E5200BDE8C60 /* Notifications.swift */, + 3EDF105515A2E151D36F33D2250A834E /* OperationQueue+Alamofire.swift */, + BCA05E2A928D7750E0E6A7C071A2AD1E /* ParameterEncoder.swift */, + E74677F64BF1B0ABEE7A723EE59B7090 /* ParameterEncoding.swift */, + 56501B182412015B15854FE4EE009688 /* Protected.swift */, + F04FDCB40B6ED3C4357E3C78095985EE /* RedirectHandler.swift */, + FB9D381B829BDAC063D7E5DC775AD8C2 /* Request.swift */, + D318EE975524358AF97E39A8BFDFEB53 /* RequestCompression.swift */, + 6CF178A4B8DD96FF0E6A97B9E2C17B88 /* RequestInterceptor.swift */, + E23AEA5C9C8F37B3F64A7967466DEC37 /* RequestTaskMap.swift */, + 4FFABBC947F0F16AA011FF708C7E6502 /* Response.swift */, + 423128D2D8E40498722E267B615BB555 /* ResponseSerialization.swift */, + 7B372A845370D74FAE7284A89A6A0A19 /* Result+Alamofire.swift */, + D78391C81FB7A4E5B9A8CEC48868A925 /* RetryPolicy.swift */, + 3ED337B10DDA1941E08A3EA9ACCA1594 /* ServerTrustEvaluation.swift */, + 3A3930860F22B0DB2936489D3F682149 /* Session.swift */, + F537DDC82AA2136183F14734E6E333AF /* SessionDelegate.swift */, + F4771B27E03FD30154D6D0BCE2F00370 /* StringEncoding+Alamofire.swift */, + 8B7D4E16F72F7A5F4E7BAAC6D9914466 /* UploadRequest.swift */, + 32C129E4D16FF427E2AF39FD3B4FF4F0 /* URLConvertible+URLRequestConvertible.swift */, + 2EF6C82979E6D0782061E25E13C86AA9 /* URLEncodedFormEncoder.swift */, + C190A553320271C09E65CF3B99386D52 /* URLRequest+Alamofire.swift */, + 8400561C73BEB7F341F42652BC804BB2 /* URLSessionConfiguration+Alamofire.swift */, + 2D2541F01CEDC5D06D49EFF897D9CFFD /* Validation.swift */, + 977A6AD416738296B5DBB41F6DB9E5ED /* WebSocketRequest.swift */, + 5561A6DADA7F283FFD95E05BE8917C18 /* Resources */, + 60DC20A010854D532D76C961D8A37CEC /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 10892642A012C1980F06E64C90045330 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 20D8D2C1254B0DCF38CD4E3F0997E52A /* KeychainAccess-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1A1A81122263D5D8BE4DF5082CACE201 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 47FBA86C15EC8060331926C9A8D54BB1 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 767C5D71D2E39582E37F0B75DA308182 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 422D446AE9FFA55420A3F5286C016FB9 /* Pods-asyncgate_iOS-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 78B67249DC2C8ED8165396FC185D87A2 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 72F899A56B333FDAA44453342ED56E7F /* Pods-asyncgate_iOSTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BD1758D504022BC643891E205C5F8B52 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 524EA7DEF50C0D0FDB5A171360D97946 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ECE343FFAC5CCBBEDC781E4FA3601A1A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 132F780E43E12D7EDADAA2AD29A012AA /* Starscream-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 03F6734F0758DC338768C753B543BAB5 /* Pods-asyncgate_iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9BB0730B26A8A389B591B55E0E48BA28 /* Build configuration list for PBXNativeTarget "Pods-asyncgate_iOS" */; + buildPhases = ( + 767C5D71D2E39582E37F0B75DA308182 /* Headers */, + 97479201228F47ADAB1FF8272C175C3A /* Sources */, + 90658D007F7A05D088B40B4307CCBFF6 /* Frameworks */, + 56C53BFB9F3E18EAB4749AE7E3E2B61F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + C106F8AC675DEB2127E1CEA27B91A259 /* PBXTargetDependency */, + CB263D12F8DC9E2603753948FE8906F6 /* PBXTargetDependency */, + 3CA414CF736194EAC83E84A52BB4E667 /* PBXTargetDependency */, + ); + name = "Pods-asyncgate_iOS"; + productName = Pods_asyncgate_iOS; + productReference = 37259FFD60EEBA0F4DC83BE9DA044C74 /* Pods-asyncgate_iOS */; + productType = "com.apple.product-type.framework"; + }; + 21C193E766AFE9E6B1D31363951D8FC4 /* Pods-asyncgate_iOSTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5352AC4E903ADEC2D012D33B71B30BAE /* Build configuration list for PBXNativeTarget "Pods-asyncgate_iOSTests" */; + buildPhases = ( + 78B67249DC2C8ED8165396FC185D87A2 /* Headers */, + 3971449F18F3133392A80926F3F1AFF8 /* Sources */, + 58F78AC8483C8DCBD093C04D1D38E5C3 /* Frameworks */, + 68EFBC4DC1926B0F2351D0DED3E0605A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + AD7A0CA4A6274CE2F785D619745F3214 /* PBXTargetDependency */, + ); + name = "Pods-asyncgate_iOSTests"; + productName = Pods_asyncgate_iOSTests; + productReference = B79946132F049EEE980603C1192A34CD /* Pods-asyncgate_iOSTests */; + productType = "com.apple.product-type.framework"; + }; + 615C831BCE925ED486B225B87E44926D /* KeychainAccess */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2A2567D919C3503794C3AC0A279285A8 /* Build configuration list for PBXNativeTarget "KeychainAccess" */; + buildPhases = ( + 10892642A012C1980F06E64C90045330 /* Headers */, + 383A7258ACDC1E628E08F47AE17EB27D /* Sources */, + 0FD546A70F9E3AB529847CBF744F37C1 /* Frameworks */, + 724F39F37AFE67C307AD4EDA853B673E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = KeychainAccess; + productName = KeychainAccess; + productReference = E8EE7F078656FABB8F6821D10FF994BB /* KeychainAccess */; + productType = "com.apple.product-type.framework"; + }; + 771210E06FA095D070EFB58429312B8F /* Starscream-Starscream_Privacy */ = { + isa = PBXNativeTarget; + buildConfigurationList = F45D6DED2027DE69A1E8AC5EFE45574E /* Build configuration list for PBXNativeTarget "Starscream-Starscream_Privacy" */; + buildPhases = ( + 80837EBEAFA3E3E4856D19CC057B10A1 /* Sources */, + 0A30CA377B146419DD5D6AB08A9F5677 /* Frameworks */, + 7EF9FE4206F73C6B259A0A73124ED843 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Starscream-Starscream_Privacy"; + productName = Starscream_Privacy; + productReference = 90DF440CB562947BB255E9A3E9B29568 /* Starscream-Starscream_Privacy */; + productType = "com.apple.product-type.bundle"; + }; + 976126A1CE06DC6E162563800E1BDF14 /* Alamofire-Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = B10EA59F4E63BFE77917DBA522CACCA1 /* Build configuration list for PBXNativeTarget "Alamofire-Alamofire" */; + buildPhases = ( + 42932597A76159DBD0F017FB03E877B8 /* Sources */, + E15ED9E83CA09E12DF09B9452AB473EA /* Frameworks */, + 73792AA5D179CB0048F5F3927E2E70C5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Alamofire-Alamofire"; + productName = Alamofire; + productReference = 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */; + productType = "com.apple.product-type.bundle"; + }; + 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */ = { + isa = PBXNativeTarget; + buildConfigurationList = E6AECD1528B47B8305DD9F79E68D882B /* Build configuration list for PBXNativeTarget "Starscream" */; + buildPhases = ( + ECE343FFAC5CCBBEDC781E4FA3601A1A /* Headers */, + 09AEF5B1B05F3FC55FE5B4A9E025B206 /* Sources */, + 92EF5BBC3EFCFE60910B74638A1755FC /* Frameworks */, + 7AC24AF3018BC9C6093C0062FFA1416B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + C6DAC6B7A90AA8336210428F3B199442 /* PBXTargetDependency */, + ); + name = Starscream; + productName = Starscream; + productReference = 891B2270823847ED23F2ECFC28F935EC /* Starscream */; + productType = "com.apple.product-type.framework"; + }; + B31EAA3353BBBF31C938DFFD0A21FDAD /* Pods-asyncgate_iOS-asyncgate_iOSUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 46FA134443F544D8F71AC0D749F870F6 /* Build configuration list for PBXNativeTarget "Pods-asyncgate_iOS-asyncgate_iOSUITests" */; + buildPhases = ( + BD1758D504022BC643891E205C5F8B52 /* Headers */, + 9F227B40BF73D8B87E42991BD32B0A1F /* Sources */, + 8A09E3EB579D177793C529FC8051283A /* Frameworks */, + 5E0149B77907E04F79DDCEA2705B1777 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + D4F1A2DD4F29C70B7F9A505C1C271C90 /* PBXTargetDependency */, + 2CC0DE0E8664841EC8DC9A0FC4FA7431 /* PBXTargetDependency */, + 374E64A5D19FA53B48B3AC20DBDF2A0E /* PBXTargetDependency */, + ); + name = "Pods-asyncgate_iOS-asyncgate_iOSUITests"; + productName = Pods_asyncgate_iOS_asyncgate_iOSUITests; + productReference = 58A58C6CAF3A48C08FE8CA3C103F413B /* Pods-asyncgate_iOS-asyncgate_iOSUITests */; + productType = "com.apple.product-type.framework"; + }; + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 63ECDE2C79B8ED0684A10A9659C0EAFB /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 1A1A81122263D5D8BE4DF5082CACE201 /* Headers */, + 29A404AEBCB50A3F5BB3DC929EC993B2 /* Sources */, + 88CA6FBB7F7F430F2FBA288A454E4858 /* Frameworks */, + 60BE915674C4C0EFFFEAB37F6462BB46 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 07B0CB45294376657891BD8FA6746933 /* PBXTargetDependency */, + ); + name = Alamofire; + productName = Alamofire; + productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 16.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + minimizedProjectReferenceProxies = 0; + preferredProjectObjectVersion = 77; + productRefGroup = 7716805D89C36863EA0F1C5234A4D455 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + 976126A1CE06DC6E162563800E1BDF14 /* Alamofire-Alamofire */, + 615C831BCE925ED486B225B87E44926D /* KeychainAccess */, + 03F6734F0758DC338768C753B543BAB5 /* Pods-asyncgate_iOS */, + B31EAA3353BBBF31C938DFFD0A21FDAD /* Pods-asyncgate_iOS-asyncgate_iOSUITests */, + 21C193E766AFE9E6B1D31363951D8FC4 /* Pods-asyncgate_iOSTests */, + 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */, + 771210E06FA095D070EFB58429312B8F /* Starscream-Starscream_Privacy */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 56C53BFB9F3E18EAB4749AE7E3E2B61F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5E0149B77907E04F79DDCEA2705B1777 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 60BE915674C4C0EFFFEAB37F6462BB46 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5CD127F101529C336A07D45CE1106A54 /* Alamofire-Alamofire in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 68EFBC4DC1926B0F2351D0DED3E0605A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 724F39F37AFE67C307AD4EDA853B673E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 73792AA5D179CB0048F5F3927E2E70C5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8D3627F773DB54051EAC3F81DB267696 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7AC24AF3018BC9C6093C0062FFA1416B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4AC4E87A3CB2C676949C33E78E64BA93 /* Starscream-Starscream_Privacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7EF9FE4206F73C6B259A0A73124ED843 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FFA11505FB1BAD600F090D2646DCB86D /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 09AEF5B1B05F3FC55FE5B4A9E025B206 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D6102474025E613F9F8D98EFB708CEC6 /* Compression.swift in Sources */, + C27AC4CF7DC6EEF22BE5CF742C34BF1B /* Data+Extensions.swift in Sources */, + C6E71C71E4833389B33C0199196A5E13 /* Engine.swift in Sources */, + 3CFB26DFC9AC8164AEC49CD75577C535 /* FoundationHTTPHandler.swift in Sources */, + 1E3E2F1DF5E1C8D27447FCF94D111167 /* FoundationHTTPServerHandler.swift in Sources */, + 69111C8CB8268AAD6DD50A84B22944EE /* FoundationSecurity.swift in Sources */, + 43FE097FBE9B5568B702545F99072CFB /* FoundationTransport.swift in Sources */, + 4816EF150D924B1987414B356C7AB77E /* FrameCollector.swift in Sources */, + 21A5D9EBAC5FED24E7FE77087A33B645 /* Framer.swift in Sources */, + DC2BE589B1C5A65E08CA6D9D7C319E17 /* HTTPHandler.swift in Sources */, + B1EDE680CB2182C3B4900E1945783F9B /* NativeEngine.swift in Sources */, + 31E77D0FAC67DCFEE1F3173E441C67D6 /* Security.swift in Sources */, + 4C5BB45AFA17EE49908EEE4B8163EF76 /* Server.swift in Sources */, + A017485C3C202ADD0A059DFCCDA5D14D /* Starscream-dummy.m in Sources */, + D8D51B6D3248D9CEA719A66A2ABC7319 /* StringHTTPHandler.swift in Sources */, + FD8A6F93705C4B172C32D52D17B2B5DC /* TCPTransport.swift in Sources */, + BECD28904453E5C00C66B51D37CAD433 /* Transport.swift in Sources */, + 8A472901A6A0E2D7231E376832198241 /* WebSocket.swift in Sources */, + 07B83A2E6FCF9A05339E6974FC9D3D32 /* WebSocketServer.swift in Sources */, + 55DAC2E8DC333019B6C1D70EC91B0A22 /* WSCompression.swift in Sources */, + 85F55FDAED763889D7DADACE5DC5C567 /* WSEngine.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 29A404AEBCB50A3F5BB3DC929EC993B2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7A232A8D5C0D06F3CE373E1B46422118 /* AFError.swift in Sources */, + 9C89110A7C655E5C39B3135E9020CBF7 /* Alamofire.swift in Sources */, + 4D9E593DECA015D410984C771CCFDD12 /* Alamofire-dummy.m in Sources */, + 8904ED8DEB77CA657A4EED2F86EB961A /* AlamofireExtended.swift in Sources */, + C6E542DE6D61F7CD41340049F2D8FFDE /* AuthenticationInterceptor.swift in Sources */, + CECA8162BFE05143ECD1DE4225B82B9C /* CachedResponseHandler.swift in Sources */, + 8DF169B3ADBCBA100BE5D2CA34EDC31A /* Combine.swift in Sources */, + D5A2B190C4A0490CAACAD3C4FC76531D /* Concurrency.swift in Sources */, + B3EC2DE8A5B6FAF5ED30071E4A3D9BE7 /* DataRequest.swift in Sources */, + 7933EDD15F245D28BE5D99E203E9BD1F /* DataStreamRequest.swift in Sources */, + 20988E7C942B437989E7A7BF1F8E9136 /* DispatchQueue+Alamofire.swift in Sources */, + 849FF90CD07B763B0D53DD4656BDED61 /* DownloadRequest.swift in Sources */, + 5ABDF47FC0D60B701B5A8E767DC1314F /* EventMonitor.swift in Sources */, + CFDB27ACA68B4C18C6DC1E51998D7623 /* HTTPHeaders.swift in Sources */, + A8437EFD962B3A3F812B756C76ADD87B /* HTTPMethod.swift in Sources */, + 9CE2B0DEBE0178D7BCA89AD9A7F0BFDF /* MultipartFormData.swift in Sources */, + B23B20F1C3E3BA41870F9137074F1AEE /* MultipartUpload.swift in Sources */, + EDD1F4A31BC9F0816F25B14E0B4B89B5 /* NetworkReachabilityManager.swift in Sources */, + 54A45AF20BFF99BA20B15AF09AC4901C /* Notifications.swift in Sources */, + A698A792F293BA997FE75C70CD18B022 /* OperationQueue+Alamofire.swift in Sources */, + 3BCAE7843A2516EBA64768CC0CD79988 /* ParameterEncoder.swift in Sources */, + 8F4AC5455CDD202655025DE431360AEE /* ParameterEncoding.swift in Sources */, + 00D69AD872EF460A7A9715B345A1C31B /* Protected.swift in Sources */, + C48A9E2CABF2ABD7D954BC1FBB6D3C77 /* RedirectHandler.swift in Sources */, + 2558B9A09FEC5710F7D00DD5E3E053C5 /* Request.swift in Sources */, + 074387D1012BC0F5C90B358F27A1331F /* RequestCompression.swift in Sources */, + DC116AC0C3BC808A198B9C1704FA8C84 /* RequestInterceptor.swift in Sources */, + 083B0B494C5F6B69924BB36E3850D23E /* RequestTaskMap.swift in Sources */, + ECBB9D041E2943036EFF0AD5B7E63B4C /* Response.swift in Sources */, + 66F024DCBE9C5AE50FD48FE6876D5DEB /* ResponseSerialization.swift in Sources */, + 0DC813E62FCEF6C6C3009180D7790BFE /* Result+Alamofire.swift in Sources */, + BACE03596343C2C83670A3996164D2F0 /* RetryPolicy.swift in Sources */, + D2854184492AB0652C029448967FE129 /* ServerTrustEvaluation.swift in Sources */, + E4BEE8283802F8F8B17F1A1BBBD3CDE4 /* Session.swift in Sources */, + CDF42ED6AF2C0252840DF2A724375380 /* SessionDelegate.swift in Sources */, + 9D46306826317C2783B0A8255691E035 /* StringEncoding+Alamofire.swift in Sources */, + C437FA9AF753C87C55F0849F7E1E176E /* UploadRequest.swift in Sources */, + 6D3071F804219E6A520372754BA9F09C /* URLConvertible+URLRequestConvertible.swift in Sources */, + 1313426F64905A867293DAA192DDAB28 /* URLEncodedFormEncoder.swift in Sources */, + A9B0233F2C7CD6365526CA2178F9215F /* URLRequest+Alamofire.swift in Sources */, + 39D449220194AE1CD884069FBF6F735D /* URLSessionConfiguration+Alamofire.swift in Sources */, + 5746320BBB67E457AF4C4EE5A2D32799 /* Validation.swift in Sources */, + FAB703884AC7E3E527AB50FB9001276B /* WebSocketRequest.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 383A7258ACDC1E628E08F47AE17EB27D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 453CB5E8B81F432DBD99BD674E41F79F /* Keychain.swift in Sources */, + E4180B507E0C530F0D7CAEFA1FAEA06F /* KeychainAccess-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3971449F18F3133392A80926F3F1AFF8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A8960279BB85041C12ADB3A704754B7F /* Pods-asyncgate_iOSTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 42932597A76159DBD0F017FB03E877B8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 80837EBEAFA3E3E4856D19CC057B10A1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97479201228F47ADAB1FF8272C175C3A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9815712350A1C2F91A5CFD84FDD9B391 /* Pods-asyncgate_iOS-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9F227B40BF73D8B87E42991BD32B0A1F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B2593CE3DA0E29BD821FF0C0860447B4 /* Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 07B0CB45294376657891BD8FA6746933 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Alamofire-Alamofire"; + target = 976126A1CE06DC6E162563800E1BDF14 /* Alamofire-Alamofire */; + targetProxy = A9E290F5AC68E340303DC0860B4EBB51 /* PBXContainerItemProxy */; + }; + 2CC0DE0E8664841EC8DC9A0FC4FA7431 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = KeychainAccess; + target = 615C831BCE925ED486B225B87E44926D /* KeychainAccess */; + targetProxy = 2D8C78DCB11EC8D20D81661A874CF54A /* PBXContainerItemProxy */; + }; + 374E64A5D19FA53B48B3AC20DBDF2A0E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = B1D08E7283ABA142CF92D0B04EA7AED5 /* PBXContainerItemProxy */; + }; + 3CA414CF736194EAC83E84A52BB4E667 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = 6DD1B3E04383EDDFC1798398CC60D01E /* PBXContainerItemProxy */; + }; + AD7A0CA4A6274CE2F785D619745F3214 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-asyncgate_iOS"; + target = 03F6734F0758DC338768C753B543BAB5 /* Pods-asyncgate_iOS */; + targetProxy = 093776EEE352BBC2B73D6A22F0FD40A7 /* PBXContainerItemProxy */; + }; + C106F8AC675DEB2127E1CEA27B91A259 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 1260E37E9610D031695C30D81FAAC442 /* PBXContainerItemProxy */; + }; + C6DAC6B7A90AA8336210428F3B199442 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Starscream-Starscream_Privacy"; + target = 771210E06FA095D070EFB58429312B8F /* Starscream-Starscream_Privacy */; + targetProxy = D9E1591248FD4E00439C8F8C71B51FF9 /* PBXContainerItemProxy */; + }; + CB263D12F8DC9E2603753948FE8906F6 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = KeychainAccess; + target = 615C831BCE925ED486B225B87E44926D /* KeychainAccess */; + targetProxy = A47C07C96A5D7FFEC6DAF2ACDBEF7311 /* PBXContainerItemProxy */; + }; + D4F1A2DD4F29C70B7F9A505C1C271C90 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 933191256C2E9E2BB3B96DC7B7AA47FA /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 0422C03EEEC84A1D8DDA744118C1A98D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 719D50C81202E0C48D1CE45BC55F6156 /* Pods-asyncgate_iOS.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 0C0ABEF0BF52F8CD37D8E0B18541A4D5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 096AD6DD2651B388B8AD33D52C0F1E3B /* Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 14D01375232210B6630DD295C8409859 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A05A201DFC60A9BCBFF0934149438CAB /* Starscream.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 30F13CA2E454A0FA93A0E97A14FBB065 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 129210C02226E114925FA3984D355E82 /* Alamofire.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Alamofire"; + IBSC_MODULE = Alamofire; + INFOPLIST_FILE = "Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + 3321B8226DB23E63F3D21AA7E21C3FD3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F9F14DB081BEE05C035DA0CE6D2DAF3D /* KeychainAccess.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/KeychainAccess/KeychainAccess-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/KeychainAccess/KeychainAccess-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/KeychainAccess/KeychainAccess.modulemap"; + PRODUCT_MODULE_NAME = KeychainAccess; + PRODUCT_NAME = KeychainAccess; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 40122AF89D66D2C986B44E4FE72AA7CC /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9D172E58771203048A637351B914E372 /* KeychainAccess.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/KeychainAccess/KeychainAccess-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/KeychainAccess/KeychainAccess-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/KeychainAccess/KeychainAccess.modulemap"; + PRODUCT_MODULE_NAME = KeychainAccess; + PRODUCT_NAME = KeychainAccess; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 43E6F219681645AA6A1DC48E87B56284 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7B00AA45E5870C31404FBE7FCEC794BD /* Alamofire.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + SWIFT_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 4C6450248165267FCCE1E931FDCC492D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 129210C02226E114925FA3984D355E82 /* Alamofire.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + SWIFT_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 6E80DE114F2BEF7B64DEE6743AA39035 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A05A201DFC60A9BCBFF0934149438CAB /* Starscream.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Starscream"; + IBSC_MODULE = Starscream; + INFOPLIST_FILE = "Target Support Files/Starscream/ResourceBundle-Starscream_Privacy-Starscream-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = Starscream_Privacy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + 7375B2701A79F5A1159912C774731F29 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 798D97427BF035F3B49BBBBA845394DF /* Pods-asyncgate_iOS.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 79BB26DDE76ED8A15C232FA991A23DE0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1FC42E2DD8BE25E03DE4AFB41D4C4BF5 /* Pods-asyncgate_iOSTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 81A7EC4E7692640204A9F338F13A2E65 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0972289B7EBCD71C4C1D5116EE3AACE6 /* Starscream.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Starscream"; + IBSC_MODULE = Starscream; + INFOPLIST_FILE = "Target Support Files/Starscream/ResourceBundle-Starscream_Privacy-Starscream-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = Starscream_Privacy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + 8C5C6FF0CD9EA85550438BB329FEA98C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3B97412F84414FAB3B5F5166CABF7EEE /* Pods-asyncgate_iOSTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 8C9963745FD01B6B3EF95F9CE58D9F10 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 944660B121E7764AE8A185470FE5185C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3756254E49A40FC70F7D70660FE613CE /* Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + B342F58912E5586D063AA0F91FF3EE36 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0972289B7EBCD71C4C1D5116EE3AACE6 /* Starscream.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + B9F3557045385CA606F5AF548D58B58A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + E290BAE161A3F098CB5478D8C9519CF4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7B00AA45E5870C31404FBE7FCEC794BD /* Alamofire.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Alamofire"; + IBSC_MODULE = Alamofire; + INFOPLIST_FILE = "Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2A2567D919C3503794C3AC0A279285A8 /* Build configuration list for PBXNativeTarget "KeychainAccess" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 40122AF89D66D2C986B44E4FE72AA7CC /* Debug */, + 3321B8226DB23E63F3D21AA7E21C3FD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 46FA134443F544D8F71AC0D749F870F6 /* Build configuration list for PBXNativeTarget "Pods-asyncgate_iOS-asyncgate_iOSUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 944660B121E7764AE8A185470FE5185C /* Debug */, + 0C0ABEF0BF52F8CD37D8E0B18541A4D5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8C9963745FD01B6B3EF95F9CE58D9F10 /* Debug */, + B9F3557045385CA606F5AF548D58B58A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5352AC4E903ADEC2D012D33B71B30BAE /* Build configuration list for PBXNativeTarget "Pods-asyncgate_iOSTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 79BB26DDE76ED8A15C232FA991A23DE0 /* Debug */, + 8C5C6FF0CD9EA85550438BB329FEA98C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 63ECDE2C79B8ED0684A10A9659C0EAFB /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 43E6F219681645AA6A1DC48E87B56284 /* Debug */, + 4C6450248165267FCCE1E931FDCC492D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9BB0730B26A8A389B591B55E0E48BA28 /* Build configuration list for PBXNativeTarget "Pods-asyncgate_iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7375B2701A79F5A1159912C774731F29 /* Debug */, + 0422C03EEEC84A1D8DDA744118C1A98D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B10EA59F4E63BFE77917DBA522CACCA1 /* Build configuration list for PBXNativeTarget "Alamofire-Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E290BAE161A3F098CB5478D8C9519CF4 /* Debug */, + 30F13CA2E454A0FA93A0E97A14FBB065 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E6AECD1528B47B8305DD9F79E68D882B /* Build configuration list for PBXNativeTarget "Starscream" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 14D01375232210B6630DD295C8409859 /* Debug */, + B342F58912E5586D063AA0F91FF3EE36 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F45D6DED2027DE69A1E8AC5EFE45574E /* Build configuration list for PBXNativeTarget "Starscream-Starscream_Privacy" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6E80DE114F2BEF7B64DEE6743AA39035 /* Debug */, + 81A7EC4E7692640204A9F338F13A2E65 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Alamofire-Alamofire.xcscheme b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Alamofire-Alamofire.xcscheme new file mode 100644 index 00000000..ac09e969 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Alamofire-Alamofire.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Alamofire.xcscheme b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 00000000..93452edc --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/KeychainAccess.xcscheme b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/KeychainAccess.xcscheme new file mode 100644 index 00000000..a3cf744c --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/KeychainAccess.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOS-asyncgate_iOSUITests.xcscheme b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOS-asyncgate_iOSUITests.xcscheme new file mode 100644 index 00000000..9ecd3570 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOS-asyncgate_iOSUITests.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOS.xcscheme b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOS.xcscheme new file mode 100644 index 00000000..e8a83968 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOS.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOSTests.xcscheme b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOSTests.xcscheme new file mode 100644 index 00000000..7e551bc8 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/Pods-asyncgate_iOSTests.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000..a1081a4a --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Pods.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,67 @@ + + + + + SchemeUserState + + Alamofire-Alamofire.xcscheme + + isShown + + orderHint + 1 + + Alamofire.xcscheme + + isShown + + orderHint + 0 + + KeychainAccess.xcscheme + + isShown + + orderHint + 2 + + Pods-asyncgate_iOS-asyncgate_iOSUITests.xcscheme + + isShown + + orderHint + 4 + + Pods-asyncgate_iOS.xcscheme + + isShown + + orderHint + 3 + + Pods-asyncgate_iOSTests.xcscheme + + isShown + + orderHint + 5 + + Starscream-Starscream_Privacy.xcscheme + + isShown + + orderHint + 7 + + Starscream.xcscheme + + isShown + + orderHint + 6 + + + SuppressBuildableAutocreation + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-Info.plist new file mode 100644 index 00000000..37be073d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.10.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 00000000..a6c45942 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 00000000..beb2a244 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 00000000..00014e3c --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig new file mode 100644 index 00000000..dbfd4d14 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 00000000..d1f125fa --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig new file mode 100644 index 00000000..dbfd4d14 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist new file mode 100644 index 00000000..83b8ed3d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + BNDL + CFBundleShortVersionString + 5.10.2 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-Info.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-Info.plist new file mode 100644 index 00000000..370c557a --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.2.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-dummy.m b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-dummy.m new file mode 100644 index 00000000..b1cd3bfc --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_KeychainAccess : NSObject +@end +@implementation PodsDummy_KeychainAccess +@end diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-prefix.pch b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-prefix.pch new file mode 100644 index 00000000..beb2a244 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-umbrella.h b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-umbrella.h new file mode 100644 index 00000000..62ce5de4 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double KeychainAccessVersionNumber; +FOUNDATION_EXPORT const unsigned char KeychainAccessVersionString[]; + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.debug.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.debug.xcconfig new file mode 100644 index 00000000..716bc86b --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/KeychainAccess +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.modulemap b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.modulemap new file mode 100644 index 00000000..f26e6b16 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.modulemap @@ -0,0 +1,6 @@ +framework module KeychainAccess { + umbrella header "KeychainAccess-umbrella.h" + + export * + module * { export * } +} diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.release.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.release.xcconfig new file mode 100644 index 00000000..716bc86b --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/KeychainAccess/KeychainAccess.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/KeychainAccess +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist new file mode 100644 index 00000000..19cf209d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.markdown b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.markdown new file mode 100644 index 00000000..67caae8d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.markdown @@ -0,0 +1,231 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## KeychainAccess + +The MIT License (MIT) + +Copyright (c) 2014 kishikawa katsumi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +## Starscream + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2023 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. +Generated by CocoaPods - https://cocoapods.org diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.plist new file mode 100644 index 00000000..abf2195f --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-acknowledgements.plist @@ -0,0 +1,275 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2014 kishikawa katsumi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + License + MIT + Title + KeychainAccess + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2023 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + License + Apache License, Version 2.0 + Title + Starscream + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m new file mode 100644 index 00000000..3ff0a1d7 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_asyncgate_iOS_asyncgate_iOSUITests : NSObject +@end +@implementation PodsDummy_Pods_asyncgate_iOS_asyncgate_iOSUITests +@end diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Debug-input-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 00000000..14ce0be7 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,4 @@ +${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Debug-output-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 00000000..f9bc9611 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,3 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/KeychainAccess.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Release-input-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Release-input-files.xcfilelist new file mode 100644 index 00000000..14ce0be7 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,4 @@ +${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Release-output-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Release-output-files.xcfilelist new file mode 100644 index 00000000..f9bc9611 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,3 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/KeychainAccess.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh new file mode 100755 index 00000000..a1eb0e5b --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh @@ -0,0 +1,190 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink -f "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h new file mode 100644 index 00000000..2874db3f --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_asyncgate_iOS_asyncgate_iOSUITestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_asyncgate_iOS_asyncgate_iOSUITestsVersionString[]; + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig new file mode 100644 index 00000000..8d7d722f --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig @@ -0,0 +1,16 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess/KeychainAccess.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift "$(PLATFORM_DIR)/Developer/Library/Frameworks" '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "KeychainAccess" -framework "Starscream" +OTHER_MODULE_VERIFIER_FLAGS = $(inherited) "-F${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "-F${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "-F${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap new file mode 100644 index 00000000..322d4ba4 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_asyncgate_iOS_asyncgate_iOSUITests { + umbrella header "Pods-asyncgate_iOS-asyncgate_iOSUITests-umbrella.h" + + export * + module * { export * } +} diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig new file mode 100644 index 00000000..8d7d722f --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig @@ -0,0 +1,16 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess/KeychainAccess.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift "$(PLATFORM_DIR)/Developer/Library/Frameworks" '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "KeychainAccess" -framework "Starscream" +OTHER_MODULE_VERIFIER_FLAGS = $(inherited) "-F${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "-F${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "-F${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-Info.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-Info.plist new file mode 100644 index 00000000..19cf209d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-acknowledgements.markdown b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-acknowledgements.markdown new file mode 100644 index 00000000..67caae8d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-acknowledgements.markdown @@ -0,0 +1,231 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## KeychainAccess + +The MIT License (MIT) + +Copyright (c) 2014 kishikawa katsumi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +## Starscream + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2023 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. +Generated by CocoaPods - https://cocoapods.org diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-acknowledgements.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-acknowledgements.plist new file mode 100644 index 00000000..abf2195f --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-acknowledgements.plist @@ -0,0 +1,275 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2014 kishikawa katsumi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + License + MIT + Title + KeychainAccess + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2023 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + License + Apache License, Version 2.0 + Title + Starscream + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-dummy.m b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-dummy.m new file mode 100644 index 00000000..0619db0f --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_asyncgate_iOS : NSObject +@end +@implementation PodsDummy_Pods_asyncgate_iOS +@end diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Debug-input-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 00000000..69bc6299 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,4 @@ +${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Debug-output-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 00000000..f9bc9611 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,3 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/KeychainAccess.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Release-input-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Release-input-files.xcfilelist new file mode 100644 index 00000000..69bc6299 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,4 @@ +${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Release-output-files.xcfilelist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Release-output-files.xcfilelist new file mode 100644 index 00000000..f9bc9611 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,3 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/KeychainAccess.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework \ No newline at end of file diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks.sh b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks.sh new file mode 100755 index 00000000..a1eb0e5b --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks.sh @@ -0,0 +1,190 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink -f "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-umbrella.h b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-umbrella.h new file mode 100644 index 00000000..15479043 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_asyncgate_iOSVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_asyncgate_iOSVersionString[]; + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.debug.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.debug.xcconfig new file mode 100644 index 00000000..94193d28 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.debug.xcconfig @@ -0,0 +1,16 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess/KeychainAccess.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "KeychainAccess" -framework "Starscream" +OTHER_MODULE_VERIFIER_FLAGS = $(inherited) "-F${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "-F${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "-F${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.modulemap b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.modulemap new file mode 100644 index 00000000..5d56a38e --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.modulemap @@ -0,0 +1,6 @@ +framework module Pods_asyncgate_iOS { + umbrella header "Pods-asyncgate_iOS-umbrella.h" + + export * + module * { export * } +} diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.release.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.release.xcconfig new file mode 100644 index 00000000..94193d28 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.release.xcconfig @@ -0,0 +1,16 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess/KeychainAccess.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "KeychainAccess" -framework "Starscream" +OTHER_MODULE_VERIFIER_FLAGS = $(inherited) "-F${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "-F${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "-F${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-Info.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-Info.plist new file mode 100644 index 00000000..19cf209d --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-acknowledgements.markdown b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-acknowledgements.markdown new file mode 100644 index 00000000..102af753 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-acknowledgements.plist b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-acknowledgements.plist new file mode 100644 index 00000000..7acbad1e --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-dummy.m b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-dummy.m new file mode 100644 index 00000000..bb3b6d44 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_asyncgate_iOSTests : NSObject +@end +@implementation PodsDummy_Pods_asyncgate_iOSTests +@end diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-umbrella.h b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-umbrella.h new file mode 100644 index 00000000..b2b7fc35 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_asyncgate_iOSTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_asyncgate_iOSTestsVersionString[]; + diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.debug.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.debug.xcconfig new file mode 100644 index 00000000..65d60b39 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.debug.xcconfig @@ -0,0 +1,11 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess/KeychainAccess.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "KeychainAccess" -framework "Starscream" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.modulemap b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.modulemap new file mode 100644 index 00000000..349042a9 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_asyncgate_iOSTests { + umbrella header "Pods-asyncgate_iOSTests-umbrella.h" + + export * + module * { export * } +} diff --git a/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.release.xcconfig b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.release.xcconfig new file mode 100644 index 00000000..65d60b39 --- /dev/null +++ b/src/ios/asyncgate_iOS/Pods/Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.release.xcconfig @@ -0,0 +1,11 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/KeychainAccess/KeychainAccess.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "KeychainAccess" -framework "Starscream" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/src/ios/asyncgate_iOS/Untitled.swift b/src/ios/asyncgate_iOS/Untitled.swift new file mode 100644 index 00000000..e69de29b diff --git a/src/ios/asyncgate_iOS/asyncgate-iOS-Info.plist b/src/ios/asyncgate_iOS/asyncgate-iOS-Info.plist index cf8c9292..1a6b1c66 100644 --- a/src/ios/asyncgate_iOS/asyncgate-iOS-Info.plist +++ b/src/ios/asyncgate_iOS/asyncgate-iOS-Info.plist @@ -14,5 +14,7 @@ Pretendard-SemiBold.otf Pretendard-Thin.otf + hostUrl + $(hostUrl) diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.pbxproj b/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.pbxproj index 2b0a2c1e..710e3677 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.pbxproj +++ b/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.pbxproj @@ -6,6 +6,12 @@ objectVersion = 77; objects = { +/* Begin PBXBuildFile section */ + 120C2F726ECDC78B341D40E7 /* Pods_asyncgate_iOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F66451FE3AC968ACC4C606FB /* Pods_asyncgate_iOS.framework */; }; + 5385074F7102DB571112FE8F /* Pods_asyncgate_iOSTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E4E8023B99B4A920514027A3 /* Pods_asyncgate_iOSTests.framework */; }; + E92BCCABD2CA3B2EB5E1BF2C /* Pods_asyncgate_iOS_asyncgate_iOSUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0DCFC22FB9EAA15A8994FBCD /* Pods_asyncgate_iOS_asyncgate_iOSUITests.framework */; }; +/* End PBXBuildFile section */ + /* Begin PBXContainerItemProxy section */ 42D3DCC42D51DA2A00BC3E8F /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; @@ -24,9 +30,19 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 07DBC075A9F63C6B8D460FC3 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig"; path = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig"; sourceTree = ""; }; + 0DCFC22FB9EAA15A8994FBCD /* Pods_asyncgate_iOS_asyncgate_iOSUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_asyncgate_iOS_asyncgate_iOSUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 1E721A53E3B7060D546CAC15 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig"; path = "Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig"; sourceTree = ""; }; + 263BFD25E29DDE3581181D4D /* Pods-asyncgate_iOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-asyncgate_iOS.release.xcconfig"; path = "Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.release.xcconfig"; sourceTree = ""; }; + 26810480EB084C8998408B13 /* Pods-asyncgate_iOSTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-asyncgate_iOSTests.release.xcconfig"; path = "Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.release.xcconfig"; sourceTree = ""; }; + 3EA7A6DE9C203FFF10094F1E /* Pods-asyncgate_iOSTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-asyncgate_iOSTests.debug.xcconfig"; path = "Target Support Files/Pods-asyncgate_iOSTests/Pods-asyncgate_iOSTests.debug.xcconfig"; sourceTree = ""; }; + 425A86F62D645D22009B4512 /* .xcconfig.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = .xcconfig.xcconfig; sourceTree = ""; }; 42D3DCB32D51DA2900BC3E8F /* asyncgate_iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = asyncgate_iOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; 42D3DCC32D51DA2A00BC3E8F /* asyncgate_iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = asyncgate_iOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 42D3DCCD2D51DA2A00BC3E8F /* asyncgate_iOSUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = asyncgate_iOSUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + BD81FEA621CDE1ACB91A518E /* Pods-asyncgate_iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-asyncgate_iOS.debug.xcconfig"; path = "Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS.debug.xcconfig"; sourceTree = ""; }; + E4E8023B99B4A920514027A3 /* Pods_asyncgate_iOSTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_asyncgate_iOSTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F66451FE3AC968ACC4C606FB /* Pods_asyncgate_iOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_asyncgate_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ @@ -52,6 +68,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 120C2F726ECDC78B341D40E7 /* Pods_asyncgate_iOS.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -59,6 +76,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 5385074F7102DB571112FE8F /* Pods_asyncgate_iOSTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -66,12 +84,21 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + E92BCCABD2CA3B2EB5E1BF2C /* Pods_asyncgate_iOS_asyncgate_iOSUITests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 425A87B12D66E071009B4512 /* Recovered References */ = { + isa = PBXGroup; + children = ( + 425A86F62D645D22009B4512 /* .xcconfig.xcconfig */, + ); + name = "Recovered References"; + sourceTree = ""; + }; 42D3DCAA2D51DA2900BC3E8F = { isa = PBXGroup; children = ( @@ -79,6 +106,9 @@ 42D3DCC62D51DA2A00BC3E8F /* asyncgate_iOSTests */, 42D3DCD02D51DA2A00BC3E8F /* asyncgate_iOSUITests */, 42D3DCB42D51DA2900BC3E8F /* Products */, + B2DC13B528D33F0397396DF4 /* Pods */, + D7EB2A16941B0EA27DEBAC32 /* Frameworks */, + 425A87B12D66E071009B4512 /* Recovered References */, ); sourceTree = ""; }; @@ -92,6 +122,29 @@ name = Products; sourceTree = ""; }; + B2DC13B528D33F0397396DF4 /* Pods */ = { + isa = PBXGroup; + children = ( + BD81FEA621CDE1ACB91A518E /* Pods-asyncgate_iOS.debug.xcconfig */, + 263BFD25E29DDE3581181D4D /* Pods-asyncgate_iOS.release.xcconfig */, + 1E721A53E3B7060D546CAC15 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig */, + 07DBC075A9F63C6B8D460FC3 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig */, + 3EA7A6DE9C203FFF10094F1E /* Pods-asyncgate_iOSTests.debug.xcconfig */, + 26810480EB084C8998408B13 /* Pods-asyncgate_iOSTests.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + D7EB2A16941B0EA27DEBAC32 /* Frameworks */ = { + isa = PBXGroup; + children = ( + F66451FE3AC968ACC4C606FB /* Pods_asyncgate_iOS.framework */, + 0DCFC22FB9EAA15A8994FBCD /* Pods_asyncgate_iOS_asyncgate_iOSUITests.framework */, + E4E8023B99B4A920514027A3 /* Pods_asyncgate_iOSTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -99,9 +152,11 @@ isa = PBXNativeTarget; buildConfigurationList = 42D3DCD72D51DA2A00BC3E8F /* Build configuration list for PBXNativeTarget "asyncgate_iOS" */; buildPhases = ( + 55623216BD408661BD8AF1E6 /* [CP] Check Pods Manifest.lock */, 42D3DCAF2D51DA2900BC3E8F /* Sources */, 42D3DCB02D51DA2900BC3E8F /* Frameworks */, 42D3DCB12D51DA2900BC3E8F /* Resources */, + 99A40181F2C12C1C395D8DFB /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -111,8 +166,6 @@ 42D3DCB52D51DA2900BC3E8F /* asyncgate_iOS */, ); name = asyncgate_iOS; - packageProductDependencies = ( - ); productName = asyncgate_iOS; productReference = 42D3DCB32D51DA2900BC3E8F /* asyncgate_iOS.app */; productType = "com.apple.product-type.application"; @@ -121,6 +174,7 @@ isa = PBXNativeTarget; buildConfigurationList = 42D3DCDA2D51DA2A00BC3E8F /* Build configuration list for PBXNativeTarget "asyncgate_iOSTests" */; buildPhases = ( + 121FBECF5C37504D221DBD66 /* [CP] Check Pods Manifest.lock */, 42D3DCBF2D51DA2A00BC3E8F /* Sources */, 42D3DCC02D51DA2A00BC3E8F /* Frameworks */, 42D3DCC12D51DA2A00BC3E8F /* Resources */, @@ -134,8 +188,6 @@ 42D3DCC62D51DA2A00BC3E8F /* asyncgate_iOSTests */, ); name = asyncgate_iOSTests; - packageProductDependencies = ( - ); productName = asyncgate_iOSTests; productReference = 42D3DCC32D51DA2A00BC3E8F /* asyncgate_iOSTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; @@ -144,9 +196,11 @@ isa = PBXNativeTarget; buildConfigurationList = 42D3DCDD2D51DA2A00BC3E8F /* Build configuration list for PBXNativeTarget "asyncgate_iOSUITests" */; buildPhases = ( + 466F2E6F2810D65E84402BCF /* [CP] Check Pods Manifest.lock */, 42D3DCC92D51DA2A00BC3E8F /* Sources */, 42D3DCCA2D51DA2A00BC3E8F /* Frameworks */, 42D3DCCB2D51DA2A00BC3E8F /* Resources */, + BF3276B03C5DBEEBAB8B01D0 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -157,8 +211,6 @@ 42D3DCD02D51DA2A00BC3E8F /* asyncgate_iOSUITests */, ); name = asyncgate_iOSUITests; - packageProductDependencies = ( - ); productName = asyncgate_iOSUITests; productReference = 42D3DCCD2D51DA2A00BC3E8F /* asyncgate_iOSUITests.xctest */; productType = "com.apple.product-type.bundle.ui-testing"; @@ -171,7 +223,7 @@ attributes = { BuildIndependentTargetsInParallel = 1; LastSwiftUpdateCheck = 1600; - LastUpgradeCheck = 1600; + LastUpgradeCheck = 1620; TargetAttributes = { 42D3DCB22D51DA2900BC3E8F = { CreatedOnToolsVersion = 16.0; @@ -231,6 +283,109 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 121FBECF5C37504D221DBD66 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-asyncgate_iOSTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 466F2E6F2810D65E84402BCF /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-asyncgate_iOS-asyncgate_iOSUITests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 55623216BD408661BD8AF1E6 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-asyncgate_iOS-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 99A40181F2C12C1C395D8DFB /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS/Pods-asyncgate_iOS-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + BF3276B03C5DBEEBAB8B01D0 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-asyncgate_iOS-asyncgate_iOSUITests/Pods-asyncgate_iOS-asyncgate_iOSUITests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 42D3DCAF2D51DA2900BC3E8F /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -271,6 +426,8 @@ /* Begin XCBuildConfiguration section */ 42D3DCD52D51DA2A00BC3E8F /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReferenceAnchor = 42D3DCB52D51DA2900BC3E8F /* asyncgate_iOS */; + baseConfigurationReferenceRelativePath = .xcconfig.xcconfig; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; @@ -390,6 +547,7 @@ }; 42D3DCD82D51DA2A00BC3E8F /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = BD81FEA621CDE1ACB91A518E /* Pods-asyncgate_iOS.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -398,6 +556,7 @@ DEVELOPMENT_ASSET_PATHS = "\"asyncgate_iOS/Preview Content\""; DEVELOPMENT_TEAM = 5UTK6J592W; ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = "asyncgate-iOS-Info.plist"; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; @@ -405,6 +564,7 @@ INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -420,6 +580,7 @@ }; 42D3DCD92D51DA2A00BC3E8F /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 263BFD25E29DDE3581181D4D /* Pods-asyncgate_iOS.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -428,6 +589,7 @@ DEVELOPMENT_ASSET_PATHS = "\"asyncgate_iOS/Preview Content\""; DEVELOPMENT_TEAM = 5UTK6J592W; ENABLE_PREVIEWS = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = "asyncgate-iOS-Info.plist"; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; @@ -435,6 +597,7 @@ INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -450,6 +613,7 @@ }; 42D3DCDB2D51DA2A00BC3E8F /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 3EA7A6DE9C203FFF10094F1E /* Pods-asyncgate_iOSTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -469,6 +633,7 @@ }; 42D3DCDC2D51DA2A00BC3E8F /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 26810480EB084C8998408B13 /* Pods-asyncgate_iOSTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -488,6 +653,7 @@ }; 42D3DCDE2D51DA2A00BC3E8F /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 1E721A53E3B7060D546CAC15 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.debug.xcconfig */; buildSettings = { CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; @@ -505,6 +671,7 @@ }; 42D3DCDF2D51DA2A00BC3E8F /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 07DBC075A9F63C6B8D460FC3 /* Pods-asyncgate_iOS-asyncgate_iOSUITests.release.xcconfig */; buildSettings = { CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate b/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate index a69a87d5..eafbef9a 100644 Binary files a/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate and b/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/project.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist b/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist index 7a67edea..3d30aa77 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/src/ios/asyncgate_iOS/asyncgate_iOS.xcodeproj/xcuserdata/kdk.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ asyncgate_iOS.xcscheme_^#shared#^_ orderHint - 0 + 8 diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS.xcworkspace/contents.xcworkspacedata b/src/ios/asyncgate_iOS/asyncgate_iOS.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..73bf8693 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate b/src/ios/asyncgate_iOS/asyncgate_iOS.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 00000000..b6d05bc4 Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS.xcworkspace/xcuserdata/kdk.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AccentColor.colorset/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AccentColor.colorset/Contents.json index eb878970..515124d7 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AccentColor.colorset/Contents.json +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AccentColor.colorset/Contents.json @@ -1,6 +1,15 @@ { "colors" : [ { + "color" : { + "color-space" : "srgb", + "components" : { + "alpha" : "1.000", + "blue" : "0.576", + "green" : "0.529", + "red" : "0.522" + } + }, "idiom" : "universal" } ], diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Contents.json index 23058801..65f68893 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,6 +1,7 @@ { "images" : [ { + "filename" : "Frame 1.jpg", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" @@ -12,6 +13,7 @@ "value" : "dark" } ], + "filename" : "Frame 3.jpg", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" @@ -23,6 +25,7 @@ "value" : "tinted" } ], + "filename" : "Frame 2.jpg", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 1.jpg b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 1.jpg new file mode 100644 index 00000000..f9c149ac Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 1.jpg differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 2.jpg b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 2.jpg new file mode 100644 index 00000000..f9c149ac Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 2.jpg differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 3.jpg b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 3.jpg new file mode 100644 index 00000000..f9c149ac Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/AppIcon.appiconset/Frame 3.jpg differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/DiscordLogo.imageset/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/DiscordLogo.imageset/Contents.json new file mode 100644 index 00000000..f6f642ce --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/DiscordLogo.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "discord-mark-white.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/DiscordLogo.imageset/discord-mark-white.png b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/DiscordLogo.imageset/discord-mark-white.png new file mode 100644 index 00000000..baececa9 Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/DiscordLogo.imageset/discord-mark-white.png differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/club.imageset/CU.jpg b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/club.imageset/CU.jpg new file mode 100644 index 00000000..cbca7339 Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/club.imageset/CU.jpg differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/club.imageset/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/club.imageset/Contents.json new file mode 100644 index 00000000..db7804a1 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/club.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "CU.jpg", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/forMe.imageset/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/forMe.imageset/Contents.json new file mode 100644 index 00000000..e387a09e --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/forMe.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "FR.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/forMe.imageset/FR.png b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/forMe.imageset/FR.png new file mode 100644 index 00000000..34213bb8 Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/forMe.imageset/FR.png differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/keyGrab.imageset/Contents.json b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/keyGrab.imageset/Contents.json new file mode 100644 index 00000000..a35e8ff3 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/keyGrab.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "keyGrab.jpg", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/keyGrab.imageset/keyGrab.jpg b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/keyGrab.imageset/keyGrab.jpg new file mode 100644 index 00000000..30fd852f Binary files /dev/null and b/src/ios/asyncgate_iOS/asyncgate_iOS/Assets.xcassets/Guild/keyGrab.imageset/keyGrab.jpg differ diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/BackgroundModifier.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/BackgroundModifier.swift new file mode 100644 index 00000000..8ddc5cb9 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/BackgroundModifier.swift @@ -0,0 +1,60 @@ +// +// BackgroundModifier.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: Modifier - 뷰에 배경색상 일괄 지정 +struct BackgroundModifier: ViewModifier { + func body(content: Content) -> some View { + ZStack { + Color(hex: "#1C1D23") + .ignoresSafeArea() + + content + } + } +} + +// MARK: Modifier - 뷰에 배경색상 일괄 지정 +struct GuildBackgroundModifier: ViewModifier { + func body(content: Content) -> some View { + ZStack { + Color(hex: "#131318") + .ignoresSafeArea() + + content + } + } +} + +// MARK: Modifier - 뷰에 배경색상 일괄 지정 +struct ChattingBGModifier: ViewModifier { + func body(content: Content) -> some View { + ZStack { + Color(hex: "#1C1D23") + .ignoresSafeArea() + + content + } + } +} + +// MARK: Extension - View에서 적용하여 사용가능하도록 지정 +extension View { + func applyBackground() -> some View { + self.modifier(BackgroundModifier()) + } + + func applyGuildBackground() -> some View { + self.modifier(GuildBackgroundModifier()) + } + + func applyChattingBG() -> some View { + self.modifier(ChattingBGModifier()) + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/BackButton.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/BackButton.swift new file mode 100644 index 00000000..662228c2 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/BackButton.swift @@ -0,0 +1,24 @@ +// +// BackButton.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: Button - 뒤로가기 버튼 +struct BackButton: View { + @Environment(\.dismiss) var dismiss + var color: Color = .white + + var body: some View { + Button { + dismiss() + } label: { + Image(systemName: "chevron.left") + .font(.system(size: 15, weight: .bold)) + .foregroundColor(color) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CToggle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CToggle.swift new file mode 100644 index 00000000..931e4451 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CToggle.swift @@ -0,0 +1,38 @@ +// +// CToggle.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import SwiftUI + +struct CToggle: View { + var text: String + @Binding var isPrivate: Bool + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 20) + .foregroundStyle(Color(hex: "#26272F")) + .frame(height: 70) + + HStack { + Image(systemName: "lock.fill") + .resizable() + .frame(width: 20, height: 25) + .foregroundStyle(Color(hex: "#C7C8CE")) + + Text(text) + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#E4E5E8")) + .padding(.leading, 5) + + Toggle("", isOn: $isPrivate) + .tint(Color.colorBlurple) + .padding() + } + .padding() + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CategoryButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CategoryButtonStyle.swift new file mode 100644 index 00000000..1715b8a7 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CategoryButtonStyle.swift @@ -0,0 +1,35 @@ +// +// CategoryButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +struct CategoryButtonStyle: View { + var categoryName: String + + var body: some View { + ZStack { + Rectangle() + .frame(width: 300, height: 30) + .foregroundStyle(Color.colorBG) + + HStack { + Image(systemName: "chevron.down") + // chevron.right로 누르면 수정 + .resizable() + .frame(width: 6, height: 4) + .foregroundStyle(Color.colorWhite) + + Text(categoryName) + .foregroundStyle(Color.colorGrayImage) + .font(Font.pretendardSemiBold(size: 14)) + + Spacer() + } + } + } + +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChannelButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChannelButtonStyle.swift new file mode 100644 index 00000000..535fe50d --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChannelButtonStyle.swift @@ -0,0 +1,39 @@ +// +// ChannelButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +struct ChannelButtonStyle: View { + var channelName: String + var channelType: String + + var body: some View { + ZStack { + Rectangle() + .frame(width: 300, height: 30) + .foregroundStyle(Color.colorBG) + + HStack { + if channelType == "VOICE" { + Image(systemName: "speaker.wave.2.fill") + .resizable() + .frame(width: 16, height: 16) + .foregroundStyle(Color(hex: "#818491")) + } else { + Text("#") + .font(Font.pretendardRegular(size: 20)) + } + + Text(channelName) + .foregroundStyle(Color.colorGrayImage) + .font(Font.pretendardSemiBold(size: 14)) + + Spacer() + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChannelNameButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChannelNameButtonStyle.swift new file mode 100644 index 00000000..8127020c --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChannelNameButtonStyle.swift @@ -0,0 +1,25 @@ +// +// ChannelNameButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/16/25. +// + +import SwiftUI + +struct ChannelNameButtonStyle: View { + var channelName: String + + var body: some View { + HStack { + Text(channelName) + .foregroundStyle(Color.colorWhite) + .font(Font.pretendardBold(size: 17)) + + Image(systemName: "chevron.right") + .resizable() + .frame(width: 5, height: 6) + .foregroundColor(Color(hex: "#9597A3")) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChoiceImageButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChoiceImageButtonStyle.swift new file mode 100644 index 00000000..cf8c633c --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/ChoiceImageButtonStyle.swift @@ -0,0 +1,43 @@ +// +// ChoiceImageButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/20/25. +// + +import SwiftUI + +// MARK: ButtonStyle - 이미지 선택하기 버튼 스타일 +struct ChoiceImageButtonStyle: View { + var image: UIImage? + + var body: some View { + ZStack { + if let image = image { + Image(uiImage: image) + .resizable() + .clipShape(Circle()) + .frame(width: 80, height: 80) + + } else { + Circle() + .stroke( + Color.colorGray, + style: StrokeStyle(lineWidth: 2, dash: [6, 8]) + ) + .foregroundStyle(Color.colorBG) + .frame(width: 80, height: 80) + + VStack { + Image(systemName: "camera.fill") + .foregroundStyle(Color.colorGray) + .padding(.bottom, 2) + + Text("올리기") + .foregroundStyle(Color.colorGray) + .font(Font.pretendardRegular(size: 12)) + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CreateGuildButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CreateGuildButtonStyle.swift new file mode 100644 index 00000000..4f15895b --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/CreateGuildButtonStyle.swift @@ -0,0 +1,58 @@ +// +// CreateGuildButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/7/25. +// + +import SwiftUI + +public struct CreateGuildButtonStyle: View { + var imageName: String + var text: String + var imageWidth: CGFloat + var imageHeight: CGFloat + + var isBehindChevron: Bool = false + var isSystemImage: Bool = false + var isDeleteButton: Bool = false + + public var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 20) + .foregroundStyle(Color(hex: "#26272F")) + .frame(height: 70) + + HStack { + if isSystemImage { + Image(systemName: imageName) + .resizable() + .foregroundStyle(Color.colorWhite) + .frame(width: imageWidth, height: imageHeight) + .padding(.trailing, 2) + } else { + Image(imageName) + .resizable() + .foregroundStyle(Color.colorWhite) + .frame(width: imageWidth, height: imageHeight) + .padding(.trailing, 2) + } + + Text(text) + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(isDeleteButton ? Color.colorRed : Color.colorWhite) + + Spacer() + + if !isBehindChevron { + Image(systemName: "chevron.right") + .resizable() + .foregroundStyle(Color.colorWhite) + .frame(width: 5, height: 10) + } + } + .padding() + } + } + +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/GuildButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/GuildButtonStyle.swift new file mode 100644 index 00000000..a517b9be --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/GuildButtonStyle.swift @@ -0,0 +1,53 @@ +// +// GuildButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/16/25. +// + +import SwiftUI + +struct GuildButtonStyle: View { + let maxLength: Int = 3 + + var name: String + var profileImageUrl: String? + var isSelected: Bool + + var body: some View { + ZStack { + if let imageUrlString = profileImageUrl, let imageUrl = URL(string: imageUrlString) { + AsyncImage(url: imageUrl) { image in + image.image?.resizable() + .clipShape(isSelected ? AnyShape(RoundedRectangle(cornerRadius: 10)) : AnyShape(Circle())) + .frame(width: 46, height: 46) + } + } else { + backgroundShape + } + } + } + + // 길드 기본 버튼 + var backgroundShape: some View { + ZStack { + if isSelected { + RoundedRectangle(cornerRadius: 14) + .frame(width: 46, height: 46) + .foregroundStyle(Color(hex: "#5865F2")) + } else { + Circle() + .frame(width: 46, height: 46) + .foregroundStyle(Color.colorNewGuildButton) + } + + Text(name.count > maxLength ? name.prefix(maxLength) + "..." : name) + .font(Font.pretendardSemiBold(size: 12)) + .foregroundStyle(Color.colorWhite) + } + } +} + +#Preview { + GuildButtonStyle(name: "", profileImageUrl: "", isSelected: true) +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/GuildIconButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/GuildIconButtonStyle.swift new file mode 100644 index 00000000..2297293a --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/GuildIconButtonStyle.swift @@ -0,0 +1,27 @@ +// +// GuildIconButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/10/25. +// + +import SwiftUI + +struct GuildIconButtonStyle: View { + var imageName: String + var width: CGFloat + var height: CGFloat + + var body: some View { + ZStack { + Circle() + .frame(width: 32, height: 32) + .foregroundStyle(Color(hex: "#383A43")) + + Image(systemName: imageName) + .resizable() + .frame(width: width, height: height) + .foregroundStyle(Color(hex: "#C7C8CE")) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/SecondaryActionButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/SecondaryActionButtonStyle.swift new file mode 100644 index 00000000..4be6b152 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/SecondaryActionButtonStyle.swift @@ -0,0 +1,26 @@ +// +// SecondaryActionButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/10/25. +// + +import SwiftUI + +struct SecondaryActionButtonStyle: View { + var imageName: String + var color: Color + + var body: some View { + ZStack { + Circle() + .frame(width: 46, height: 46) + .foregroundStyle(Color.colorNewGuildButton) + + Image(systemName: imageName) + .frame(width: 30, height: 30) + .foregroundStyle(color) + } + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/SignButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/SignButtonStyle.swift new file mode 100644 index 00000000..b4465bf1 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/SignButtonStyle.swift @@ -0,0 +1,25 @@ +// +// SignButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: ButtonStyle - 회원가입/로그인 시 사용되는 버튼 스타일 +struct SignButtonStyle: View { + var text: String + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 4) + .foregroundStyle(Color.colorBlurple) + .frame(height: 40) + + Text(text) + .font(Font.pretendardSemiBold(size: 15)) + .foregroundStyle(Color.colorWhite) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/UsingButtonStyle.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/UsingButtonStyle.swift new file mode 100644 index 00000000..ef8ad554 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/ButtonStyleAndButton/UsingButtonStyle.swift @@ -0,0 +1,28 @@ +// +// UsingButtonStyle.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: ButtonStyle - 반복적으로 사용되는 버튼 스타일 +struct UsingButtonStyle: View { + var text: String + var backgroundColor: Color + var textColor: Color + var size: CGFloat + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 20) + .foregroundStyle(backgroundColor) + .frame(height: 40) + + Text(text) + .font(Font.pretendardSemiBold(size: size)) + .foregroundStyle(textColor) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Chat.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Chat.swift new file mode 100644 index 00000000..edc9b7c8 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Chat.swift @@ -0,0 +1,48 @@ +// +// Chat.swift +// asyncgate_iOS +// +// Created by kdk on 2/28/25. +// + +import SwiftUI + +struct Chat: View { + var profileImage: String + var nickName: String + var message: String + + var body: some View { + HStack { + VStack { + Image(profileImage) + .resizable() + .frame(width: 45, height: 45) + .foregroundStyle(Color(hex: "#C7C8CE")) + + Spacer() + } + + VStack(alignment: .leading) { + HStack { + Text(nickName) + .font(Font.pretendardSemiBold(size: 15)) + .foregroundStyle(Color.colorWhite) + + Text("날짜") + .font(Font.pretendardRegular(size: 13)) + .foregroundStyle(Color(hex: "#C7C8CE")) + + Text("시간") + .font(Font.pretendardRegular(size: 13)) + .foregroundStyle(Color(hex: "#C7C8CE")) + } + + Text(message) + .font(Font.pretendardRegular(size: 15)) + .foregroundStyle(Color.colorWhite) + } + + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Font.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Font.swift deleted file mode 100644 index 75411910..00000000 --- a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Font.swift +++ /dev/null @@ -1,19 +0,0 @@ -// -// Font.swift -// asyncgate_iOS -// -// Created by kdk on 2/4/25. -// - -import SwiftUI - -extension Font { - static let PretendardRegular = Font.custom("Pretendard-Regular", size: 14) - static let PretendardThin = Font.custom("Pretendard-Thin", size: 14) - static let PretendardExtraLight = Font.custom("Pretendard-ExtraLight", size: 14) - static let PretendardLight = Font.custom("Pretendard-Light", size: 14) - static let PretendardSemiBold = Font.custom("Pretendard-SemiBold", size: 14) - static let PretendardBold = Font.custom("Pretendard-Bold", size: 14) - static let PretendardExtraBold = Font.custom("Pretendard-ExtraBold", size: 14) - static let PretendardBlack = Font.custom("Pretendard-Black", size: 14) -} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/CTextField.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/CTextField.swift new file mode 100644 index 00000000..80bc3069 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/CTextField.swift @@ -0,0 +1,39 @@ +// +// CTextField.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import SwiftUI + +// MARK: TextField - 입력하는 텍스트필드 +struct CTextField: View { + var stepCaption: String + var placeholder: String + @Binding var text: String + + var body: some View { + VStack(alignment: .leading) { + Text(stepCaption) + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $text) + .foregroundColor(.white) + .padding() + .background(Color(hex: "#111216")) + .cornerRadius(20) + .overlay( + Group { + if text.isEmpty { + Text(text) + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/PasswordTextField.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/PasswordTextField.swift new file mode 100644 index 00000000..58fa5d55 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/PasswordTextField.swift @@ -0,0 +1,50 @@ +// +// PasswordTextField.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: TextField(SecureField) - 공통으로 사용되는 비밀번호용 텍스트필드 컴포넌트 +struct PasswordField: View { + @Binding var password: String + @State private var isSecure: Bool = true + + var body: some View { + HStack { + if isSecure { + SecureField("", text: $password) + .foregroundColor(.white) + .background(Color.colorDart500) + .cornerRadius(4) + .overlay( + Group { + if password.isEmpty { + Text("비밀번호") + .foregroundStyle(Color.colorDart400) + .padding(.leading, 2) + } + } + , alignment: .leading + ) + } else { + TextField("비밀번호", text: $password) + + } + + Button { + isSecure.toggle() + } label: { + Image(systemName: isSecure ? "eye.slash" : "eye") + .foregroundStyle(Color.colorWhite) + } + } + .foregroundStyle(Color.colorWhite) + .padding() + .background(Color.colorDart500) + .cornerRadius(4) + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/SignTextField.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/SignTextField.swift new file mode 100644 index 00000000..ece259f5 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Component/TextField/SignTextField.swift @@ -0,0 +1,40 @@ +// +// SignTextField.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: TextField - 공통으로 사용되는 텍스트필드 컴포넌트 +struct SignTextField: View { + var stepCaption: String + var placeholder: String + @Binding var text: String + + var body: some View { + VStack(alignment: .leading) { + Text(stepCaption) + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $text) + .foregroundColor(.white) + .padding() + .background(Color.colorDart500) + .cornerRadius(4) + .overlay( + Group { + if text.isEmpty { + Text(placeholder) + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + } + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ContentView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ContentView.swift index e815542c..43db417a 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS/ContentView.swift +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ContentView.swift @@ -9,19 +9,29 @@ import SwiftUI struct ContentView: View { var body: some View { - Text("폰트 이름 출력하기") - .font(Font.PretendardExtraLight) - .onAppear { - for family in UIFont.familyNames { - print(family) - for font in UIFont.fontNames(forFamilyName: family) { - print(" - \(font)") - } - } + TabView { + GuildMainView() + .tabItem { + Image(systemName: "house.fill") + Text("홈") } + + NotificationView() + .tabItem { + Image(systemName: "bell.fill") + Text("알림") + } + + UserInfoView() + .tabItem { + Image(systemName: "person.fill") + Text("나") + } + } } } #Preview { ContentView() } + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/Config.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/Config.swift new file mode 100644 index 00000000..368e3caa --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/Config.swift @@ -0,0 +1,20 @@ +// +// Config.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import Foundation + +// MARK: API 주소 및 번들ID (.gitignore) +class Config { + static let shared = Config() + let hostUrl: String + let bundleId: String + + private init() { + hostUrl = Bundle.main.infoDictionary?["hostUrl"] as? String ?? "" + bundleId = Bundle.main.infoDictionary?["bundleId"] as? String ?? "" + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/CategoryGuildServiceAPIManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/CategoryGuildServiceAPIManager.swift new file mode 100644 index 00000000..96a6fc66 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/CategoryGuildServiceAPIManager.swift @@ -0,0 +1,89 @@ +// +// CategoryGuildServiceAPIManager.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import Alamofire + +// MARK: Manager - Guild Category Service API 매니저 +class CategoryGuildServiceAPIManager { + static let shared = CategoryGuildServiceAPIManager() + + // 호출 - 엑세스 토큰 사용 및 API 주소 + private let accessTokenViewModel = AccessTokenViewModel.shared + private let hostUrl = Config.shared.hostUrl + + // MARK: 함수 - 카테고리 생성 + func createGuildCategory(name: String, guildId: String, isPrivate: Bool, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/category" + + let parameters: [String: Any] = [ + "name": name, + "guildId": guildId, + "private": isPrivate + ] + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: CategoryResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 1, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + } + } + } + } + } + + // MARK: 함수 - 카테고리 삭제 + func deleteGuildCategory(guildId: String, categoryId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/category/\(guildId)/\(categoryId)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .delete, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 1, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + } + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/ChannelGuildServiceAPIManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/ChannelGuildServiceAPIManager.swift new file mode 100644 index 00000000..3bf911c2 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/ChannelGuildServiceAPIManager.swift @@ -0,0 +1,128 @@ +// +// ChannelGuildServiceAPIManager.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import Alamofire + +// MARK: Manager - Guild Channel Service API 매니저 +class ChannelGuildServiceAPIManager { + static let shared = ChannelGuildServiceAPIManager() + + // 호출 - 엑세스 토큰 사용 및 API 주소 + private let accessTokenViewModel = AccessTokenViewModel.shared + private let hostUrl = Config.shared.hostUrl + + // MARK: 함수 - 채널 생성 + func createGuildChannel(name: String, guildId: String, categoryId: String, channelType: String, isPrivate: Bool, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/channel" + + let parameters: [String: Any] = [ + "name": name, + "guildId": guildId, + "categoryId": categoryId, + "channelType": channelType, + "private": isPrivate + ] + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: ChannelResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 1, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + } + } + } + } + } + + // MARK: 함수 - 채널 수정 + func updateGuildChannel(guildId: String, categoryId: String, channelId: String, name: String, topic: String, isPrivate: Bool, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/channel/\(guildId)/\(categoryId)/\(channelId)" + + let parameters: [String: Any] = [ + "name": name, + "topic": topic, + "private": isPrivate + ] + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .patch, parameters: parameters, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: ChannelResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(let e): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + } + print("Error: \(e.localizedDescription)") + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 1, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + } + } + } + } + } + + // MARK: 함수 - 채널 삭제 + func deleteGuildChannel(guildId: String, categoryId: String, channelId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/channel/\(guildId)/\(categoryId)/\(channelId)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .delete, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 1, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + } + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/GuildMemberServiceAPIManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/GuildMemberServiceAPIManager.swift new file mode 100644 index 00000000..33c85736 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/GuildMemberServiceAPIManager.swift @@ -0,0 +1,127 @@ +// +// GuildMemberServiceAPIManager.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import Alamofire + +// MARK: Manager - Guild Member Service API 매니저 +class GuildMemberServiceAPIManager { + static let shared = GuildServiceAPIManager() + + // 호출 - 엑세스 토큰 사용 및 API 주소 + private let accessTokenViewModel = AccessTokenViewModel.shared + private let hostUrl = Config.shared.hostUrl + + // MARK: 함수 - 길드 초대 전송 + func sendGuildInvitation(guildId: String, targetUserId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)/invitations?targetUserId=\(targetUserId)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .post, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } + } + } + } + + // MARK: 함수 - 길드 초대 수락 + func acceptGuildInvitation(guildId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)/invitations/accept)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .patch, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } + } + } + } + + // MARK: 함수 - 길드 초대 거절 + func rejectGuildInvitation(guildId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)/invitations/accept)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .patch, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(let error): + completion(.failure(error)) + } + } + } + } + + // MARK: 함수 - 길드 초대 취소 + func deleteGuildInvitation(guildId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)/invitations" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .delete, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(let error): + completion(.failure(error)) + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/GuildServiceAPIManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/GuildServiceAPIManager.swift new file mode 100644 index 00000000..e9853724 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/GuildAPI/GuildServiceAPIManager.swift @@ -0,0 +1,226 @@ +// +// GuildServiceAPIManager.swift +// asyncgate_iOS +// +// Created by kdk on 2/17/25. +// + +import Alamofire + +// MARK: Manager - Guild Service API 매니저 +class GuildServiceAPIManager { + static let shared = GuildServiceAPIManager() + + // 호출 - 엑세스 토큰 사용 및 API 주소 + private let accessTokenViewModel = AccessTokenViewModel.shared + private let hostUrl = Config.shared.hostUrl + + // MARK: 함수 - 길드 생성 + func createGuild(name: String, isPrivate: Bool, profileImage: UIImage?, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + "Content-Type": "multipart/form-data" + ] + + AF.upload(multipartFormData: { multipartFormData in + multipartFormData.append(name.data(using: .utf8)!, withName: "name") + multipartFormData.append("\(isPrivate)".data(using: .utf8)!, withName: "isPrivate") + + if let image = profileImage?.pngData() { + multipartFormData.append(image, withName: "profileImage", fileName: "\(image).png", mimeType: "image/png") + } + }, to: url, usingThreshold: UInt64.init(), method: .post, headers: headers) + .validate() + .responseDecodable(of: SuccessCreateGuildResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 1))) + } + } + } + } + } + + // MARK: 함수 - 길드 정보 수정 + func updateGuild(guildId: String, name: String, isPrivate: Bool, profileImage: UIImage?, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + "Content-Type": "multipart/form-data" + ] + + AF.upload(multipartFormData: { multipartFormData in + multipartFormData.append(name.data(using: .utf8)!, withName: "name") + multipartFormData.append("\(isPrivate)".data(using: .utf8)!, withName: "isPrivate") + + if let image = profileImage?.pngData() { + multipartFormData.append(image, withName: "profileImage", fileName: "\(image).png", mimeType: "image/png") + } + }, to: url, usingThreshold: UInt64.init(), method: .patch, headers: headers) + .validate() + .responseDecodable(of: SuccessCreateGuildResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 1))) + } + } + } + } + } + + // MARK: 함수 - 길드 삭제 + func deleteGuild(guildId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .delete, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 1))) + } + } + } + } + } + + // MARK: 함수 - 내 길드 목록 조회 + func loadMyGuildList(completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .get, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessLoadGuildListResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 1))) + } + } + } + } + } + + // MARK: 함수 - 랜덤 길드 조회 + func loadMyGuildListRandom(limit: Int, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/rand?limit=\(limit)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .get, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessLoadGuildListResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(OnlyHttpStatusResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 0))) + } + } else { + completion(.failure(OnlyHttpStatusResponse(httpStatus: 1))) + } + } + } + } + } + + // MARK: 함수 - 길드 단일 조회 + func fetchGuildInfo(guildId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/guilds/guilds/\(guildId)" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .get, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: GuildDetailResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(FourErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(FourErrorResponse(timeStamp: "", status: 0, error: "오류가 발생했습니다.", path: ""))) + } + } else { + completion(.failure(FourErrorResponse(timeStamp: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", path: ""))) + } + } + } + } + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/UserServiceAPIManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/UserServiceAPIManager.swift new file mode 100644 index 00000000..fd34c574 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/UserServiceAPIManager.swift @@ -0,0 +1,298 @@ +// +// UserServiceAPIManager.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import Alamofire + +// MARK: Manager - User Service API 매니저 +class UserServiceAPIManager { + static let shared = UserServiceAPIManager() + + // 호출 - 엑세스 토큰 사용 및 API 주소 + private let accessTokenViewModel = AccessTokenViewModel.shared + private let hostUrl = Config.shared.hostUrl + + // MARK: 함수 - 서버 연동 확인 + func health(completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/health" + + AF.request(url, method: .get, encoding: JSONEncoding.default) + .validate() + .responseDecodable(of: SuccessResultStringResponse.self) { response in + switch response.result { + case .success(let healthResponse): + completion(.success(healthResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + + // MARK: 함수 - 임시 회원가입 + func signUp(email: String, passWord: String, name: String, nickName: String, birth: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/sign-up" + + let parameters: [String: Any] = [ + "email": email, + "password": passWord, + "name": name, + "nickname": nickName, + "birth": birth + ] + + AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .validate() + .responseDecodable(of: SuccessEmptyResultResponse.self) { response in + switch response.result { + case .success(let signUpResponse): + completion(.success(signUpResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + + // MARK: 함수 - 이메일 중복 검사 + func checkDuplicatedEmail(email: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/validation/email" + + let parameters: [String: Any] = [ + "email": email + ] + + AF.request(url, method: .post, parameters: parameters, encoding: URLEncoding.queryString) + .validate() + .responseDecodable(of: CheckDuplicatedEmailResponse.self) { response in + switch response.result { + case .success(let checkDuplicatedEmailResponse): + completion(.success(checkDuplicatedEmailResponse)) + + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + + // MARK: 함수 - 이메일 인증번호 인증 + func authEmailCode(email: String, authenticationCode: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/validation/authentication-code" + + let parameters: [String: Any] = [ + "email": email, + "authentication_code": authenticationCode, + ] + + AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .validate() + .responseDecodable(of: SuccessEmptyResultResponse.self) { response in + switch response.result { + case .success(let signUpResponse): + completion(.success(signUpResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + + // MARK: 함수 - 로그인 + func signIn(email: String, passWord: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/sign-in" + + let parameters: [String: Any] = [ + "email": email, + "password": passWord, + ] + + AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .validate() + .responseDecodable(of: SignInResponse.self) { response in + switch response.result { + case .success(let signInResponse): + completion(.success(signInResponse)) + + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + + // MARK: 함수 - 유저 정보 수정 + func updateUserInfo(name: String, nickName: String, profileImage: UIImage?, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/info" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + "Content-Type": "multipart/form-data" + ] + + AF.upload(multipartFormData: { multipartFormData in + multipartFormData.append(name.data(using: .utf8)!, withName: "name") + multipartFormData.append(nickName.data(using: .utf8)!, withName: "nickName") + + if let image = profileImage?.pngData() { + multipartFormData.append(image, withName: "profile_image", fileName: "\(image).png", mimeType: "image/png") + } + }, to: url, usingThreshold: UInt64.init(), method: .patch, headers: headers) + .validate() + .responseDecodable(of: SuccessEmptyResultResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 1, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + } + + // MARK: 함수 - 회원 탈퇴 + func deleteUser(completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/auth" + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)" + ] + + AF.request(url, method: .delete, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessEmptyResultResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + } + } + } + } + } + + // MARK: 함수 - 디바이스 토큰 업데이트 + func updateDeviceToken(deviceToken: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/users/device-token" + + let parameters: [String: Any] = [ + "device_token": deviceToken + ] + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)" + ] + + AF.request(url, method: .patch, parameters: parameters, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: SuccessEmptyResultResponse.self) { response in + switch response.result { + case .success(let signUpResponse): + completion(.success(signUpResponse)) + + case .failure(_): + if let data = response.data { + do { + let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: data) + completion(.failure(errorResponse)) + } catch { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "오류가 발생했습니다.", requestId: ""))) + + } + } else { + completion(.failure(ErrorResponse(timeStamp: "", path: "", status: 0, error: "서버와 연결할 수 없습니다. 다시 시도해주세요.", requestId: ""))) + + } + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/WebSocket/ChattingManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/WebSocket/ChattingManager.swift new file mode 100644 index 00000000..7db5dffc --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/WebSocket/ChattingManager.swift @@ -0,0 +1,44 @@ +// +// ChattingManager.swift +// asyncgate_iOS +// +// Created by kdk on 3/9/25. +// + +import Alamofire + +// MARK: Manager +class ChattingManager { + static let shared = ChattingManager() + + // 호출 - 엑세스 토큰 사용 및 API 주소 + private let accessTokenViewModel = AccessTokenViewModel.shared + private let hostUrl = Config.shared.hostUrl + + // MARK: 함수 - 채팅 불러오기 + func getChattingList(page: Int, size: Int, channelId: String, completion: @escaping (Result) -> Void) { + let url = "https://\(hostUrl)/chats/chat/direct?page=\(page)&size=\(size)&channel-id=\(channelId)" + + print(url) + + if let accessToken = accessTokenViewModel.accessToken { + let headers: HTTPHeaders = [ + "Authorization": "Bearer \(accessToken)", + ] + + AF.request(url, method: .get, encoding: JSONEncoding.default, headers: headers) + .validate() + .responseDecodable(of: ChatResponse.self) { response in + switch response.result { + case .success(let successResponse): + completion(.success(successResponse)) + print("결과 확인확인 \(successResponse)") + + case .failure(let error): + completion(.failure(error)) + print("에러발생발생발생 \(error)") + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/WebSocket/WedSocketManager.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/WebSocket/WedSocketManager.swift new file mode 100644 index 00000000..28cdf4dd --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Manager/WebSocket/WedSocketManager.swift @@ -0,0 +1,140 @@ +// +// WedSocketManager.swift +// asyncgate_iOS +// +// Created by kdk on 3/9/25. +// + +import Starscream + +class WedSocketManager: ObservableObject, WebSocketDelegate { + + private var socket: WebSocket? + + @Published var messages: [ChatMessage] = [] + + private let accessTokenViewModel = AccessTokenViewModel.shared + + // 기본 웹소켓 설정 + init() { + connect() + } + + // Websocket 연결 시작 + func connect() { + if let accessToken = accessTokenViewModel.accessToken { + guard let url = URL(string: "") else { + return + } + + var request = URLRequest(url: url) + request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") + request.addValue(accessToken, forHTTPHeaderField: "Sec-WebSocket-Protocol") + request.timeoutInterval = 5 + + self.socket = WebSocket(request: request) + self.socket?.delegate = self + self.socket?.connect() + } + } + + // Websocket 연결 종료 + func disconnect() { + self.socket?.disconnect() + + } + + func didConnect(socket: WebSocketClient) { + let connectMessage = """ + CONNECT + accept-version:1.0 + heart-beat:10000,10000 + """ + socket.write(string: connectMessage) + } + + // 서버에서 받기 + func didReceive(event: WebSocketEvent, client: WebSocketClient) { + switch event { + case .connected(let headers): + print("웹소켓 연결 성공. 헤더 \(headers)") + case .disconnected(let reason, let code): + print("웹소켓 연결 종료 \(reason), code: \(code)") + case .text(let string): + print("서버에서 받은 텍스트 메시지: \(string)") + case .binary(let data): + print("바이너리 데이터: \(data)") + case .ping(_): + print("웹소켓 핑") + break + case .pong(_): + print("웹소켓 퐁") + break + case .viabilityChanged(let result): + if result { + print("웹소켓 연결 안정적? \(result)") + } else { + print("다시 다시 재연결 시도 중...") + socket?.connect() + } + break + case .reconnectSuggested(let result): + print("웹소켓 재연결 필요? \(result)") + if result { + print("재연결 시도 중...") + socket?.connect() + } + break + case .cancelled: + print("웹소켓이 강제로 종료됨") + break + case .peerClosed: + print("서버에서 웹소켓 닫음") + break + case .error(let error): + if let error = error { + print("웹소켓 도중 에러 발생: \(error.localizedDescription)") + + if let upgradeError = error as? Starscream.HTTPUpgradeError { + // HTTPUpgradeError에서 발생한 에러를 더 자세히 출력 + print("업그레이드 에러 발생: \(upgradeError.localizedDescription)") + + } + + if let urlError = error as? URLError { + print("URL 오류 코드: \(urlError.code)") + print("URL 오류 설명: \(urlError.localizedDescription)") + } + } else { + print("웹소켓 도중 알 수 없는 오류 발생") + } + } + } + + // 서버로 현재 입력 상태인지 보내기 + func sendTyping(channelId: String, name: String, content: String) { + if let accessToken = accessTokenViewModel.accessToken { + let directTyping: [String: Any] = [ + "channelId": channelId, + "name": name, + "content": content + ] + + guard let directTypingJsonData = try? JSONSerialization.data(withJSONObject: directTyping), let jsonString = String(data: directTypingJsonData, encoding: .utf8) else { return } + + let stompMessage = """ + SEND + destination:/kafka/chat/direct/typing + + \(jsonString) + """ + + socket?.write(string: stompMessage) + } + } + + // Websocket 연결 끊어짐 + func didDisconnect(error: Error?, socket: WebSocketClient) { + print("웹소켓 연결 끊어짐") + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Model/ChatResponse.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Model/ChatResponse.swift new file mode 100644 index 00000000..938283a6 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Model/ChatResponse.swift @@ -0,0 +1,78 @@ +// +// ChatResponse.swift +// asyncgate_iOS +// +// Created by kdk on 3/9/25. +// + +import Foundation + +struct ChatResponse: Codable { + let httpStatus: Int + let message: String + let time: String + let result: ChatResult +} + +struct ChatResult: Codable { + let isFirst: Bool + let isLast: Bool + let totalCount: Int + let totalPages: Int + let currentPage: Int + let pageSize: Int + let directMessages: [DirectMessage] +} + +struct DirectMessage: Codable { + let id: String + let channelId: String + let userId: String + let type: String + let profileImage: String + let name: String + let content: String + let thumbnail: String + let parentId: String + let parentName: String + let parentContent: String + let createdAt: String + + func toChatMeassage() -> ChatMessage { + ChatMessage( + channelId: self.channelId, + userId: self.userId, + profileImage: self.profileImage, + name: self.name, + content: self.content, + createdAt: formattedCreatedAt() + ) + } + + // 함수 - 채팅 생성 날짜를 형태에 맞게 변환 (값 전환 불가 시 기본 값) + func formattedCreatedAt() -> String { + let dateStringformatter = DateFormatter() + dateStringformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" + dateStringformatter.locale = Locale(identifier: "ko_KR") + dateStringformatter.timeZone = TimeZone(abbreviation: "UTC") + + if let date = dateStringformatter.date(from: createdAt) { + let formatter = DateFormatter() + formatter.dateFormat = "M/d/yy, HH:mm" + formatter.locale = Locale(identifier: "ko_KR") + + return formatter.string(from: date) + } + + return createdAt + } +} + +struct ChatMessage: Codable { + let channelId: String + let userId: String + let profileImage: String + let name: String + let content: String + let createdAt: String +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Model/OnlyUserAPIResponse.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Model/OnlyUserAPIResponse.swift new file mode 100644 index 00000000..c3af6518 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Model/OnlyUserAPIResponse.swift @@ -0,0 +1,45 @@ +// +// OnlyUserAPIResponse.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import Foundation + +// MARK: ONLY USER API RESPONSE (USER API에서만 사용됨) + +// MARK: 응답 - 엑세스 토큰을 받는 응답 +struct SignInResponse: Decodable { + let httpStatus: Int + let message: String + let time: String + let result: AccessTokenResponse? +} + +// SignInResponse -> 엑세스 토큰을 받아옴 +struct AccessTokenResponse: Decodable { + let accessToken: String + + enum CodingKeys: String, CodingKey { + case accessToken = "access_token" + } +} + +// MARK: 응답 - 이메일 중복 확인 후 받을 응답 +struct CheckDuplicatedEmailResponse: Decodable { + let httpStatus: Int + let message: String + let time: String + let result: DuplicateEmailResponse +} + +// CheckDuplicatedEmailResponse -> 이메일 중복 여부를 받아옴 +struct DuplicateEmailResponse: Decodable { + let isDuplicate: Bool + + enum CodingKeys: String, CodingKey { + case isDuplicate = "is_duplicate" + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Model/Response.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Model/Response.swift new file mode 100644 index 00000000..94583a67 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Model/Response.swift @@ -0,0 +1,157 @@ +// +// Response.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import Foundation + +// MARK: 응답 - result가 String 타입인 응답 +struct SuccessResultStringResponse: Decodable { + let httpStatus: Int + let message: String + let time: String + let result: String +} + +// MARK: 응답 - 회원가입, 유저 정보 수정 등 가장 자주 사용되는 응답 +struct SuccessEmptyResultResponse: Decodable { + let httpStatus: Int + let message: String + let time: String + let result: EmptyResponse? +} + +// SuccessEmptyResultResponse -> 빈 배열의 형태로 받아오므로 빈 상태로 선언 +struct EmptyResponse: Decodable { +} + +// MARK: 에러 응답 - 에러 발생 시 받아올 응답 +struct ErrorResponse: Decodable, Error { + let timeStamp: String + let path: String + let status: Int + let error: String + let requestId: String? + + enum CodingKeys: String, CodingKey { + case timeStamp = "timestamp" + case path + case status + case error + case requestId + } +} + +// MARK: 에러 응답 - 에러 발생 시 받아올 응답 (4개만 존재) +struct FourErrorResponse: Decodable, Error { + let timeStamp: String + let status: Int + let error: String + let path: String + + enum CodingKeys: String, CodingKey { + case timeStamp = "timestamp" + case status + case error + case path + } +} + +// MARK: 에러 응답 - httpStatus만 받는 응답 +struct OnlyHttpStatusResponse: Decodable, Error { + let httpStatus: Int +} + +// MARK: 응답 - 길드 생성 시 받는 응답 +struct SuccessCreateGuildResponse: Codable { + let httpStatus: Int + let message: String + let time: String + let result: GuildInfo +} + +// MARK: 응답 - 내 길드 목록 조회 시 받는 응답 +struct SuccessLoadGuildListResponse: Codable { + let httpStatus: Int + let message: String + let time: String + let result: LoadGuildListResponse +} + +// 길드 정보 배열 +struct LoadGuildListResponse: Codable { + let responses: [GuildInList] +} + +// 길드 한개에 대한 정보 +struct GuildInList: Codable, Hashable { + let guildId: String + let name: String + let profileImageUrl: String +} + +// MARK: 응답 - 길드 단일 조회 시 받는 응답 +struct GuildDetailResponse: Codable { + let httpStatus: Int + let message: String + let time: String + let result: GuildDetailResponseResult +} + +// 단일 조회 시 받아오는 목록 +struct GuildDetailResponseResult: Codable { + let guild: GuildInfo + let categories: [GuildCategory] + let channels: [GuildChannel] +} + +// 길드 정보 +struct GuildInfo: Codable, Hashable { + let guildId: String + let name: String + let isPrivate: Bool + let profileImageUrl: String +} + +// 길드 카테고리 +struct GuildCategory: Codable, Hashable { + let categoryId: String + let name: String + let isPrivate: Bool +} + +// 길드 채널 +struct GuildChannel: Codable, Hashable { + let channelId: String + let name: String + let topic: String? + let categoryId: String? + let guildId: String? + let channelType: String + let isPrivate: Bool +} + +// MARK: 응답 - 카테고리 관련 응답 +struct CategoryResponse: Codable { + let httpStatus: Int + let message: String + let time: String + let result: CategoryInfo +} + +struct CategoryInfo: Codable, Hashable { + let categoryId: String + let name: String + let isPrivate: Bool + let guildId: String +} + +// MARK: 응답 - 채널 관련 응답 +struct ChannelResponse: Codable { + let httpStatus: Int + let message: String + let time: String + let result: GuildChannel +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Color.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Resources/Color.swift similarity index 64% rename from src/ios/asyncgate_iOS/asyncgate_iOS/Component/Color.swift rename to src/ios/asyncgate_iOS/asyncgate_iOS/Resources/Color.swift index 15fbd8cb..fdf7c15d 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS/Component/Color.swift +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Resources/Color.swift @@ -33,4 +33,16 @@ extension Color { static let colorDart500 = Color(hex: "#383A40") static let colorDart400 = Color(hex: "#80848E") static let colorWhite = Color(hex: "#FFFFFF") + static let colorMain = Color(hex: "#5865F2") + static let colorBlue = Color(hex: "#161CBC") + static let colorBlurple = Color(hex: "#5865F2") + static let colorGreen = Color(hex: "#57F287") + static let colorYellow = Color(hex: "#FEE75C") + static let colorFuchsia = Color(hex: "#EB459E") + static let colorRed = Color(hex: "#ED4245") + static let colorBG = Color(hex: "#1C1D23") + static let colorGray = Color(hex: "#B9BBBE") + static let colorGrayCaption = Color(hex: "#E4E5E8") + static let colorNewGuildButton = Color(hex: "#26272F") + static let colorGrayImage = Color(hex: "#C7C8CE") } diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/Resources/Font.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/Resources/Font.swift new file mode 100644 index 00000000..61c6bfdb --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/Resources/Font.swift @@ -0,0 +1,42 @@ +// +// Font.swift +// asyncgate_iOS +// +// Created by kdk on 2/4/25. +// + +import SwiftUI + +extension Font { + static func pretendardRegular(size: CGFloat) -> Font { + return Font.custom("Pretendard-Regular", size: size) + } + + static func pretendardThin(size: CGFloat) -> Font { + return Font.custom("Pretendard-Thin", size: size) + } + + static func pretendardExtraLight(size: CGFloat) -> Font { + return Font.custom("Pretendard-ExtraLight", size: size) + } + + static func pretendardLight(size: CGFloat) -> Font { + return Font.custom("Pretendard-Light", size: size) + } + + static func pretendardSemiBold(size: CGFloat) -> Font { + return Font.custom("Pretendard-SemiBold", size: size) + } + + static func pretendardBold(size: CGFloat) -> Font { + return Font.custom("Pretendard-Bold", size: size) + } + + static func pretendardExtraBold(size: CGFloat) -> Font { + return Font.custom("Pretendard-ExtraBold", size: size) + } + + static func pretendardBlack(size: CGFloat) -> Font { + return Font.custom("Pretendard-Black", size: size) + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Chatting/ChattingView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Chatting/ChattingView.swift new file mode 100644 index 00000000..8a537a3f --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Chatting/ChattingView.swift @@ -0,0 +1,89 @@ +// +// ChattingView.swift +// asyncgate_iOS +// +// Created by kdk on 2/16/25. +// + +import SwiftUI + +// FIXME: UI만 만들어놓음 +struct ChattingView: View { + @State private var chat: String = "" + + var body: some View { + VStack { + HStack { + BackButton() + + Button { + + } label: { + chattingChannelNameButtonStyle + } + + Spacer() + + Button { + + } label: { + GuildIconButtonStyle(imageName: "magnifyingglass", width: 16, height: 17) + } + + } + + ScrollView { + ForEach(0..<4, id: \.self) { _ in + Chat(profileImage: "", nickName: "KDK", message: "안녕하세요.") + } + } + + HStack { + Button { + + } label: { + chattingIconButtonStyle + } + + TextField("채팅을 입력하세요", text: $chat) + .frame(height: 43) + .padding(.leading, 15) + .background(Color(hex: "#25272E")) + .clipShape(RoundedRectangle(cornerRadius: 20)) + } + + } + .padding(15) + .applyChattingBG() + .navigationBarBackButtonHidden(true) + } + + var chattingChannelNameButtonStyle: some View { + HStack { + Text("#") + .foregroundStyle(Color.colorDart400) + .font(Font.pretendardBold(size: 20)) + + ChannelNameButtonStyle(channelName: "중꺽마") + + } + } + + var chattingIconButtonStyle: some View { + ZStack { + Circle() + .frame(width: 43, height: 43) + .foregroundStyle(Color(hex: "#25272E")) + + Image(systemName: "plus") + .resizable() + .frame(width: 20, height: 20) + .foregroundStyle(Color(hex: "#C7C8CE")) + } + } +} + + +#Preview { + ChattingView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Chatting/cccc.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Chatting/cccc.swift new file mode 100644 index 00000000..838135ef --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Chatting/cccc.swift @@ -0,0 +1,46 @@ +// +// Chat.swift +// asyncgate_iOS +// +// Created by kdk on 3/9/25. +// + +import SwiftUI + +struct ChatChatView: View { + @StateObject var webSocketManager: WedSocketManager = WedSocketManager() + @StateObject var chatchat: ChatViewModel = ChatViewModel() + + @State private var typingContent: String = "" + + var body: some View { + VStack { + Text("Messages:") + .font(.title2) + .padding(.top) + + Button("NEEEEEEEEE") { + chatchat.getMessages() + } + + HStack { + TextField("Type a message", text: $typingContent) + .padding() + .textFieldStyle(RoundedBorderTextFieldStyle()) + + Button("Send Typing Status") { + webSocketManager.sendTyping(channelId: "7e27f7c8-581d-4001-a684-a58e953b3e26", name: "John Doe", content: typingContent) + } + .padding() + } + } + .onAppear { + webSocketManager.connect() // WebSocket 연결 + print("처음 연결 시도") + } + .onDisappear { + webSocketManager.disconnect() + print("해제됨")// WebSocket 연결 해제 + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/ChoiceGuildTypeView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/ChoiceGuildTypeView.swift new file mode 100644 index 00000000..93c53718 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/ChoiceGuildTypeView.swift @@ -0,0 +1,50 @@ +// +// ChoiceGuildTypeView.swift +// asyncgate_iOS +// +// Created by kdk on 2/7/25. +// + +import SwiftUI + +// MARK: View - 길드 타입 설정 +struct ChoiceGuildTypeView: View { + @StateObject var cudGuildViewModel = CUDGuildViewModel() + @Binding var isShowCreateGuildView: Bool + + var body: some View { + VStack { + Text("이 서버에 대해 더 자세히 말해주세요.") + .font(Font.pretendardBold(size: 24)) + .foregroundColor(Color.colorWhite) + .padding(.bottom, 10) + + Text("설정을 돕고자 질문을 드려요. 혹시 서버가 친구 몇 명만을 위한 서버인가요, 아니면 다른 더 큰 커뮤니티를 위한 서버인가요?") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorDart400) + .multilineTextAlignment(.center) + .padding(.bottom, 30) + + NavigationLink(destination: CreateGuildLastView(cudGuildViewModel: cudGuildViewModel, isShowCreateGuildView: $isShowCreateGuildView)) { + CreateGuildButtonStyle(imageName: "club",text: "클럽, 혹은 커뮤니티용 서버", imageWidth: 48, imageHeight: 44) + } + .simultaneousGesture(TapGesture().onEnded { + cudGuildViewModel.isPrivate = false + }) + + NavigationLink(destination: CreateGuildLastView(cudGuildViewModel: cudGuildViewModel, isShowCreateGuildView: $isShowCreateGuildView)) { + CreateGuildButtonStyle(imageName: "forMe", text: "나와 친구들을 위한 서버", imageWidth: 48, imageHeight: 44) + } + .simultaneousGesture(TapGesture().onEnded { + cudGuildViewModel.isPrivate = true + }) + + Spacer() + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/CreateGuildLastView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/CreateGuildLastView.swift new file mode 100644 index 00000000..d487e565 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/CreateGuildLastView.swift @@ -0,0 +1,103 @@ +// +// CreateGuildLastView.swift +// asyncgate_iOS +// +// Created by kdk on 2/7/25. +// + +import SwiftUI +import PhotosUI + +// MARK: View - 서버 이름 및 이미지 선택 후 길드 생성 +struct CreateGuildLastView: View { + @ObservedObject var cudGuildViewModel: CUDGuildViewModel + @State var selectedPhoto: PhotosPickerItem? + @Binding var isShowCreateGuildView: Bool + + var body: some View { + NavigationStack { + VStack { + Text("서버를 만들어보세요") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + .padding(.bottom, 10) + + Text("서버는 나와 친구들이 함께 어울리는 공간입니다.\n 내 서버를 만들고 대화를 시작해보세요.") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorDart400) + .multilineTextAlignment(.center) + .padding(.bottom, 37) + + PhotosPicker( + selection: $selectedPhoto, + matching: .images + ) { + ChoiceImageButtonStyle(image: cudGuildViewModel.profileImage) + } + + VStack(alignment: .leading) { + Text("서버 이름") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $cudGuildViewModel.name) + .foregroundColor(.white) + .padding() + .background(Color(hex: "#111216")) + .cornerRadius(20) + .overlay( + Group { + if cudGuildViewModel.name == "" { + Text("서버 이름") + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + } + .padding(.top, 13) + .padding(.bottom, 30) + + Button { + cudGuildViewModel.createGuild() + isShowCreateGuildView = false + } label: { + UsingButtonStyle(text: "서버 만들기", backgroundColor: Color.colorBlurple, textColor: Color.colorWhite, size: 14) + } + + if let errorMessage = cudGuildViewModel.errorMessage { + Text(errorMessage) + .foregroundColor(.red) + .font(Font.pretendardRegular(size: 14)) + .padding(.top, 10) + } + + Spacer() + } + .applyBackground() + } + .onChange(of: selectedPhoto) { _, newValue in + loadPhoto(from: newValue) + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + } + + // 함수 - PhotosPickerItem 타입의 이미지를 UIImage로 변경하는 함수 + private func loadPhoto(from photo: PhotosPickerItem?) { + guard let photo = photo else { return } + + photo.loadTransferable(type: Data.self) { result in + if case .success(let data) = result, let data, let image = UIImage(data: data) { + DispatchQueue.main.async { + cudGuildViewModel.profileImage = image + } + } + } + } +} + + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/CreateGuildView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/CreateGuildView.swift new file mode 100644 index 00000000..d4ed8bd1 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/CreateGuild/CreateGuildView.swift @@ -0,0 +1,61 @@ +// +// CreateGuildView.swift +// asyncgate_iOS +// +// Created by kdk on 2/7/25. +// + +import SwiftUI + +struct CreateGuildView: View { + @Environment(\.dismiss) var dismiss + @Binding var isShowCreateGuildView: Bool + + var body: some View { + NavigationStack { + VStack { + Text("서버를 만들어보세요") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + .padding(.bottom, 10) + + Text("서버는 나와 친구들이 함께 어울리는 공간입니다.\n 내 서버를 만들고 대화를 시작해보세요.") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorDart400) + .multilineTextAlignment(.center) + .padding(.bottom, 30) + + NavigationLink(destination: ChoiceGuildTypeView(isShowCreateGuildView: $isShowCreateGuildView)) { + CreateGuildButtonStyle(imageName: "keyGrab",text: "직접 만들기", imageWidth: 48, imageHeight: 44) + } + + Spacer() + + VStack { + Text("이미 초대장을 받으셨나요?") + .font(Font.pretendardSemiBold(size: 20)) + .foregroundColor(Color.colorGrayCaption) + .padding(.bottom, 10) + + Button { + // FIXME: 수정 예정 + } label: { + UsingButtonStyle(text: "서버 참가하기", backgroundColor: Color.colorBlurple, textColor: Color.colorWhite, size: 14) + } + } + + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 15, weight: .bold)) + .foregroundStyle(Color.colorWhite) + }) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/CreateCategoryView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/CreateCategoryView.swift new file mode 100644 index 00000000..0eaba173 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/CreateCategoryView.swift @@ -0,0 +1,76 @@ +// +// CreateCategoryView.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import SwiftUI + +// MARK: View - 카테고리 생성하기 +struct CreateCategoryView: View { + @Environment(\.dismiss) var dismiss + @ObservedObject var guildCategoryViewModel: GuildCategoryViewModel + @ObservedObject var guildDetailViewModel: GuildDetailViewModel + + var body: some View { + NavigationStack { + VStack { + HStack { + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 16, weight: .bold)) + .foregroundStyle(Color.colorWhite) + } + Spacer() + + Text("카테고리 만들기") + .font(Font.pretendardBold(size: 18)) + .foregroundColor(Color.colorWhite) + + Spacer() + + Button { + if let guildId = guildDetailViewModel.guildId { + guildCategoryViewModel.guildId = guildId + guildCategoryViewModel.createCategory() + dismiss() + } + } label: { + Text("만들기") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#6469A2")) + } + } + .padding(.bottom, 10) + + Divider() + .padding(.bottom, 10) + + CTextField(stepCaption: "카테고리 이름", placeholder: "새로운 카테고리", text: $guildCategoryViewModel.name) + + Text("카테고리를 비공개로 만들면 선택한 멤버들과 역할만 이 카테고리를 볼 수 있어요. 이 설정은 이 카테고리에 동기화된 채널들에도 자동으로 적용돼요.") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorDart400) + .multilineTextAlignment(.leading) + .padding(.top, 10) + .padding(.bottom, 10) + + CToggle(text: "비공개 카테고리", isPrivate: $guildCategoryViewModel.isPrivate) + + if let error = guildDetailViewModel.errorMessage { + Text(error) + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorRed) + } + + Spacer() + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/CreateChannelView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/CreateChannelView.swift new file mode 100644 index 00000000..adb6557a --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/CreateChannelView.swift @@ -0,0 +1,174 @@ +// +// CreateChannelView.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import SwiftUI + +// MARK: View - 채널 생성하기 +struct CreateChannelView: View { + @Environment(\.dismiss) var dismiss + @ObservedObject var guildChannelViewModel: GuildChannelViewModel + @ObservedObject var guildDetailViewModel: GuildDetailViewModel + + var guildId: String? + + var body: some View { + NavigationStack { + VStack(alignment: .leading) { + HStack { + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 16, weight: .bold)) + .foregroundStyle(Color.colorWhite) + } + Spacer() + + Text("채널 만들기") + .font(Font.pretendardBold(size: 18)) + .foregroundColor(Color.colorWhite) + + Spacer() + + Button { + if let guildId = guildDetailViewModel.guildId { + guildChannelViewModel.guildId = guildId + guildChannelViewModel.createChannel() + dismiss() + } + } label: { + Text("만들기") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#6469A2")) + } + } + .padding(.bottom, 10) + + Divider() + .padding(.bottom, 10) + + CTextField(stepCaption: "채널 이름", placeholder: "새로운 채널", text: $guildChannelViewModel.name) + + Text("채널 유형") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + Button { + guildChannelViewModel.channelType = "TEXT" + } label: { + ZStack { + RoundedRectangle(cornerRadius: 20) + .foregroundStyle(Color(hex: "#26272F")) + .frame(height: 60) + + HStack { + Text("#") + .font(Font.pretendardRegular(size: 30)) + .foregroundStyle(Color(hex: "#C7C8CE")) + + VStack(alignment: .leading) { + Text("텍스트") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#C7C8CE")) + + Text("이미지, GIF, 스티커, 의견, 농담을 올려보세요") + .font(Font.pretendardSemiBold(size: 11)) + .foregroundStyle(Color.colorDart400) + .multilineTextAlignment(.leading) + } + .padding(.leading, 2) + + Spacer() + + if guildChannelViewModel.channelType == "TEXT" { + selectedButtonStyle + } else { + notSelectedButtonStyle + } + } + .padding() + } + } + + Button { + guildChannelViewModel.channelType = "VOICE" + } label: { + ZStack { + RoundedRectangle(cornerRadius: 20) + .foregroundStyle(Color(hex: "#26272F")) + .frame(height: 60) + + HStack { + Image(systemName: "speaker.1.fill") + .resizable() + .frame(width: 22, height: 22) + .foregroundStyle(Color(hex: "#C7C8CE")) + + VStack(alignment: .leading) { + Text("음성") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#C7C8CE")) + + Text("음성, 영상, 화면 공유로 함께 어울리세요") + .font(Font.pretendardSemiBold(size: 11)) + .foregroundStyle(Color.colorDart400) + .multilineTextAlignment(.leading) + } + .padding(.leading, 2) + + Spacer() + + if guildChannelViewModel.channelType == "TEXT" { + notSelectedButtonStyle + } else { + selectedButtonStyle + } + } + .padding() + } + } + + Text("채널을 비공개로 만들면 선택한 멤버들과 역할만 이 채널을 볼 수 있어요.") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorDart400) + .multilineTextAlignment(.leading) + .padding(.top, 10) + .padding(.bottom, 10) + + CToggle(text: "비공개 채널", isPrivate: $guildChannelViewModel.isPrivate) + + Spacer() + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + } + } + + // ButtonStyle - 텍스트/음성 선택 여부 - 선택 O + var selectedButtonStyle: some View { + ZStack { + Circle() + .foregroundStyle(Color.colorWhite) + .frame(width: 30, height: 30) + + Image(systemName: "record.circle.fill") + .resizable() + .frame(width: 30, height: 30) + .foregroundStyle(Color(hex: "#5865F2")) + } + } + + // ButtonStyle - 텍스트/음성 선택 여부 - 선택 X + var notSelectedButtonStyle: some View { + Image(systemName: "circle") + .resizable() + .frame(width: 30, height: 30) + .foregroundStyle(Color(hex: "#C7C8CE")) + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildCategoryModalView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildCategoryModalView.swift new file mode 100644 index 00000000..4f7e2f1d --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildCategoryModalView.swift @@ -0,0 +1,80 @@ +// +// GuildCategoryModalView.swift +// asyncgate_iOS +// +// Created by kdk on 2/21/25. +// + +import SwiftUI + +// MARK: View - 카테고리 모달 뷰 (편집) +struct GuildCategoryModalView: View { + @Environment(\.presentationMode) var presentation + + @ObservedObject var guildDetailViewModel: GuildDetailViewModel + @ObservedObject var guildCategoryViewModel: GuildCategoryViewModel + @ObservedObject var guildChannelViewModel: GuildChannelViewModel + + @State private var isShowCreateCategoryView: Bool = false + @State private var isShowCreateChannelView: Bool = false + @State private var isShowUpdateGuildView: Bool = false + + let maxLength: Int = 4 + + var body: some View { + VStack(alignment: .leading) { + HStack { + ZStack { + if let imageUrlString = guildDetailViewModel.guild?.profileImageUrl, let imageUrl = URL(string: imageUrlString) { + AsyncImage(url: imageUrl) { image in + image.image?.resizable() + .clipShape(RoundedRectangle(cornerRadius: 10)) + .frame(width: 50, height: 50) + } + + } else { + RoundedRectangle(cornerRadius: 10) + .frame(width: 50, height: 50) + .foregroundStyle(Color.colorNewGuildButton) + + if let guildName = guildDetailViewModel.guild?.name { + Text(guildName.count > maxLength ? guildName.prefix(maxLength) + "..." : guildName) + .font(Font.pretendardSemiBold(size: 12)) + .foregroundStyle(Color.colorWhite) + } + } + } + + Text(guildCategoryViewModel.name) + .font(Font.pretendardSemiBold(size: 20)) + .foregroundStyle(Color.colorWhite) + .padding(.top, 10) + + Spacer() + } + .padding(.bottom, 20) + + Button { + isShowCreateChannelView = true + } label: { + CreateGuildButtonStyle(imageName: "plus", text: "채널 만들기", imageWidth: 24, imageHeight: 24, isBehindChevron: true, isSystemImage: true) + } + + Button { + guildCategoryViewModel.deleteCategory() + presentation.wrappedValue.dismiss() + } label: { + CreateGuildButtonStyle(imageName: "xmark", text: "카테고리 삭제하기", imageWidth: 24, imageHeight: 24, isBehindChevron: true, isSystemImage: true) + } + + + Spacer() + } + .padding() + .applyBackground() + .padding(.top, 20) + .fullScreenCover(isPresented: $isShowCreateChannelView) { + CreateChannelView(guildChannelViewModel: guildChannelViewModel, guildDetailViewModel: guildDetailViewModel) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildChannelModalView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildChannelModalView.swift new file mode 100644 index 00000000..d55d6fc6 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildChannelModalView.swift @@ -0,0 +1,76 @@ +// +// GuildChannelModalView.swift +// asyncgate_iOS +// +// Created by kdk on 2/21/25. +// + +import SwiftUI + +// MARK: View - 채널 모달 뷰 (편집) +struct GuildChannelModalView: View { + @Environment(\.presentationMode) var presentation + + @ObservedObject var guildDetailViewModel: GuildDetailViewModel + @ObservedObject var guildChannelViewModel: GuildChannelViewModel + + @State private var isShowUpdateChannelView: Bool = false + + let maxLength: Int = 4 + + var body: some View { + VStack(alignment: .leading) { + HStack { + ZStack { + if let imageUrlString = guildDetailViewModel.guild?.profileImageUrl, let imageUrl = URL(string: imageUrlString) { + AsyncImage(url: imageUrl) { image in + image.image?.resizable() + .clipShape(RoundedRectangle(cornerRadius: 10)) + .frame(width: 50, height: 50) + } + + } else { + RoundedRectangle(cornerRadius: 10) + .frame(width: 50, height: 50) + .foregroundStyle(Color.colorNewGuildButton) + + if let guildName = guildDetailViewModel.guild?.name { + Text(guildName.count > maxLength ? guildName.prefix(maxLength) + "..." : guildName) + .font(Font.pretendardSemiBold(size: 12)) + .foregroundStyle(Color.colorWhite) + } + } + } + + Text(guildChannelViewModel.name) + .font(Font.pretendardSemiBold(size: 20)) + .foregroundStyle(Color.colorWhite) + .padding(.top, 10) + + Spacer() + } + .padding(.bottom, 20) + + Button { + isShowUpdateChannelView = true + } label: { + CreateGuildButtonStyle(imageName: "gearshape.fill", text: "채널 편집", imageWidth: 24, imageHeight: 24, isBehindChevron: true, isSystemImage: true) + } + + Button { + guildChannelViewModel.deleteChannel() + presentation.wrappedValue.dismiss() + } label: { + CreateGuildButtonStyle(imageName: "", text: "채널 삭제하기", imageWidth: 0, imageHeight: 0, isBehindChevron: true, isSystemImage: true, isDeleteButton: true) + } + + Spacer() + } + .padding() + .applyBackground() + .padding(.top, 20) + .fullScreenCover(isPresented: $isShowUpdateChannelView) { + UpdateChannelView(guildChannelViewModel: guildChannelViewModel, guildDetailViewModel: guildDetailViewModel) + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildMainView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildMainView.swift new file mode 100644 index 00000000..dc2886b7 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildMainView.swift @@ -0,0 +1,266 @@ +// +// GuildMainView.swift +// asyncgate_iOS +// +// Created by kdk on 2/7/25. +// + +import SwiftUI + +// MARK: MainView - 길드 메인 화면 +struct GuildMainView: View { + @StateObject var guildListViewModel = GuildListViewModel() + @StateObject var guildDetailViewModel = GuildDetailViewModel() + @StateObject var cudGuildViewModel = CUDGuildViewModel() + @StateObject var guildCategoryViewModel = GuildCategoryViewModel() + @StateObject var guildChannelViewModel = GuildChannelViewModel() + + @State private var isShowCreateGuildView: Bool = false + @State private var isShowGuildModalView: Bool = false + @State private var isShowCategoryModalView: Bool = false + @State private var isShowChannelModalView: Bool = false + + @State private var needToFetchDetails: Bool = false + @State private var needToFetchGuildList: Bool = false + + var body: some View { + NavigationStack { + VStack { + HStack { + ScrollView { + VStack(alignment: .center) { + Button { + + } label: { + SecondaryActionButtonStyle(imageName: "message.fill", color: Color.colorGrayImage) + } + + Rectangle() + .frame(width: 40, height: 1) + .foregroundStyle(Color(hex: "#282930")) + .padding(.bottom, 4) + + ForEach(guildListViewModel.myGuildList, id: \.self) { guild in + Button { + guildDetailViewModel.guildId = guild.guildId + } label: { + GuildButtonStyle(name: guild.name, profileImageUrl: guild.profileImageUrl, isSelected: guildDetailViewModel.guildId == guild.guildId) + } + } + + Button { + isShowCreateGuildView.toggle() + } label: { + SecondaryActionButtonStyle(imageName: "plus", color: Color.colorGreen) + } + } + } + .padding(.leading, 4) + .padding(5) + + ZStack { + RoundedRectangle(cornerRadius: 20) + .foregroundStyle(Color.colorBG) + .frame(maxHeight: .infinity) + + VStack(alignment: .leading) { + Button { + if let guildId = guildDetailViewModel.guildId { + guildChannelViewModel.guildId = guildId + guildCategoryViewModel.guildId = guildId + } + isShowGuildModalView.toggle() + } label: { + ChannelNameButtonStyle(channelName: guildDetailViewModel.guild?.name ?? "") + } + .padding(.top, 20) + + HStack { + Button { + guildChannelViewModel.deleteChannel() + } label: { + GuildSerachButtonStyle + } + + Button { + + } label: { + GuildIconButtonStyle(imageName: "person.2.badge.plus.fill", width: 20, height: 14) + } + + Button { + + } label: { + GuildIconButtonStyle(imageName: "calendar", width: 16, height: 16) + } + } + + Divider() + + ScrollView { + let filteredChannels = guildDetailViewModel.channels.filter { + guard let categoryId = $0.categoryId else { return true } + return categoryId == "CATEGORY_ID_IS_NULL" + } + + if !filteredChannels.isEmpty { + ForEach(filteredChannels, id: \.self) { channel in + Button { + + } label: { + ChannelButtonStyle(channelName: channel.name, channelType: channel.channelType) + } + .simultaneousGesture(LongPressGesture().onEnded { _ in + if let guildId = guildDetailViewModel.guildId { + guildChannelViewModel.guildId = guildId + } + guildChannelViewModel.channelId = channel.channelId + guildChannelViewModel.name = channel.name + isShowChannelModalView = true + } + ) + } + } + + ForEach(guildDetailViewModel.categories, id: \.self) { category in + Button { + + } label: { + CategoryButtonStyle(categoryName: category.name) + } + .simultaneousGesture(LongPressGesture().onEnded { _ in + if let guildId = guildDetailViewModel.guildId { + guildCategoryViewModel.guildId = guildId + } + guildChannelViewModel.categoryId = category.categoryId + guildCategoryViewModel.categoryId = category.categoryId + guildCategoryViewModel.name = category.name + isShowCategoryModalView = true + } + ) + + let filteredChannelList = guildDetailViewModel.channels.filter({ $0.categoryId == category.categoryId }) + + if !filteredChannelList.isEmpty { + ForEach(filteredChannelList, id: \.self) { channel in + Button { + + } label: { + ChannelButtonStyle(channelName: channel.name, channelType: channel.channelType) + } + .simultaneousGesture(LongPressGesture().onEnded { _ in + if let guildId = guildDetailViewModel.guildId { + guildChannelViewModel.guildId = guildId + } + guildChannelViewModel.channelId = channel.channelId + guildChannelViewModel.categoryId = category.categoryId + guildChannelViewModel.name = channel.name + isShowChannelModalView = true + } + ) + } + } + } + } + } + .padding() + } + } + .applyGuildBackground() + .navigationBarBackButtonHidden(true) + } + .onChange(of: guildListViewModel.firstGuildId) { + guildDetailViewModel.guildId = guildListViewModel.firstGuildId + needToFetchGuildList = true + needToFetchDetails = true + } + .onChange(of: guildListViewModel.firstGuildId) { + guildDetailViewModel.guildId = guildListViewModel.firstGuildId + needToFetchDetails = true + } + .onChange(of: guildDetailViewModel.guildId) { + needToFetchDetails = true + } + .onChange(of: cudGuildViewModel.isNeedRefresh) { + needToFetchGuildList = true + needToFetchDetails = true + } + .onChange(of: guildCategoryViewModel.isNeedRefresh) { + needToFetchDetails = true + } + .onChange(of: guildChannelViewModel.isNeedRefresh) { + needToFetchDetails = true + } + .onChange(of: [needToFetchGuildList, needToFetchDetails]) { + DispatchQueue.main.async { + if needToFetchGuildList { + guildListViewModel.fetchMyGuildList() + needToFetchGuildList = false + } + + if needToFetchDetails { + guildDetailViewModel.fetchGuildDetail() + needToFetchDetails = false + } + } + } + .fullScreenCover(isPresented: $isShowCreateGuildView) { + CreateGuildView(isShowCreateGuildView: $isShowCreateGuildView) + .onDisappear { + cudGuildViewModel.reset() + needToFetchGuildList = true + needToFetchDetails = true + } + } + .sheet(isPresented: $isShowGuildModalView) { + GuildModalView(guildListViewModel: guildListViewModel, guildDetailViewModel: guildDetailViewModel, cudGuildViewModel: cudGuildViewModel, guildCategoryViewModel: guildCategoryViewModel, guildChannelViewModel: guildChannelViewModel) + .onDisappear { + if cudGuildViewModel.isDeleteGuild { + guildDetailViewModel.guildId = guildListViewModel.firstGuildId ?? "" + } + needToFetchGuildList = true + cudGuildViewModel.reset() + needToFetchDetails = true + } + } + .sheet(isPresented: $isShowCategoryModalView) { + GuildCategoryModalView(guildDetailViewModel: guildDetailViewModel, guildCategoryViewModel: guildCategoryViewModel, guildChannelViewModel: guildChannelViewModel) + .onDisappear { + guildChannelViewModel.reset() + guildCategoryViewModel.name = "" + } + } + .sheet(isPresented: $isShowChannelModalView) { + GuildChannelModalView(guildDetailViewModel: guildDetailViewModel, guildChannelViewModel: guildChannelViewModel) + .onDisappear { + guildChannelViewModel.reset() + } + } + } + .applyGuildBackground() + .navigationBarBackButtonHidden(true) + } + + // ButtonStyle - '검색하기' 버튼 스타일 + var GuildSerachButtonStyle: some View { + ZStack { + RoundedRectangle(cornerRadius: 20) + .frame(height: 32) + .foregroundStyle(Color(hex: "383A43")) + HStack { + Image(systemName: "magnifyingglass") + .resizable() + .frame(width: 18, height: 18) + .foregroundStyle(Color(hex: "#C7C8CE")) + + Text("검색하기") + .foregroundStyle(Color(hex: "#C6C7CD")) + .font(Font.pretendardSemiBold(size: 16)) + } + } + } +} + +#Preview { + GuildMainView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildModalView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildModalView.swift new file mode 100644 index 00000000..68f9b9a3 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/GuildModalView.swift @@ -0,0 +1,127 @@ +// +// GuildModalView.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +// MARK: View - 길드 모달 뷰 (편집) +struct GuildModalView: View { + @Environment(\.presentationMode) var presentation + + @ObservedObject var guildListViewModel: GuildListViewModel + @ObservedObject var guildDetailViewModel: GuildDetailViewModel + @ObservedObject var cudGuildViewModel: CUDGuildViewModel + @ObservedObject var guildCategoryViewModel: GuildCategoryViewModel + @ObservedObject var guildChannelViewModel: GuildChannelViewModel + + @State private var isShowCreateCategoryView: Bool = false + @State private var isShowCreateChannelView: Bool = false + @State private var isShowUpdateGuildView: Bool = false + + let maxLength: Int = 4 + + var body: some View { + VStack(alignment: .leading) { + HStack { + ZStack { + if let imageUrlString = guildDetailViewModel.guild?.profileImageUrl, let imageUrl = URL(string: imageUrlString) { + AsyncImage(url: imageUrl) { image in + image.image?.resizable() + .clipShape(RoundedRectangle(cornerRadius: 10)) + .frame(width: 70, height: 70) + } + } else { + RoundedRectangle(cornerRadius: 10) + .frame(width: 70, height: 70) + .foregroundStyle(Color.colorNewGuildButton) + + if let guildName = guildDetailViewModel.guild?.name { + Text(guildName.count > maxLength ? guildName.prefix(maxLength) + "..." : guildName) + .font(Font.pretendardSemiBold(size: 12)) + .foregroundStyle(Color.colorWhite) + } + } + } + Spacer() + } + + if let guildName = guildDetailViewModel.guild?.name { + Text(guildName) + .font(Font.pretendardSemiBold(size: 24)) + .foregroundStyle(Color.colorWhite) + .padding(.top, 10) + } + + Text("카테고리 및 채널") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + .padding(.top, 10) + + Button { + isShowCreateCategoryView = true + } label: { + CreateGuildButtonStyle(imageName: "", text: "카테고리 만들기", imageWidth: 0, imageHeight: 0) + } + + Button { + if let guildId = guildDetailViewModel.guildId { + guildChannelViewModel.guildId = guildId + } + isShowCreateChannelView = true + } label: { + CreateGuildButtonStyle(imageName: "", text: "채널 만들기", imageWidth: 0, imageHeight: 0) + } + + Text("길드") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + .padding(.top, 10) + + Button { + if let guildId = guildDetailViewModel.guildId { + cudGuildViewModel.guildId = guildId + } + isShowUpdateGuildView = true + } label: { + CreateGuildButtonStyle(imageName: "", text: "길드 수정하기", imageWidth: 0, imageHeight: 0) + } + + Button { + if let guildId = guildDetailViewModel.guildId { + cudGuildViewModel.guildId = guildId + cudGuildViewModel.deleteGuildDetail() + presentation.wrappedValue.dismiss() + } + } label: { + CreateGuildButtonStyle(imageName: "", text: "길드 삭제하기", imageWidth: 0, imageHeight: 0) + } + + + Spacer() + } + .applyBackground() + .padding() + .padding(.top, 20) + .fullScreenCover(isPresented: $isShowCreateCategoryView) { + CreateCategoryView(guildCategoryViewModel: guildCategoryViewModel, guildDetailViewModel: guildDetailViewModel) + .onDisappear() { + presentation.wrappedValue.dismiss() + } + } + .fullScreenCover(isPresented: $isShowCreateChannelView) { + CreateChannelView(guildChannelViewModel: guildChannelViewModel, guildDetailViewModel: guildDetailViewModel) + .onDisappear() { + presentation.wrappedValue.dismiss() + } + } + .fullScreenCover(isPresented: $isShowUpdateGuildView) { + UpdateGuildView(cudGuildViewModel: cudGuildViewModel, guildListViewModel: guildListViewModel) + .onDisappear() { + presentation.wrappedValue.dismiss() + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/UpdateChannelView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/UpdateChannelView.swift new file mode 100644 index 00000000..895fcc3b --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/UpdateChannelView.swift @@ -0,0 +1,132 @@ +// +// UpdateChannelView.swift +// asyncgate_iOS +// +// Created by kdk on 2/21/25. +// + +import SwiftUI + +// MARK: View - 채널 수정 +struct UpdateChannelView: View { + @Environment(\.dismiss) var dismiss + @ObservedObject var guildChannelViewModel: GuildChannelViewModel + @ObservedObject var guildDetailViewModel: GuildDetailViewModel + + var body: some View { + NavigationStack { + VStack(alignment: .leading) { + HStack { + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 16, weight: .bold)) + .foregroundStyle(Color.colorWhite) + } + Spacer() + + Text("채널 설정") + .font(Font.pretendardBold(size: 18)) + .foregroundColor(Color.colorWhite) + + Spacer() + + Button { + if let guildId = guildDetailViewModel.guildId { + guildChannelViewModel.guildId = guildId + guildChannelViewModel.updateChannel() + dismiss() + } + } label: { + Text("저장") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#6469A2")) + } + } + .padding(.bottom, 10) + + Divider() + .padding(.bottom, 10) + + CTextField(stepCaption: "채널 이름", placeholder: "새로운 채널", text: $guildChannelViewModel.name) + + Text("채널 주제") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $guildChannelViewModel.topic) + .foregroundColor(.white) + .padding() + .frame(height: 100) + .background(Color(hex: "#111216")) + .cornerRadius(20) + .overlay( + Group { + if guildChannelViewModel.topic.isEmpty { + Text("채널에 대한 설명을 입력하세요.") + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + + Text("카테고리") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + ScrollView(.horizontal, showsIndicators: false) { + HStack { + Button { + guildChannelViewModel.categoryId = "CATEGORY_ID_IS_NULL" + } label: { + let isSelected = guildChannelViewModel.categoryId == "CATEGORY_ID_IS_NULL" + + Text("없음") + .padding() + .font(Font.pretendardSemiBold(size: 14)) + .background( + RoundedRectangle(cornerRadius: 20) + .fill(isSelected ? Color.colorBlurple : Color.colorDart400) + ) + .foregroundStyle(Color.colorWhite) + } + + ForEach(guildDetailViewModel.categories, id: \.self) { category in + Button { + guildChannelViewModel.categoryId = category.categoryId + } label: { + let isSelected = guildChannelViewModel.categoryId == category.categoryId + + Text(category.name) + .padding() + .font(Font.pretendardSemiBold(size: 14)) + .background( + RoundedRectangle(cornerRadius: 20) + .fill(isSelected ? Color.colorBlurple : Color.colorDart400) + ) + .foregroundStyle(Color.colorWhite) + } + } + } + } + + Text("채널을 비공개로 만들면 선택한 멤버들과 역할만 이 채널을 볼 수 있어요.") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundColor(Color.colorDart400) + .multilineTextAlignment(.leading) + .padding(.top, 10) + .padding(.bottom, 10) + + CToggle(text: "비공개 채널", isPrivate: $guildChannelViewModel.isPrivate) + + Spacer() + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + } + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/UpdateGuildView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/UpdateGuildView.swift new file mode 100644 index 00000000..0f47614e --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/Guild/UpdateGuildView.swift @@ -0,0 +1,119 @@ +// +// UpdateGuildView.swift +// asyncgate_iOS +// +// Created by kdk on 2/20/25. +// + +import SwiftUI +import PhotosUI + +// MARK: View - 길드 수정 뷰 +struct UpdateGuildView: View { + @Environment(\.dismiss) var dismiss + @ObservedObject var cudGuildViewModel: CUDGuildViewModel + @ObservedObject var guildListViewModel: GuildListViewModel + + @State var selectedPhoto: PhotosPickerItem? + + var currentGuildName: String? + + var body: some View { + NavigationStack { + VStack { + HStack { + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 16, weight: .bold)) + .foregroundStyle(Color.colorWhite) + } + Spacer() + + Text("서버 수정하기") + .font(Font.pretendardBold(size: 18)) + .foregroundColor(Color.colorWhite) + + Spacer() + + Button { + cudGuildViewModel.patchGuild() + dismiss() + } label: { + Text("수정하기") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#6469A2")) + } + } + .padding(.bottom, 10) + + Divider() + .padding(.bottom, 10) + + PhotosPicker( + selection: $selectedPhoto, + matching: .images + ) { + ChoiceImageButtonStyle(image: cudGuildViewModel.profileImage) + } + + VStack(alignment: .leading) { + Text("서버 이름") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $cudGuildViewModel.name) + .foregroundColor(.white) + .padding() + .background(Color(hex: "#111216")) + .cornerRadius(20) + .overlay( + Group { + if let currentGuildName = currentGuildName { + Text(currentGuildName) + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + } + .padding(.top, 13) + .padding(.bottom, 6) + + CToggle(text: "개인용 서버 여부", isPrivate: $cudGuildViewModel.isPrivate) + .padding(.bottom, 10) + + if let errorMessage = cudGuildViewModel.errorMessage { + Text(errorMessage) + .foregroundColor(.red) + .font(Font.pretendardRegular(size: 14)) + .padding(.top, 10) + } + + Spacer() + } + .applyBackground() + } + .onChange(of: selectedPhoto) { _, newValue in + loadPhoto(from: newValue) + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + } + + // 함수 - PhotosPickerItem 타입의 이미지를 UIImage로 변경하는 함수 + private func loadPhoto(from photo: PhotosPickerItem?) { + guard let photo = photo else { return } + + photo.loadTransferable(type: Data.self) { result in + if case .success(let data) = result, let data, let image = UIImage(data: data) { + DispatchQueue.main.async { + cudGuildViewModel.profileImage = image + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/NotificationView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/NotificationView.swift new file mode 100644 index 00000000..8d32fbd8 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/NotificationView.swift @@ -0,0 +1,52 @@ +// +// NotificationView.swift +// asyncgate_iOS +// +// Created by kdk on 2/7/25. +// + +import SwiftUI + +// FIXME: UI만 만들어놓음 +struct NotificationView: View { + + var body: some View { + VStack { + HStack { + Text("알림") + .foregroundStyle(Color.colorWhite) + .font(Font.pretendardBold(size: 20)) + + Spacer() + + Button { + + } label: { + Image(systemName: "ellipsis.circle") + .resizable() + .frame(width: 30, height: 30) + } + } + + Spacer() + + Text("아직 아무것도 없어요") + .foregroundStyle(Color.colorWhite) + .font(Font.pretendardBold(size: 18)) + .padding(.bottom, 10) + + Text("나중에 돌아와서 이벤트, 스트림 등의 알림을 확인하세요.") + .foregroundStyle(Color.colorWhite) + .font(Font.pretendardRegular(size: 16)) + + Spacer() + + } + .padding(15) + .applyBackground() + } +} + +#Preview { + NotificationView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/AuthEmailCodeView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/AuthEmailCodeView.swift new file mode 100644 index 00000000..840fa66f --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/AuthEmailCodeView.swift @@ -0,0 +1,55 @@ +// +// AuthEmailCodeView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 이메일 인증 코드 확인 View +struct AuthEmailCodeView: View { + @ObservedObject var signUpViewModel: SignUpViewModel + @StateObject var authEmailCodeViewModel = AuthEmailCodeViewModel() + + var body: some View { + VStack { + Text("이메일로 전송받은 인증 코드를 입력하세요") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + .multilineTextAlignment(.center) + + SignTextField(stepCaption: "인증 코드", placeholder: "", text: $authEmailCodeViewModel.authenticationCode) + .padding(.top, 24) + .padding(.bottom, 30) + + Button { + authEmailCodeViewModel.email = signUpViewModel.email + authEmailCodeViewModel.isEmailCodeMatched() + } label: { + SignButtonStyle(text: "확인") + } + + if authEmailCodeViewModel.isEmailCodeAuthenticated { + Text("이메일 인증되었습니다.") + .font(Font.pretendardBold(size: 14)) + .foregroundColor(Color.colorGreen) + + } else if let errorMessage = authEmailCodeViewModel.errorMessage { + Text(errorMessage) + .font(Font.pretendardBold(size: 14)) + .foregroundColor(Color.colorRed) + } + + Spacer() + } + .padding(15) + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + .fullScreenCover(isPresented: $authEmailCodeViewModel.isEmailCodeAuthenticated) { + SignInView() + } + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignBirthView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignBirthView.swift new file mode 100644 index 00000000..bb38e76e --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignBirthView.swift @@ -0,0 +1,52 @@ +// +// SignBirthView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 회원가입 - 생년월일 설정 View +struct SignBirthView: View { + @ObservedObject var signUpViewModel: SignUpViewModel + var date: Date = Date() + + var body: some View { + VStack { + Text("몇 살이신가요?") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + + SignTextField(stepCaption: "생년월일", placeholder: formattedDate, text: $signUpViewModel.birth) + .padding(.top, 24) + .padding(.bottom, 30) + + Button { + signUpViewModel.signUpUser() + } label: { + SignButtonStyle(text: "계정 만들기") + } + + if let errorMessage = signUpViewModel.errorMessage { + Text(errorMessage) + .foregroundColor(.red) + } + + Spacer() + } + .padding(15) + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + .navigationDestination(isPresented: $signUpViewModel.isVerificationCodeRequested) { + AuthEmailCodeView(signUpViewModel: signUpViewModel) + } + } + + var formattedDate: String { + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter.string(from: date) + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignInView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignInView.swift new file mode 100644 index 00000000..68155dac --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignInView.swift @@ -0,0 +1,81 @@ +// +// SignInView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 로그인 화면 +struct SignInView: View { + @StateObject var signInViewModel = SignInViewModel() + + var body: some View { + VStack { + Text("돌아오신 것을 환영해요!") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + .padding(.top, 10) + .padding(.bottom, 5) + + Text("다시 만나다니 너무 반가워요!") + .font(Font.pretendardBold(size: 16)) + .foregroundColor(Color.colorWhite) + + VStack(alignment: .leading) { + Text("계정 정보") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $signInViewModel.email) + .keyboardType(.emailAddress) + .foregroundColor(.white) + .padding() + .background(Color.colorDart500) + .cornerRadius(4) + .overlay( + Group { + if signInViewModel.email.isEmpty { + Text("이메일") + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + } + + PasswordField(password: $signInViewModel.password) + .padding(.bottom, 30) + + Button { + signInViewModel.signInUser() + } label: { + SignButtonStyle(text: "로그인") + } + .navigationDestination(isPresented: $signInViewModel.isSignInSuccess) { + ContentView() + } + + if let message = signInViewModel.errorMessage { + Text(message) + .font(Font.pretendardBold(size: 14)) + .foregroundColor(Color.colorRed) + } + + Spacer() + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + .fullScreenCover(isPresented: $signInViewModel.isSignInSuccess) { + ContentView() + } + } +} + +#Preview { + SignInView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignMainView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignMainView.swift new file mode 100644 index 00000000..3eb38e5f --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignMainView.swift @@ -0,0 +1,56 @@ +// +// SignMainView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 디스코드 초기 접속 View +struct SignMainView: View { + + var body: some View { + NavigationStack { + VStack(alignment: .center) { + Spacer() + + Image("DiscordLogo") + .resizable() + .frame(width: 85, height: 65) + .padding(.bottom, 27) + + Text("ASYNCGATE에 오신 걸 환영합니다") + .foregroundStyle(Color.colorWhite) + .font(Font.pretendardBold(size: 30)) + .multilineTextAlignment(.center) + .padding(.bottom, 9) + + Text("어울리고, 게임하고, 가볍게 대화하세요. 아래를 탭해 시작해요!") + .foregroundStyle(Color.colorWhite) + .font(Font.pretendardSemiBold(size: 18)) + .multilineTextAlignment(.center) + + Spacer() + + VStack { + NavigationLink(destination: SignUpView()) { + UsingButtonStyle(text: "가입하기", backgroundColor: Color.colorWhite, textColor: Color.colorBlack, size: 15) + } + .padding(.bottom, 13) + + NavigationLink(destination: SignInView()) { + UsingButtonStyle(text: "로그인", backgroundColor: Color.colorBlurple, textColor: Color.colorWhite, size: 15) + } + } + .padding(.bottom, 25) + } + .padding(30) + .applyBackground() + } + } +} + +#Preview { + SignMainView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpEmailView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpEmailView.swift new file mode 100644 index 00000000..5e9fbd40 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpEmailView.swift @@ -0,0 +1,64 @@ +// +// SignUpEmailView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 회원가입 - 이메일 설정 View +struct SignUpEmailView: View { + @ObservedObject var signUpViewModel: SignUpViewModel + + var body: some View { + VStack { + Text("이메일 주소를 입력하세요") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + + VStack(alignment: .leading) { + Text("이메일") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $signUpViewModel.email) + .keyboardType(.emailAddress) + .foregroundColor(.white) + .padding() + .background(Color.colorDart500) + .cornerRadius(4) + .overlay( + Group { + if signUpViewModel.email.isEmpty { + Text("이메일") + .foregroundStyle(Color.colorDart400) + .padding(.leading, 15) + } + } + , alignment: .leading + ) + + if let meesage = signUpViewModel.emailRequestMessage { + Text(meesage) + .font(Font.pretendardBold(size: 13)) + .foregroundColor(Color.colorRed) + } + } + .padding(.top, 24) + .padding(.bottom, 30) + + Button { + signUpViewModel.isDuplicatedEmail() + } label: { + SignButtonStyle(text: "다음") + } + .navigationDestination(isPresented: $signUpViewModel.isNotEmailDuplicated) { + SignUpNickNameView(signUpViewModel: signUpViewModel) + } + + Spacer() + } + .padding(15) + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpNameAndPasswordView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpNameAndPasswordView.swift new file mode 100644 index 00000000..91c91d30 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpNameAndPasswordView.swift @@ -0,0 +1,44 @@ +// +// SignUpNameAndPasswordView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 회원가입 - 사용자명 및 비밀번호 설정 View +struct SignUpNameAndPasswordView: View { + @ObservedObject var signUpViewModel: SignUpViewModel + + var body: some View { + VStack { + Text("이제 계정을 만들어보세요") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + + SignTextField(stepCaption: "사용자명", placeholder: "", text: $signUpViewModel.name) + .padding(.top, 24) + .padding(.bottom, 10) + + VStack(alignment: .leading) { + Text("비밀번호") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + PasswordField(password: $signUpViewModel.passWord) + } + .padding(.bottom, 30) + + NavigationLink(destination: SignBirthView(signUpViewModel: signUpViewModel)) { + SignButtonStyle(text: "다음") + } + + Spacer() + } + .padding(15) + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpNickNameView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpNickNameView.swift new file mode 100644 index 00000000..06f9cdd3 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpNickNameView.swift @@ -0,0 +1,35 @@ +// +// SignUpNickNameView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 회원가입 - 닉네임 설정 View +struct SignUpNickNameView: View { + @ObservedObject var signUpViewModel: SignUpViewModel + + var body: some View { + VStack { + Text("이름은 무엇인가요?") + .font(Font.pretendardBold(size: 28)) + .foregroundColor(Color.colorWhite) + + SignTextField(stepCaption: "별명", placeholder: "", text: $signUpViewModel.nickName) + .padding(.top, 24) + .padding(.bottom, 30) + + NavigationLink(destination: SignUpNameAndPasswordView(signUpViewModel: signUpViewModel)) { + SignButtonStyle(text: "다음") + } + + Spacer() + } + .padding(15) + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpView.swift new file mode 100644 index 00000000..03913b98 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/SignUpAndSignInViews/SignUpView.swift @@ -0,0 +1,26 @@ +// +// SignUpView.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: View - 회원가입 Main View +struct SignUpView: View { + @StateObject var signUpViewModel = SignUpViewModel() + + var body: some View { + NavigationStack { + SignUpEmailView(signUpViewModel: signUpViewModel) + .applyBackground() + .navigationBarBackButtonHidden(true) + .navigationBarItems(leading: BackButton(color: .white)) + } + } +} + +#Preview { + SignUpView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/User/UpdateUserInfoView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/User/UpdateUserInfoView.swift new file mode 100644 index 00000000..74b47c23 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/User/UpdateUserInfoView.swift @@ -0,0 +1,128 @@ +// +// UpdateUserInfoView.swift +// asyncgate_iOS +// +// Created by kdk on 2/17/25. +// + +import SwiftUI +import PhotosUI + +// MARK: View - 프로필 수정 뷰 +struct UpdateUserInfoView: View { + @Environment(\.dismiss) var dismiss + @StateObject var userInfoViewModel = UserInfoViewModel() + @State var selectedPhoto: PhotosPickerItem? + + var body: some View { + NavigationStack { + VStack { + HStack { + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 16, weight: .bold)) + .foregroundStyle(Color.colorWhite) + } + Spacer() + + Text("프로필 수정하기") + .font(Font.pretendardBold(size: 18)) + .foregroundColor(Color.colorWhite) + + Spacer() + + Button { + userInfoViewModel.updateUserInfos() + dismiss() + } label: { + Text("수정하기") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#6469A2")) + } + } + .padding(.bottom, 10) + + Divider() + .padding(.bottom, 20) + + PhotosPicker( + selection: $selectedPhoto, + matching: .images + ) { + ChoiceImageButtonStyle(image: userInfoViewModel.profileImage) + } + + VStack(alignment: .leading) { + Text("이름") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + + TextField("", text: $userInfoViewModel.name) + .foregroundColor(.white) + .padding() + .background(Color(hex: "#111216")) + .cornerRadius(20) + + Text("닉네임") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundColor(Color.colorDart400) + .padding(.top, 13) + + TextField("", text: $userInfoViewModel.nickName) + .foregroundColor(.white) + .padding() + .background(Color(hex: "#111216")) + .cornerRadius(20) + } + .padding(.top, 13) + .padding(.bottom, 6) + + Spacer() + + Button { + userInfoViewModel.deleteUserInfo() + dismiss() + } label: { + VStack { + Text("탈퇴하기") + .font(Font.pretendardSemiBold(size: 16)) + .foregroundStyle(Color(hex: "#6469A2")) + .padding() + + Text("누르면 바로 탈퇴되니 주의하세요.") + .font(Font.pretendardSemiBold(size: 14)) + .foregroundStyle(Color.colorDart400) + } + } + + Spacer() + } + .applyBackground() + } + .onChange(of: selectedPhoto) { _, newValue in + loadPhoto(from: newValue) + } + .padding() + .applyBackground() + .navigationBarBackButtonHidden(true) + } + + // 함수 - PhotosPickerItem 타입의 이미지를 UIImage로 변경하는 함수 + private func loadPhoto(from photo: PhotosPickerItem?) { + guard let photo = photo else { return } + + photo.loadTransferable(type: Data.self) { result in + if case .success(let data) = result, let data, let image = UIImage(data: data) { + DispatchQueue.main.async { + userInfoViewModel.profileImage = image + } + } + } + } +} + +#Preview { + UpdateUserInfoView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/View/User/UserInfoView.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/View/User/UserInfoView.swift new file mode 100644 index 00000000..c701968e --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/View/User/UserInfoView.swift @@ -0,0 +1,53 @@ +// +// UserInfoView.swift +// asyncgate_iOS +// +// Created by kdk on 2/20/25. +// + +import SwiftUI + +struct UserInfoView: View { + @State private var isEditProfile: Bool = false + + var body: some View { + VStack(alignment: .leading) { + profileImage + + Button { + isEditProfile.toggle() + } label: { + UsingButtonStyle(text: "프로필 편집하기", backgroundColor: Color.colorBlurple, textColor: Color.colorWhite, size: 14) + } + + Spacer() + } + .padding() + .applyBackground() + .fullScreenCover(isPresented: $isEditProfile) { + UpdateUserInfoView() + } + } + + var profileImage: some View { + ZStack { + Circle() + .stroke( + Color.colorGray, + style: StrokeStyle(lineWidth: 2, dash: [6, 8]) + ) + .foregroundStyle(Color.colorBG) + .frame(width: 100, height: 100) + .padding(.bottom, 10) + + Image(systemName: "person.fill") + .resizable() + .frame(width: 50, height: 50) + .foregroundStyle(Color.colorWhite) + } + } +} + +#Preview { + UserInfoView() +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/ChatViewModels/ChatViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/ChatViewModels/ChatViewModel.swift new file mode 100644 index 00000000..4653b094 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/ChatViewModels/ChatViewModel.swift @@ -0,0 +1,31 @@ +// +// ChatViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 3/9/25. +// + +import SwiftUI + +class ChatViewModel: ObservableObject { + @Published var messages: [ChatMessage] = [] + @Published var channelId: String = "" + + func getMessages() { + ChattingManager.shared.getChattingList(page: 10, size: 10, channelId: "7e27f7c8-581d-4001-a684-a58e953b3e26") { result in + switch result { + case .success(let value): + value.result.directMessages.forEach { oneMessage in + print("oneMessage \(oneMessage)") + DispatchQueue.main.async { + self.messages.append(oneMessage.toChatMeassage()) + print("susususususus") + } + } + + case .failure(let error): + print("ChatViewModel - getMessages() - 에러 발생 \(error)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/CUDGuildViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/CUDGuildViewModel.swift new file mode 100644 index 00000000..c2cb9b49 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/CUDGuildViewModel.swift @@ -0,0 +1,102 @@ +// +// CUDGuildViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +// MARK: ViewModel - 길드 CUD +class CUDGuildViewModel: ObservableObject { + // Request 변수 + @Published var name: String = "" + @Published var isPrivate: Bool = true + @Published var profileImage: UIImage? + + @Published var errorMessage: String? + + @Published var isNeedRefresh: Bool = false + @Published var isDeleteGuild: Bool = false + @Published var isNeedRefreshAll: Bool = false + + + @Published var guildId: String = "" + + // 변수 초기화 + func reset() { + self.name = "" + self.isPrivate = true + self.profileImage = nil + self.errorMessage = nil + self.isNeedRefresh = false + self.isNeedRefreshAll = false + self.isDeleteGuild = false + } + + // MARK: 함수 - 길드 생성하기 + func createGuild() { + GuildServiceAPIManager.shared.createGuild(name: name, isPrivate: isPrivate, profileImage: profileImage) { result in + switch result { + case .success(let successResponse): + DispatchQueue.main.async { + self.errorMessage = nil + self.isNeedRefresh = true + self.isNeedRefreshAll = true + } + self.reset() + + print("CreateGuildViewModel - createGuild() - 길드 생성 성공 \(successResponse)") + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = "길드를 생성하지 못했습니다." + } + print("CreateGuildViewModel - createGuild() - 에러 발생 \(errorResponse)") + } + } + } + + // MARK: 함수 - 길드 수정하기 + func patchGuild() { + GuildServiceAPIManager.shared.updateGuild(guildId: guildId, name: name, isPrivate: isPrivate, profileImage: profileImage) { result in + switch result { + case .success(let successResponse): + DispatchQueue.main.async { + self.errorMessage = nil + self.isNeedRefreshAll = true + } + self.reset() + + print("CreateGuildViewModel - patchGuild() - 길드 수정 성공 \(successResponse)") + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = "길드 수정을 실패했습니다." + } + print("CreateGuildViewModel - patchGuild() - 에러 발생 \(errorResponse)") + } + } + } + + // MARK: 함수 - 길드 삭제하기 + func deleteGuildDetail() { + GuildServiceAPIManager.shared.deleteGuild(guildId: guildId) { result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isNeedRefresh = true + self.isDeleteGuild = true + } + self.reset() + print("GuildDetailViewModel - deleteGuildDetail() - 길드 삭제 성공") + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildDetailViewModel - deleteGuildDetail() - 에러 발생: \(errorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildCategoryViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildCategoryViewModel.swift new file mode 100644 index 00000000..dd94f88c --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildCategoryViewModel.swift @@ -0,0 +1,74 @@ +// +// GuildCategoryViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import SwiftUI + +// MARK: ViewModel - 길드 카테고리 +class GuildCategoryViewModel: ObservableObject { + @Published var name: String = "새로운 카테고리" + @Published var isPrivate: Bool = false + @Published var guildId: String? + + @Published var categoryId: String = "" + + @Published var isNeedRefresh: Bool = false + + @Published var errorMessage: String? + + // 초기화 + func reset() { + self.name = "새로운 카테고리" + self.isPrivate = false + self.guildId = nil + self.errorMessage = nil + self.isNeedRefresh = false + } + + // MARK: 함수 - 카테고리 생성 + func createCategory() { + if let guildId = guildId { + CategoryGuildServiceAPIManager.shared.createGuildCategory(name: name, guildId: guildId, isPrivate: isPrivate) { + result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isNeedRefresh = true + } + self.reset() + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildDetailViewModel - fetchGuildDetail() - 에러 발생: \(errorResponse)") + } + } + } + } + + // MARK: 함수 - 카테고리 삭제 + func deleteCategory() { + if let guildId = guildId { + CategoryGuildServiceAPIManager.shared.deleteGuildCategory(guildId: guildId, categoryId: categoryId) { + result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isNeedRefresh = true + } + self.reset() + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildDetailViewModel - deleteCategory() - 에러 발생: \(errorResponse)") + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildChannelViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildChannelViewModel.swift new file mode 100644 index 00000000..a355d6a2 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildChannelViewModel.swift @@ -0,0 +1,104 @@ +// +// GuildChannelViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/19/25. +// + +import SwiftUI + +// MARK: ViewModel - 길드 채널 +class GuildChannelViewModel: ObservableObject { + @Published var name: String = "새로운 채널" + @Published var guildId: String = "" + @Published var categoryId: String = "" + @Published var channelType: String = "TEXT" + @Published var isPrivate: Bool = false + + @Published var channelId: String = "" + @Published var topic: String = "" + + @Published var isNeedRefresh: Bool = false + + @Published var errorMessage: String? + + func reset() { + self.name = "새로운 채널" + self.guildId = "" + self.categoryId = "" + self.channelType = "TEXT" + self.isPrivate = false + self.isNeedRefresh = false + self.channelId = "" + self.topic = "" + } + + init() { + self.categoryId = "2715874a-858d-4cfb-b169-eadf8a223062" + self.guildId = "" + self.channelId = "1c71b065-f497-46d6-8416-80f8e636769e" + self.topic = "test" + self.name = "스윗" + } + + // MARK: 함수 - 새로운 채널 생성 + func createChannel() { + ChannelGuildServiceAPIManager.shared.createGuildChannel(name: name, guildId: guildId, categoryId: categoryId, channelType: channelType, isPrivate: isPrivate) { + result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isNeedRefresh = true + } + self.reset() + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.isNeedRefresh = false + self.errorMessage = errorResponse.localizedDescription + } + print("GuildChannelViewModel - createChannel() - 에러 발생: \(errorResponse)") + } + } + } + + // MARK: 함수 - 채널 수정 + func updateChannel() { + ChannelGuildServiceAPIManager.shared.updateGuildChannel(guildId: guildId, categoryId: categoryId, channelId: channelId, name: name, topic: topic, isPrivate: isPrivate) { + result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isNeedRefresh = true + } + self.reset() + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildChannelViewModel - updateChannel() - 에러 발생: \(errorResponse)") + } + } + } + + // MARK: 함수 - 채널 삭제 + func deleteChannel() { + ChannelGuildServiceAPIManager.shared.deleteGuildChannel(guildId: guildId, categoryId: categoryId, channelId: channelId) { + result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isNeedRefresh = true + } + self.reset() + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildChannelViewModel - deleteChannel() - 에러 발생: \(errorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildDetailViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildDetailViewModel.swift new file mode 100644 index 00000000..c632843c --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildDetailViewModel.swift @@ -0,0 +1,41 @@ +// +// GuildDetailViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +// MARK: ViewModel - 길드 세부 정보 (카테고리, 채널 포함) +class GuildDetailViewModel: ObservableObject { + @Published var guild: GuildInfo? + @Published var categories: [GuildCategory] = [] + @Published var channels: [GuildChannel] = [] + + @Published var guildId: String? + + @Published var errorMessage: String? + + // MARK: 함수 - 길드 세부 정보 불러오기 + func fetchGuildDetail() { + if let guildId = guildId { + GuildServiceAPIManager.shared.fetchGuildInfo(guildId: guildId) { result in + switch result { + case .success(let susscessResponse): + DispatchQueue.main.async { + self.guild = susscessResponse.result.guild + self.categories = susscessResponse.result.categories + self.channels = susscessResponse.result.channels + } + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildDetailViewModel - fetchGuildDetail() - 에러 발생: \(errorResponse)") + } + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildListViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildListViewModel.swift new file mode 100644 index 00000000..1a8d1413 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/GuildViewModels/GuildListViewModel.swift @@ -0,0 +1,42 @@ +// +// GuildListViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +// MARK: ViewModel - 내 길드 목록 +class GuildListViewModel: ObservableObject { + @Published var myGuildList: [GuildInList] = [] + + @Published var firstGuildId: String? + + @Published var errorMessage: String? + + init() { + fetchMyGuildList() + } + + // MARK: 함수 - 내 길드 목록 조회하기 + func fetchMyGuildList() { + GuildServiceAPIManager.shared.loadMyGuildList() { result in + switch result { + case .success(let successResponse): + DispatchQueue.main.async { + self.myGuildList = successResponse.result.responses + if let firstGuildId = self.myGuildList.first { + self.firstGuildId = firstGuildId.guildId + } + } + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.localizedDescription + } + print("GuildListViewModel - fetchMyGuildList() - 에러 발생 \(errorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/AccessTokenViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/AccessTokenViewModel.swift new file mode 100644 index 00000000..287b3c1a --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/AccessTokenViewModel.swift @@ -0,0 +1,61 @@ +// +// AuthenticationViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import KeychainAccess +import SwiftUI + +// MARK: ViewModel - 엑세스 토큰을 KeyChain으로 관리 +class AccessTokenViewModel: ObservableObject { + static let shared = AccessTokenViewModel() + + @Published var accessToken: String? + + private let bundleId: String + let keychain: Keychain + + private init() { + self.bundleId = Config.shared.bundleId + self.keychain = Keychain(service: self.bundleId) + + loadToken() + } + + // MARK: 함수 - 엑세스 토큰 KeyChain에 저장 + func saveToken(_ token: String) { + do { + try keychain.set(token, key: "accessToken") + self.accessToken = token + + } catch { + print("AccessTokenViewModel - Keychain save 에러: \(error)") + } + } + + // MARK: 함수 - 엑세스 토큰 가져오기 + func loadToken() { + do { + if let token = try keychain.getString("accessToken") { + self.accessToken = token + } + + } catch { + print("AccessTokenViewModel - Keychain load 에러: \(error)") + self.accessToken = nil + } + } + + // MARK: 함수 - 엑세스 토큰 삭제 + func deleteToken() { + do { + try keychain.remove("accessToken") + self.accessToken = nil + + } catch { + print("AccessTokenViewModel - Keychain delete 에러: \(error)") + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/AuthEmailCodeViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/AuthEmailCodeViewModel.swift new file mode 100644 index 00000000..c7b5834b --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/AuthEmailCodeViewModel.swift @@ -0,0 +1,43 @@ +// +// AuthEmailCodeViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/17/25. +// + +import SwiftUI + +// MARK: ViewModel - 이메일 인증 +class AuthEmailCodeViewModel: ObservableObject { + // Request 변수 - 이메일, 인증코드 + @Published var email: String = "" + @Published var authenticationCode: String = "" + + // Response 변수 - 에러 메시지(String?), 인증코드 일치여부 확인(Bool) + @Published var errorMessage: String? + @Published var isEmailCodeAuthenticated: Bool = false + + // MARK: 함수 - 이메일 인증코드 일치 여부 확인 + func isEmailCodeMatched() { + UserServiceAPIManager.shared.authEmailCode(email: email, authenticationCode: authenticationCode) { result in + switch result { + case .success(let response): + if (200...299).contains(response.httpStatus) { + DispatchQueue.main.async { + self.isEmailCodeAuthenticated = true + } + } else { + DispatchQueue.main.async { + self.errorMessage = response.message + } + } + + case .failure(let SignUpErrorResponse): + DispatchQueue.main.async { + self.errorMessage = SignUpErrorResponse.error + } + } + } + } +} + diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/HealthViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/HealthViewModel.swift new file mode 100644 index 00000000..0a737d74 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/HealthViewModel.swift @@ -0,0 +1,41 @@ +// +// HealthViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/18/25. +// + +import SwiftUI + +// MARK: ViewModel - 길드 생성 +class HealthViewModel: ObservableObject { + // Request 변수 + @Published var httpStatus: Int = 0 + @Published var message: String = "" + @Published var time: String = "" + @Published var result: String = "" + + @Published var errorMessage: String = "" + + func checkHealth() { + UserServiceAPIManager.shared.health { result in + switch result { + case .success(let successResponse): + DispatchQueue.main.async { + self.httpStatus = successResponse.httpStatus + self.message = successResponse.message + self.time = successResponse.time + self.result = successResponse.result + } + + print("HealthViewModel - checkHealth() - 서버 연결 성공 \(successResponse)") + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = "\(errorResponse)" + } + print("HealthViewModel - checkHealth() - 에러 발생 \(errorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/SignInViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/SignInViewModel.swift new file mode 100644 index 00000000..6cc55605 --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/SignInViewModel.swift @@ -0,0 +1,51 @@ +// +// SignInViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: ViewModel - 로그인 +class SignInViewModel: ObservableObject { + // Request 변수 + @Published var email: String = "" + @Published var password: String = "" + + // Response 변수 + @Published var errorMessage: String? + + @Published var isSignInSuccess: Bool = false + + // ViewModel - 엑세스 토큰 + private let auth = AccessTokenViewModel.shared + + // MARK: 함수 - 로그인 시도 + func signInUser() { + UserServiceAPIManager.shared.signIn(email: email, passWord: password) { result in + switch result { + case .success(let signInResponse): + if (200...299).contains(signInResponse.httpStatus) { + DispatchQueue.main.async { + self.isSignInSuccess = true + if let accessToken = signInResponse.result?.accessToken { + self.auth.saveToken(accessToken) + self.isSignInSuccess = true + } + } + } else { + DispatchQueue.main.async { + self.errorMessage = signInResponse.message + } + } + + case .failure(let signInErrorResponse): + DispatchQueue.main.async { + self.errorMessage = signInErrorResponse.error + } + print("SignInViewModel - signInUser() error : \(signInErrorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/SignUpViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/SignUpViewModel.swift new file mode 100644 index 00000000..df8427dd --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/SignUpViewModel.swift @@ -0,0 +1,69 @@ +// +// SignUpViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/5/25. +// + +import SwiftUI + +// MARK: ViewModel - 회원가입 +class SignUpViewModel: ObservableObject { + // Request 변수 - 회원가입용 + @Published var email: String = "" + @Published var passWord: String = "" + @Published var name: String = "" + @Published var nickName: String = "" + @Published var birth: String = "" + + // Response 변수 + @Published var errorMessage: String? + @Published var emailRequestMessage: String? + @Published var isVerificationCodeRequested: Bool = false + @Published var isNotEmailDuplicated: Bool = false + + + // MARK: 함수 - 회원가입 진행 + func signUpUser() { + UserServiceAPIManager.shared.signUp(email: email, passWord: passWord, name: name, nickName: nickName, birth: birth) { result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isVerificationCodeRequested = true + self.emailRequestMessage = "인증번호가 발송되었습니다." + } + + case .failure(let signUpErrorResponse): + DispatchQueue.main.async { + self.errorMessage = signUpErrorResponse.error + } + print("SignUpViewModel - signUpUser() error : \(signUpErrorResponse)") + } + } + } + + // MARK: 함수 - 이메일 중복 여부 확인 + func isDuplicatedEmail() { + UserServiceAPIManager.shared.checkDuplicatedEmail(email: email) { result in + switch result { + case .success(let checkDuplicatedEmailResponse): + if checkDuplicatedEmailResponse.result.isDuplicate { + DispatchQueue.main.async { + self.isNotEmailDuplicated = false + } + } else { + DispatchQueue.main.async { + self.isNotEmailDuplicated = true + self.emailRequestMessage = "중복된 이메일입니다." + } + } + + case .failure(let signUpErrorResponse): + DispatchQueue.main.async { + self.errorMessage = signUpErrorResponse.error + } + print("SignUpViewModel - isDuplicatedEmail() error : \(signUpErrorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/UserInfoViewModel.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/UserInfoViewModel.swift new file mode 100644 index 00000000..52a0c2cc --- /dev/null +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/ViewModel/UserViewModels/UserInfoViewModel.swift @@ -0,0 +1,58 @@ +// +// UserInfoViewModel.swift +// asyncgate_iOS +// +// Created by kdk on 2/17/25. +// + +import SwiftUI + +// MARK: ViewModel - 유저 정보 +class UserInfoViewModel: ObservableObject { + // Request 변수 + @Published var name: String = "" + @Published var nickName: String = "" + @Published var profileImage: UIImage? + + // Response 변수 + @Published var errorMessage: String? + @Published var isUpdateUserInfo: Bool = false + + // ViewModel - 엑세스 토큰 + private let auth = AccessTokenViewModel.shared + + // MARK: 함수 - 유저 정보 업데이트 + func updateUserInfos() { + UserServiceAPIManager.shared.updateUserInfo(name: name, nickName: nickName, profileImage: profileImage) { result in + switch result { + case .success(_): + DispatchQueue.main.async { + self.isUpdateUserInfo = true + } + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.error + } + print("UpdateUserInfoViewModel - updateUserInfos() error : \(errorResponse)") + } + } + } + + // MARK: 함수 - 회원 탈퇴 + func deleteUserInfo() { + UserServiceAPIManager.shared.deleteUser() { result in + switch result { + case .success(_): + print("UpdateUserInfoViewModel - updateUserInfos() 탈퇴 성공") + self.auth.deleteToken() + + case .failure(let errorResponse): + DispatchQueue.main.async { + self.errorMessage = errorResponse.error + } + print("UpdateUserInfoViewModel - deleteUserInfo() error : \(errorResponse)") + } + } + } +} diff --git a/src/ios/asyncgate_iOS/asyncgate_iOS/asyncgate_iOSApp.swift b/src/ios/asyncgate_iOS/asyncgate_iOS/asyncgate_iOSApp.swift index 84a8043c..aec4a0f7 100644 --- a/src/ios/asyncgate_iOS/asyncgate_iOS/asyncgate_iOSApp.swift +++ b/src/ios/asyncgate_iOS/asyncgate_iOS/asyncgate_iOSApp.swift @@ -9,9 +9,15 @@ import SwiftUI @main struct asyncgate_iOSApp: App { + private let accessTokenViewModel = AccessTokenViewModel.shared + var body: some Scene { WindowGroup { - ContentView() + if accessTokenViewModel.accessToken != nil { + GuildMainView() + } else { + SignMainView() + } } } }