@fountispanel/connect-react-native 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/README.md +7 -6
  3. package/android/build.gradle +35 -16
  4. package/android/src/main/AndroidManifest.xml +5 -16
  5. package/build/index.js +1 -126
  6. package/build/index.web.js +1 -57
  7. package/ios/FountisConnect.xcframework/Info.plist +44 -0
  8. package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/engine.html +5 -5
  9. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/FountisConnect +0 -0
  10. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Info.plist +53 -0
  11. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  12. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftinterface +48 -0
  13. package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/engine.html +5 -5
  14. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/FountisConnect +0 -0
  15. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Info.plist +49 -0
  16. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  17. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftinterface +48 -0
  18. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  19. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +48 -0
  20. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/PrivacyInfo.xcprivacy +23 -0
  21. package/ios/FountisConnectAppDelegateSubscriber.swift +3 -0
  22. package/ios/FountisConnectModule.swift +3 -0
  23. package/ios/FountisConnectReactNative.podspec +27 -6
  24. package/package.json +14 -12
  25. package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +0 -161
  26. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +0 -616
  27. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +0 -321
  28. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +0 -143
  29. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +0 -167
  30. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +0 -128
  31. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +0 -109
  32. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +0 -74
  33. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +0 -45
  34. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +0 -72
  35. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +0 -12
  36. package/android/connect-sdk/main/res/values/fountis_styles.xml +0 -13
  37. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +0 -12
  38. package/build/types.js +0 -1
  39. package/ios/FountisConnectBundle.swift +0 -15
  40. package/ios/FountisConnectSDK/ApiClient.swift +0 -113
  41. package/ios/FountisConnectSDK/FountisConnect.swift +0 -436
  42. package/ios/FountisConnectSDK/LocalState.swift +0 -81
  43. package/ios/FountisConnectSDK/Matcher.swift +0 -102
  44. package/ios/FountisConnectSDK/Models.swift +0 -116
  45. package/ios/FountisConnectSDK/Notifier.swift +0 -63
  46. package/ios/FountisConnectSDK/RequestDeadline.swift +0 -93
  47. package/ios/FountisConnectSDK/SheetController.swift +0 -259
  48. package/ios/FountisConnectSDK/Strings.swift +0 -34
  49. package/ios/FountisConnectSDK/TokenProviderCall.swift +0 -91
  50. package/scripts/vendor-native.sh +0 -16
  51. package/src/index.ts +0 -142
  52. package/src/index.web.ts +0 -64
  53. package/src/types.ts +0 -26
  54. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/ar.json +0 -0
  55. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/en.json +0 -0
  56. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/kmr.json +0 -0
  57. /package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/ku.json +0 -0
  58. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/PrivacyInfo.xcprivacy +0 -0
  59. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/ar.json +0 -0
  60. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/en.json +0 -0
  61. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/kmr.json +0 -0
  62. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/ku.json +0 -0
@@ -1,116 +0,0 @@
1
- import Foundation
2
- import os
3
-
4
- let fcLog = Logger(subsystem: "org.fountis.connect", category: "sdk")
5
-
6
- /// What `show()` returns. Every failure is `.noFill`.
7
- public enum FountisResult: Equatable, Sendable {
8
- /// Nothing to show (no matching study, no consent, no token, network trouble, nowhere to present).
9
- case noFill
10
- /// The person closed the study before finishing it, or was screened out / the study filled up.
11
- case dismissed
12
- /// The person finished the study.
13
- case completed
14
- }
15
-
16
- /// Anonymous lifecycle event for the host app (`onEvent`). Carries no titles, topics or answers.
17
- public struct FountisEvent: Sendable {
18
- /// `shown`, `dismissed`, `completed`, `noFill`, `notified`
19
- public let type: String
20
- public let offerId: String?
21
- }
22
-
23
- /// Minimal Codable JSON value (for portable conditions and pass-through).
24
- enum JSONValue: Codable, Equatable {
25
- case string(String), number(Double), bool(Bool), array([JSONValue]), object([String: JSONValue]), null
26
-
27
- init(from decoder: Decoder) throws {
28
- let c = try decoder.singleValueContainer()
29
- if c.decodeNil() { self = .null }
30
- else if let b = try? c.decode(Bool.self) { self = .bool(b) }
31
- else if let n = try? c.decode(Double.self) { self = .number(n) }
32
- else if let s = try? c.decode(String.self) { self = .string(s) }
33
- else if let a = try? c.decode([JSONValue].self) { self = .array(a) }
34
- else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }
35
- else { self = .null }
36
- }
37
-
38
- func encode(to encoder: Encoder) throws {
39
- var c = encoder.singleValueContainer()
40
- switch self {
41
- case .string(let s): try c.encode(s)
42
- case .number(let n): try c.encode(n)
43
- case .bool(let b): try c.encode(b)
44
- case .array(let a): try c.encode(a)
45
- case .object(let o): try c.encode(o)
46
- case .null: try c.encodeNil()
47
- }
48
- }
49
-
50
- var string: String? { if case .string(let s) = self { return s }; return nil }
51
- var number: Double? {
52
- switch self {
53
- case .number(let n): return n
54
- case .string(let s): return Double(s)
55
- default: return nil
56
- }
57
- }
58
- }
59
-
60
- struct Condition: Codable {
61
- let attr: String
62
- let op: String
63
- let value: JSONValue
64
- }
65
-
66
- struct Conditions: Codable {
67
- let all: [Condition]?
68
- }
69
-
70
- struct OfferReward: Codable {
71
- let mode: String
72
- let units: Int?
73
- let unitName: JSONValue?
74
-
75
- var isRewarded: Bool { mode == "rewarded" && (units ?? 0) > 0 }
76
-
77
- func unitLabel(lang: String) -> String {
78
- switch unitName {
79
- case .string(let s)?: return s
80
- case .object(let o)?: return o[lang]?.string ?? o["en"]?.string ?? o.values.compactMap { $0.string }.first ?? ""
81
- default: return ""
82
- }
83
- }
84
- }
85
-
86
- struct Offer: Codable {
87
- let offerId: String
88
- let conditions: Conditions?
89
- let requiredAttrs: [String]?
90
- let loiMinutes: Int?
91
- let reward: OfferReward?
92
- let locales: [String]?
93
- let expiresAt: String?
94
- /// Open to guests (people with no signed token). Only ever true on apps FOUNTIS allowed guests in.
95
- let guest: Bool?
96
- }
97
-
98
- struct SurveysConfig: Codable {
99
- let maxNotificationsPerDay: Int?
100
- let quietHours: [Int]?
101
- let checkIntervalMinutes: Int?
102
- }
103
-
104
- struct SurveysAppInfo: Codable {
105
- let publicId: String?
106
- let env: String?
107
- let name: String?
108
- /// The app may offer free studies to guests.
109
- let guests: Bool?
110
- }
111
-
112
- struct SurveysResponse: Codable {
113
- let app: SurveysAppInfo?
114
- let config: SurveysConfig?
115
- let surveys: [Offer]
116
- }
@@ -1,63 +0,0 @@
1
- import Foundation
2
- import UIKit
3
- import BackgroundTasks
4
- import UserNotifications
5
-
6
- /// Forwards notification callbacks to the SDK. Installed only when the host app has no delegate of its own.
7
- final class ForwardingNotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
8
- func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
9
- Task { @MainActor in
10
- _ = FountisConnect.handleNotificationResponse(response)
11
- completionHandler()
12
- }
13
- }
14
-
15
- func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
16
- completionHandler([.banner, .list])
17
- }
18
- }
19
-
20
- enum BGRefresh {
21
- static let identifier = "org.fountis.connect.refresh"
22
- /// Submitting a request without a registered handler raises an Objective-C exception, so only schedule after register.
23
- nonisolated(unsafe) private(set) static var registered = false
24
-
25
- /// Must run before the host app finishes launching. Never throws: a missing Info.plist entry only logs.
26
- @MainActor
27
- static func register(handler: @escaping @MainActor () async -> Void) -> Bool {
28
- let info = Bundle.main.infoDictionary ?? [:]
29
- let ids = info["BGTaskSchedulerPermittedIdentifiers"] as? [String] ?? []
30
- let modes = info["UIBackgroundModes"] as? [String] ?? []
31
- guard ids.contains(identifier), modes.contains("fetch") else {
32
- fcLog.debug("background refresh not set up: add \(identifier) to BGTaskSchedulerPermittedIdentifiers and 'fetch' to UIBackgroundModes")
33
- return false
34
- }
35
- // register(...) raises an Objective-C exception once launch has finished. A scene that is already
36
- // connected means launch is over (applicationState is not reliable this early).
37
- if UIApplication.shared.connectedScenes.contains(where: { $0.activationState != .unattached }) {
38
- fcLog.debug("start() ran after launch finished; background refresh not registered")
39
- return false
40
- }
41
- registered = BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { task in
42
- Task { @MainActor in
43
- schedule(minutes: nil)
44
- let work = Task { @MainActor in
45
- await handler()
46
- task.setTaskCompleted(success: true)
47
- }
48
- task.expirationHandler = {
49
- work.cancel()
50
- task.setTaskCompleted(success: false)
51
- }
52
- }
53
- }
54
- return registered
55
- }
56
-
57
- static func schedule(minutes: Int?) {
58
- guard registered else { return }
59
- let req = BGAppRefreshTaskRequest(identifier: identifier)
60
- req.earliestBeginDate = Date(timeIntervalSinceNow: Double(max(minutes ?? 240, 60)) * 60)
61
- do { try BGTaskScheduler.shared.submit(req) } catch { fcLog.debug("could not schedule refresh: \(error.localizedDescription)") }
62
- }
63
- }
@@ -1,93 +0,0 @@
1
- import Foundation
2
-
3
- /// The most one API request may take in total: opening the connection, sending the request and reading the whole
4
- /// response body. The web and Android SDKs end a request at the same 15 s.
5
- ///
6
- /// URLSession alone cannot promise that. `timeoutIntervalForRequest` is an idle timeout (it restarts whenever bytes
7
- /// arrive), so a server that sends a byte now and then keeps a request open forever. `timeoutIntervalForResource` does
8
- /// bound the whole transfer, and `ApiClient` sets it, but the deadline below does not depend on it: it is the SDK's own.
9
- let requestDeadline: TimeInterval = 15
10
-
11
- /// Runs `work` (one HTTP exchange) but never waits on it for longer than `deadline` seconds, whatever it is doing.
12
- ///
13
- /// After `deadline` this throws `URLError(.timedOut)`, the error URLSession itself raises for a timeout, so every
14
- /// caller already treats it as an ordinary network failure (the study ends as `noFill`, `event()` swallows it, the
15
- /// engine's own retry takes over for in-study calls). `work` is cancelled at that point, which makes URLSession cancel
16
- /// the task and close the connection.
17
- ///
18
- /// Deliberately not a task group, like `callTokenProvider`: a group waits for all its children, so work that is slow
19
- /// to react to cancellation would keep the caller waiting. Instead `work` and a timer run as unstructured tasks, the
20
- /// first to finish settles a one-shot continuation, and a late outcome from `work` is dropped. Cancelling the caller
21
- /// ends the call at once with `CancellationError` and cancels `work`.
22
- func runWithinDeadline<T: Sendable>(
23
- _ deadline: TimeInterval,
24
- _ work: @escaping @Sendable () async throws -> T
25
- ) async throws -> T {
26
- let call = DeadlineCall<T>()
27
- return try await withTaskCancellationHandler {
28
- try await withCheckedThrowingContinuation { (cont: CheckedContinuation<T, Error>) in
29
- // Already cancelled (or timed out, which cannot happen yet): attach resumes `cont` with that outcome.
30
- guard call.attach(cont) else { return }
31
- call.track(Task {
32
- do { call.settle(.success(try await work())) } catch { call.settle(.failure(error)) }
33
- })
34
- call.track(Task {
35
- do { try await Task.sleep(nanoseconds: UInt64(max(deadline, 0) * 1_000_000_000)) } catch { return }
36
- call.settle(.failure(URLError(.timedOut)))
37
- })
38
- }
39
- } onCancel: {
40
- call.settle(.failure(CancellationError()))
41
- }
42
- }
43
-
44
- /// The one-shot state of a single `runWithinDeadline`: the continuation is resumed exactly once, by whichever of the
45
- /// work, the timer or a cancellation settles first. Everything is guarded by one lock because those three race on
46
- /// different threads.
47
- private final class DeadlineCall<T: Sendable>: @unchecked Sendable {
48
- private let lock = NSLock()
49
- private var continuation: CheckedContinuation<T, Error>?
50
- private var outcome: Result<T, Error>?
51
- private var tasks: [Task<Void, Never>] = []
52
-
53
- /// Stores the continuation. Returns `false` (after resuming it) when the call was already settled, which only a
54
- /// cancellation that arrived before the continuation existed can have done.
55
- func attach(_ cont: CheckedContinuation<T, Error>) -> Bool {
56
- lock.lock()
57
- if let done = outcome {
58
- lock.unlock()
59
- cont.resume(with: done)
60
- return false
61
- }
62
- continuation = cont
63
- lock.unlock()
64
- return true
65
- }
66
-
67
- /// Keeps a task so settling can cancel it; cancels it at once if the call is already settled.
68
- func track(_ task: Task<Void, Never>) {
69
- lock.lock()
70
- if outcome == nil {
71
- tasks.append(task)
72
- lock.unlock()
73
- } else {
74
- lock.unlock()
75
- task.cancel()
76
- }
77
- }
78
-
79
- /// First caller wins; later calls (a late answer from the work, a timer that lost the race) do nothing. Cancels
80
- /// both tasks: the timer when the work won, the work when the timer or the caller won.
81
- func settle(_ result: Result<T, Error>) {
82
- lock.lock()
83
- guard outcome == nil else { lock.unlock(); return }
84
- outcome = result
85
- let cont = continuation
86
- continuation = nil
87
- let running = tasks
88
- tasks = []
89
- lock.unlock()
90
- running.forEach { $0.cancel() }
91
- cont?.resume(with: result)
92
- }
93
- }
@@ -1,259 +0,0 @@
1
- import UIKit
2
- import WebKit
3
-
4
- /// The SDK-owned survey screen. It is always presented full screen (no sheet, no swipe-to-dismiss) and hosts the
5
- /// bundled FOUNTIS-branded engine edge to edge in a locked-down WKWebView; the engine handles the safe areas
6
- /// itself (`viewport-fit=cover`) and is the only way out (its close button sends `{type:"close"}`).
7
- /// The controller relays the engine's messages to the API (the engine never touches the network in native mode).
8
- @MainActor
9
- final class SheetController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate {
10
- struct Finish {
11
- /// "complete", "screen_out", "quota_full", or nil when closed before the end.
12
- let outcome: String?
13
- /// A fatal API code (not_eligible, closed, ...) was shown.
14
- let fatal: String?
15
- /// UIKit never started showing the sheet (see `abandonIfNotShown`): nothing was shown, so it is neither completed nor dismissed.
16
- var unavailable = false
17
- }
18
-
19
- private let engineURL: URL
20
- private let initJSON: String
21
- private let api: ApiClient
22
- private let attemptToken: String
23
- private let onShown: () -> Void
24
- private let onFinish: (Finish) -> Void
25
-
26
- private var webView: WKWebView!
27
- private var cover: UIView?
28
- private var inFlight = Set<String>()
29
- private var outcome: String?
30
- private var fatal: String?
31
- private var navigated = false
32
- private var appeared = false
33
- private var finished = false
34
-
35
- /// `onShown` runs once, when UIKit first starts showing the sheet. `onFinish` runs exactly once, ever.
36
- init(engineURL: URL, initPayload: [String: Any], api: ApiClient, attemptToken: String, onShown: @escaping () -> Void, onFinish: @escaping (Finish) -> Void) {
37
- self.engineURL = engineURL
38
- let data = (try? JSONSerialization.data(withJSONObject: initPayload)) ?? Data("{}".utf8)
39
- self.initJSON = String(decoding: data, as: UTF8.self)
40
- self.api = api
41
- self.attemptToken = attemptToken
42
- self.onShown = onShown
43
- self.onFinish = onFinish
44
- super.init(nibName: nil, bundle: nil)
45
- modalPresentationStyle = .fullScreen
46
- isModalInPresentation = true
47
- modalTransitionStyle = .coverVertical
48
- }
49
-
50
- required init?(coder: NSCoder) { fatalError("not supported") }
51
-
52
- // MARK: lifecycle
53
-
54
- override func viewDidLoad() {
55
- super.viewDidLoad()
56
- view.backgroundColor = Self.ground
57
- }
58
-
59
- /// Built when UIKit first starts showing the sheet, not in `viewDidLoad`: UIKit loads the view of a presentation it
60
- /// then refuses, and a sheet nobody sees must not start the engine.
61
- private func buildWebView() {
62
- let cfg = WKWebViewConfiguration()
63
- cfg.websiteDataStore = .nonPersistent()
64
- cfg.allowsInlineMediaPlayback = true
65
- cfg.dataDetectorTypes = []
66
- cfg.userContentController.add(WeakHandler(self), name: "fountis")
67
- webView = WKWebView(frame: .zero, configuration: cfg)
68
- if #available(iOS 16.4, *) { webView.isInspectable = false }
69
- webView.navigationDelegate = self
70
- webView.isOpaque = false
71
- webView.backgroundColor = .clear
72
- webView.scrollView.backgroundColor = .clear
73
- webView.scrollView.bounces = false
74
- webView.scrollView.isScrollEnabled = false // the engine scrolls its own body; a scrolling document is what slides the header under the status bar when the keyboard opens
75
- webView.scrollView.contentInsetAdjustmentBehavior = .never // edge to edge: the engine reads env(safe-area-inset-*)
76
- webView.translatesAutoresizingMaskIntoConstraints = false
77
- view.addSubview(webView)
78
- NSLayoutConstraint.activate([
79
- webView.topAnchor.constraint(equalTo: view.topAnchor),
80
- webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
81
- webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
82
- webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
83
- ])
84
- webView.loadFileURL(engineURL, allowingReadAccessTo: engineURL.deletingLastPathComponent())
85
-
86
- let nc = NotificationCenter.default
87
- nc.addObserver(self, selector: #selector(hideContent), name: UIApplication.willResignActiveNotification, object: nil)
88
- nc.addObserver(self, selector: #selector(showContent), name: UIApplication.didBecomeActiveNotification, object: nil)
89
- }
90
-
91
- deinit { NotificationCenter.default.removeObserver(self) }
92
-
93
- /// FOUNTIS page ground (#F2F5F4), the same colour the engine paints, so nothing flashes before it loads.
94
- private static let ground = UIColor(red: 0xF2 / 255, green: 0xF5 / 255, blue: 0xF4 / 255, alpha: 1)
95
-
96
- // The engine's ground is light, so the status bar content is dark.
97
- override var preferredStatusBarStyle: UIStatusBarStyle { .darkContent }
98
- override var prefersStatusBarHidden: Bool { false }
99
-
100
- override func viewWillAppear(_ animated: Bool) {
101
- super.viewWillAppear(animated)
102
- guard !appeared, !finished else { return }
103
- appeared = true
104
- buildWebView()
105
- onShown()
106
- }
107
-
108
- override func viewDidAppear(_ animated: Bool) {
109
- super.viewDidAppear(animated)
110
- // UIKit showed a sheet the presenter had already given up on: its result is out, so just get it off the screen.
111
- if finished, presentingViewController != nil { dismiss(animated: false) }
112
- }
113
-
114
- override func viewDidDisappear(_ animated: Bool) {
115
- super.viewDidDisappear(animated)
116
- if isBeingDismissed || presentingViewController == nil { finish() }
117
- }
118
-
119
- /// The presenter's watchdog: if UIKit has not started showing the sheet by now, it is not going to (a refused
120
- /// presentation only logs a warning), so finish it as `unavailable`. Goes through `finish()`, so `onFinish` still
121
- /// runs once however this races with a late appearance. A sheet UIKit does show after this loads nothing.
122
- func abandonIfNotShown() {
123
- guard !appeared, !finished else { return }
124
- finish(unavailable: true)
125
- }
126
-
127
- private func finish(unavailable: Bool = false) {
128
- guard !finished else { return }
129
- finished = true
130
- webView?.configuration.userContentController.removeScriptMessageHandler(forName: "fountis")
131
- onFinish(Finish(outcome: outcome, fatal: fatal, unavailable: unavailable))
132
- }
133
-
134
- private func close() {
135
- if presentingViewController != nil { dismiss(animated: true) { [weak self] in self?.finish() } } else { finish() }
136
- }
137
-
138
- // MARK: privacy cover
139
-
140
- @objc private func hideContent() {
141
- guard cover == nil else { return }
142
- let v = UIView(frame: view.bounds)
143
- v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
144
- v.backgroundColor = Self.ground
145
- view.addSubview(v)
146
- cover = v
147
- }
148
-
149
- @objc private func showContent() {
150
- cover?.removeFromSuperview()
151
- cover = nil
152
- }
153
-
154
- // MARK: navigation lock
155
-
156
- func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
157
- if !navigated, navigationAction.request.url?.isFileURL == true {
158
- navigated = true
159
- decisionHandler(.allow)
160
- } else {
161
- decisionHandler(.cancel)
162
- }
163
- }
164
-
165
- func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
166
- fcLog.debug("web content process terminated")
167
- close()
168
- }
169
-
170
- // MARK: engine messages
171
-
172
- func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
173
- guard let body = message.body as? [String: Any], let type = body["type"] as? String else { return }
174
- switch type {
175
- case "ready":
176
- send(js: "window.FountisEngine && window.FountisEngine.init(\(initJSON))")
177
- case "answer":
178
- guard let code = body["code"] as? String else { return }
179
- handleAnswer(code: code, value: body["value"] ?? NSNull())
180
- case "consent":
181
- handleConsent()
182
- case "complete":
183
- handleComplete()
184
- case "done":
185
- if let o = body["outcome"] as? String { outcome = o }
186
- case "close":
187
- close()
188
- default:
189
- break // progress, height: nothing to do on the host
190
- }
191
- }
192
-
193
- private func reply(_ obj: [String: Any]) {
194
- guard let d = try? JSONSerialization.data(withJSONObject: obj) else { return }
195
- send(js: "window.FountisEngine && window.FountisEngine.receive(\(String(decoding: d, as: UTF8.self)))")
196
- }
197
-
198
- private func send(js: String) { webView?.evaluateJavaScript(js, completionHandler: nil) }
199
-
200
- private func fail(_ error: Error) {
201
- if let e = error as? APIError {
202
- if e.isFatal { fatal = e.code }
203
- reply(["type": "error", "message": e.message, "code": e.code])
204
- } else {
205
- reply(["type": "error", "message": "network"])
206
- }
207
- }
208
-
209
- /// Runs `work` unless the same request is already in flight (the engine re-sends every 5 s).
210
- private func once(_ key: String, _ work: @escaping () async -> Void) {
211
- guard inFlight.insert(key).inserted else { return }
212
- Task { [weak self] in
213
- await work()
214
- self?.inFlight.remove(key)
215
- }
216
- }
217
-
218
- private func handleAnswer(code: String, value: Any) {
219
- let sig = "a:" + code + ":" + ((try? JSONSerialization.data(withJSONObject: [value], options: [.sortedKeys])).map { String(decoding: $0, as: UTF8.self) } ?? "")
220
- once(sig) { [weak self] in
221
- guard let self else { return }
222
- do {
223
- let r = try await self.api.putAnswer(code: code, value: value, attemptToken: self.attemptToken)
224
- self.reply(["type": "ack", "code": code, "stop": r["stop"] ?? NSNull()])
225
- } catch { self.fail(error) }
226
- }
227
- }
228
-
229
- private func handleConsent() {
230
- once("consent") { [weak self] in
231
- guard let self else { return }
232
- do {
233
- try await self.api.consent(attemptToken: self.attemptToken)
234
- self.reply(["type": "ack", "code": "consent", "stop": NSNull()])
235
- } catch { self.fail(error) }
236
- }
237
- }
238
-
239
- private func handleComplete() {
240
- once("complete") { [weak self] in
241
- guard let self else { return }
242
- do {
243
- let r = try await self.api.complete(attemptToken: self.attemptToken)
244
- let o = (r["outcome"] as? String) ?? "complete"
245
- self.outcome = o
246
- self.reply(["type": "result", "outcome": o, "reward": r["reward"] ?? NSNull()])
247
- } catch { self.fail(error) }
248
- }
249
- }
250
- }
251
-
252
- /// WKUserContentController retains its handlers strongly; this proxy avoids a retain cycle.
253
- private final class WeakHandler: NSObject, WKScriptMessageHandler {
254
- weak var target: (any WKScriptMessageHandler)?
255
- init(_ t: any WKScriptMessageHandler) { target = t }
256
- func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
257
- target?.userContentController(ucc, didReceive: message)
258
- }
259
- }
@@ -1,34 +0,0 @@
1
- import Foundation
2
-
3
- /// Reads the shared i18n JSON (the same files the engine uses) for the few host-side strings.
4
- enum Strings {
5
- private static var cache: [String: [String: String]] = [:]
6
-
7
- private static func table(_ lang: String) -> [String: String] {
8
- if let t = cache[lang] { return t }
9
- var t: [String: String] = [:]
10
- if let url = Bundle.module.url(forResource: lang, withExtension: "json", subdirectory: "Engine/i18n"),
11
- let d = try? Data(contentsOf: url),
12
- let o = try? JSONSerialization.jsonObject(with: d) as? [String: String] { t = o }
13
- cache[lang] = t
14
- return t
15
- }
16
-
17
- static func get(_ key: String, lang: String, _ vars: [String: String] = [:]) -> String {
18
- var s = table(lang)[key] ?? table("en")[key] ?? key
19
- for (k, v) in vars { s = s.replacingOccurrences(of: "{\(k)}", with: v) }
20
- return s
21
- }
22
-
23
- static func normalize(_ lang: String?) -> String {
24
- guard let l = lang?.lowercased() else { return "en" }
25
- let two = l.hasPrefix("kmr") ? "kmr" : l.hasPrefix("ckb") ? "ku" : String(l.prefix(2))
26
- return ["en", "ku", "kmr", "ar"].contains(two) ? two : "en"
27
- }
28
-
29
- static func isRTL(_ lang: String) -> Bool { ["ku", "kmr", "ar"].contains(lang) }
30
-
31
- static var deviceLang: String {
32
- normalize(Locale.preferredLanguages.first)
33
- }
34
- }
@@ -1,91 +0,0 @@
1
- import Foundation
2
-
3
- /// How long the SDK waits for the partner's token provider. Same 10 seconds as the React Native and Flutter wrappers.
4
- let tokenProviderTimeout: TimeInterval = 10
5
-
6
- /// The token provider did not answer in time. A failure, never "signed out": nothing is shown (`noFill`).
7
- struct TokenProviderTimeout: Error {}
8
-
9
- /// Calls the partner's token provider, but never waits on it for longer than `timeout` seconds.
10
- ///
11
- /// A provider that never returns (a hung request, a lost continuation) must not wedge the SDK: `Core.runInner` holds
12
- /// `presenting` for the whole call, so a call that never ends would turn every later show, auto-show, push and
13
- /// notification tap into `noFill` for good. After `timeout` this throws `TokenProviderTimeout`, which the caller treats
14
- /// as a failed check. It is never the guest path: only a provider that returns `nil` means nobody is signed in.
15
- ///
16
- /// Deliberately not a task group: a group waits for all its children, so a provider that ignores cancellation would
17
- /// still hang the call. Instead the provider and a timer run as unstructured tasks, the first to finish settles a
18
- /// one-shot continuation, and a late answer from the provider is dropped. Cancelling the caller (for example
19
- /// `signOut()` cancelling the auto-show task) ends the call at once with `CancellationError`.
20
- func callTokenProvider(
21
- _ provider: @escaping () async throws -> String?,
22
- timeout: TimeInterval = tokenProviderTimeout
23
- ) async throws -> String? {
24
- let call = TokenCall()
25
- return try await withTaskCancellationHandler {
26
- try await withCheckedThrowingContinuation { (cont: CheckedContinuation<String?, Error>) in
27
- // Already cancelled (or timed out, which cannot happen yet): attach resumes `cont` with that outcome.
28
- guard call.attach(cont) else { return }
29
- call.track(Task {
30
- do { call.settle(.success(try await provider())) } catch { call.settle(.failure(error)) }
31
- })
32
- call.track(Task {
33
- do { try await Task.sleep(nanoseconds: UInt64(max(timeout, 0) * 1_000_000_000)) } catch { return }
34
- call.settle(.failure(TokenProviderTimeout()))
35
- })
36
- }
37
- } onCancel: {
38
- call.settle(.failure(CancellationError()))
39
- }
40
- }
41
-
42
- /// The one-shot state of a single `callTokenProvider`: the continuation is resumed exactly once, by whichever of the
43
- /// provider, the timer or a cancellation settles first. Everything is guarded by one lock because those three race
44
- /// on different threads.
45
- private final class TokenCall: @unchecked Sendable {
46
- private let lock = NSLock()
47
- private var continuation: CheckedContinuation<String?, Error>?
48
- private var outcome: Result<String?, Error>?
49
- private var tasks: [Task<Void, Never>] = []
50
-
51
- /// Stores the continuation. Returns `false` (after resuming it) when the call was already settled, which only a
52
- /// cancellation that arrived before the continuation existed can have done.
53
- func attach(_ cont: CheckedContinuation<String?, Error>) -> Bool {
54
- lock.lock()
55
- if let done = outcome {
56
- lock.unlock()
57
- cont.resume(with: done)
58
- return false
59
- }
60
- continuation = cont
61
- lock.unlock()
62
- return true
63
- }
64
-
65
- /// Keeps a task so settling can cancel it; cancels it at once if the call is already settled.
66
- func track(_ task: Task<Void, Never>) {
67
- lock.lock()
68
- if outcome == nil {
69
- tasks.append(task)
70
- lock.unlock()
71
- } else {
72
- lock.unlock()
73
- task.cancel()
74
- }
75
- }
76
-
77
- /// First caller wins; later calls (a late provider answer, a timer that lost the race) do nothing. Cancels both
78
- /// tasks: the timer when the provider won, the provider when the timer or the caller won.
79
- func settle(_ result: Result<String?, Error>) {
80
- lock.lock()
81
- guard outcome == nil else { lock.unlock(); return }
82
- outcome = result
83
- let cont = continuation
84
- continuation = nil
85
- let running = tasks
86
- tasks = []
87
- lock.unlock()
88
- running.forEach { $0.cancel() }
89
- cont?.resume(with: result)
90
- }
91
- }
@@ -1,16 +0,0 @@
1
- #!/bin/sh
2
- # Makes the npm tarball self-contained by copying the native SDK sources into this package.
3
- # Runs on `npm pack` / `npm publish` (prepack). In this repository the podspec copies the Swift SDK itself
4
- # and Gradle reads ../../android/connect directly, so you do not need this script for development.
5
- set -e
6
- HERE="$(cd "$(dirname "$0")/.." && pwd)"
7
- SDK="$HERE/.."
8
-
9
- rm -rf "$HERE/ios/FountisConnectSDK" "$HERE/android/connect-sdk"
10
- mkdir -p "$HERE/ios/FountisConnectSDK" "$HERE/android/connect-sdk"
11
- cp "$SDK/ios/Sources/FountisConnect/"*.swift "$HERE/ios/FountisConnectSDK/"
12
- cp "$SDK/ios/Sources/FountisConnect/PrivacyInfo.xcprivacy" "$HERE/ios/FountisConnectSDK/"
13
- cp -R "$SDK/ios/Sources/FountisConnect/Engine" "$HERE/ios/FountisConnectSDK/Engine"
14
- cp -R "$SDK/android/connect/src/main" "$HERE/android/connect-sdk/main"
15
- rm -f "$HERE/android/connect-sdk/main/AndroidManifest.xml" # this package has its own copy of it
16
- echo "vendored the native SDKs into ios/FountisConnectSDK and android/connect-sdk"