@fountispanel/connect-react-native 0.0.0-stage → 1.1.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 (60) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +24 -0
  3. package/README.md +92 -2
  4. package/android/build.gradle +37 -0
  5. package/android/connect-sdk/main/assets/fountis-connect/engine.html +47 -0
  6. package/android/connect-sdk/main/assets/fountis-connect/i18n/ar.json +70 -0
  7. package/android/connect-sdk/main/assets/fountis-connect/i18n/en.json +70 -0
  8. package/android/connect-sdk/main/assets/fountis-connect/i18n/kmr.json +70 -0
  9. package/android/connect-sdk/main/assets/fountis-connect/i18n/ku.json +70 -0
  10. package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +179 -0
  11. package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +234 -0
  12. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +641 -0
  13. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +321 -0
  14. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +143 -0
  15. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +167 -0
  16. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +144 -0
  17. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +109 -0
  18. package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +70 -0
  19. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +74 -0
  20. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +45 -0
  21. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +72 -0
  22. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +12 -0
  23. package/android/connect-sdk/main/res/values/fountis_styles.xml +13 -0
  24. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +12 -0
  25. package/android/src/main/AndroidManifest.xml +18 -0
  26. package/android/src/main/java/org/fountis/connect/rn/FountisConnectModule.kt +113 -0
  27. package/app.plugin.js +41 -0
  28. package/build/index.d.ts +34 -0
  29. package/build/index.js +126 -0
  30. package/build/index.web.d.ts +22 -0
  31. package/build/index.web.js +57 -0
  32. package/build/types.d.ts +23 -0
  33. package/build/types.js +1 -0
  34. package/expo-module.config.json +10 -0
  35. package/ios/FountisConnectAppDelegateSubscriber.swift +16 -0
  36. package/ios/FountisConnectBundle.swift +15 -0
  37. package/ios/FountisConnectModule.swift +131 -0
  38. package/ios/FountisConnectReactNative.podspec +35 -0
  39. package/ios/FountisConnectSDK/ApiClient.swift +137 -0
  40. package/ios/FountisConnectSDK/Attestation.swift +276 -0
  41. package/ios/FountisConnectSDK/Engine/engine.html +47 -0
  42. package/ios/FountisConnectSDK/Engine/i18n/ar.json +70 -0
  43. package/ios/FountisConnectSDK/Engine/i18n/en.json +70 -0
  44. package/ios/FountisConnectSDK/Engine/i18n/kmr.json +70 -0
  45. package/ios/FountisConnectSDK/Engine/i18n/ku.json +70 -0
  46. package/ios/FountisConnectSDK/FountisConnect.swift +441 -0
  47. package/ios/FountisConnectSDK/LocalState.swift +81 -0
  48. package/ios/FountisConnectSDK/Matcher.swift +102 -0
  49. package/ios/FountisConnectSDK/Models.swift +133 -0
  50. package/ios/FountisConnectSDK/Notifier.swift +63 -0
  51. package/ios/FountisConnectSDK/PrivacyInfo.xcprivacy +23 -0
  52. package/ios/FountisConnectSDK/RequestDeadline.swift +93 -0
  53. package/ios/FountisConnectSDK/SheetController.swift +259 -0
  54. package/ios/FountisConnectSDK/Strings.swift +34 -0
  55. package/ios/FountisConnectSDK/TokenProviderCall.swift +91 -0
  56. package/package.json +67 -4
  57. package/scripts/vendor-native.sh +16 -0
  58. package/src/index.ts +142 -0
  59. package/src/index.web.ts +64 -0
  60. package/src/types.ts +26 -0
@@ -0,0 +1,91 @@
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
+ }
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@fountispanel/connect-react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "FOUNTIS Connect for React Native and Expo (development builds): native iOS and Android SDKs, Web SDK on React Native Web.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "main": "build/index.js",
7
+ "types": "build/index.d.ts",
8
+ "files": [
9
+ "build",
10
+ "src",
11
+ "ios",
12
+ "android",
13
+ "app.plugin.js",
14
+ "expo-module.config.json",
15
+ "scripts",
16
+ "README.md",
17
+ "CHANGELOG.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.json",
22
+ "typecheck": "tsc --noEmit",
23
+ "prepack": "npm run build && sh scripts/vendor-native.sh",
24
+ "prepublishOnly": "npm run typecheck && npm run build && sh scripts/vendor-native.sh"
25
+ },
26
+ "keywords": [
27
+ "fountis",
28
+ "survey",
29
+ "expo",
30
+ "react-native",
31
+ "sdk"
32
+ ],
33
+ "peerDependencies": {
34
+ "expo": ">=52",
35
+ "expo-modules-core": "*",
36
+ "react": "*",
37
+ "react-native": "*",
38
+ "@fountispanel/connect": "^1.1.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "@fountispanel/connect": {
42
+ "optional": true
43
+ }
44
+ },
45
+ "devDependencies": {
46
+ "@expo/config-plugins": "*",
47
+ "@types/react": "^19",
48
+ "expo": "*",
49
+ "expo-modules-core": "*",
50
+ "react": "19.1.0",
51
+ "react-native": "0.81.5",
52
+ "typescript": "^5",
53
+ "@fountispanel/connect": "file:../web"
54
+ },
55
+ "author": "FOUNTIS",
56
+ "homepage": "https://github.com/darbaz/fountis-connect#readme",
57
+ "repository": {
58
+ "type": "git",
59
+ "url": "git+https://github.com/darbaz/fountis-connect.git",
60
+ "directory": "react-native"
61
+ },
62
+ "bugs": {
63
+ "url": "https://github.com/darbaz/fountis-connect/issues",
64
+ "email": "dev@fountis.org"
65
+ },
66
+ "publishConfig": {
67
+ "access": "public"
68
+ }
69
+ }
@@ -0,0 +1,16 @@
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"
package/src/index.ts ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @fountispanel/connect-react-native. Public API (same names as the native and web SDKs):
3
+ * start, setUserToken, enableNotifications, show, handlePush, setUserConsent, signOut, onEvent
4
+ *
5
+ * iOS and Android use the native FOUNTIS Connect SDKs (needs an Expo development build or a bare app, not Expo Go).
6
+ * React Native Web wraps the Web SDK (see index.web.ts).
7
+ */
8
+ import { requireNativeModule } from 'expo-modules-core';
9
+ import type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
10
+
11
+ export type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
12
+
13
+ type NativeSubscription = { remove(): void };
14
+ type Native = {
15
+ start(key: string, apiBase: string | null): void;
16
+ enableNotifications(): void;
17
+ show(): Promise<ShowResult>;
18
+ handlePush(data: Record<string, string>): Promise<boolean>;
19
+ setUserConsent(granted: boolean): void;
20
+ signOut(): void;
21
+ setTokenProviderEnabled(enabled: boolean): void;
22
+ resolveToken(id: string, token: string | null): void;
23
+ /** Newer native builds only: tells the SDK the token could not be fetched. Missing on an older binary. */
24
+ rejectToken?(id: string): void;
25
+ addListener(name: string, cb: (payload: any) => void): NativeSubscription;
26
+ };
27
+
28
+ let cached: Native | null | undefined;
29
+ /** The native module, or null (with one console warning) when it is missing, for example in Expo Go. */
30
+ function native(): Native | null {
31
+ if (cached !== undefined) return cached;
32
+ try {
33
+ cached = requireNativeModule<Native>('FountisConnect');
34
+ } catch {
35
+ cached = null;
36
+ console.warn(
37
+ '[FountisConnect] The native module was not found. Use an Expo development build or a bare React Native app (not Expo Go), and add the "@fountispanel/connect-react-native" config plugin.',
38
+ );
39
+ }
40
+ return cached;
41
+ }
42
+
43
+ let provider: TokenProvider | null = null;
44
+ let tokenSub: NativeSubscription | null = null;
45
+
46
+ function ensureTokenListener(n: Native) {
47
+ if (tokenSub) return;
48
+ // The native SDK asks for a token when it needs one. We answer from the function the app gave us.
49
+ tokenSub = n.addListener('onTokenRequest', async (e: { id: string }) => {
50
+ let token: string | null;
51
+ try {
52
+ token = (await provider?.()) ?? null;
53
+ } catch {
54
+ // A provider that throws could not get a token (a failed request, say). That is not "signed out", so never
55
+ // answer null here: null makes the SDK offer guest studies to someone who is signed in. Report the failure instead.
56
+ // An older native binary has no rejectToken: nothing is sent, the request times out as before and is read as null
57
+ // (the old behaviour). Rebuild the native app to get the fix.
58
+ if (typeof n.rejectToken === 'function') n.rejectToken(e.id);
59
+ return;
60
+ }
61
+ n.resolveToken(e.id, token);
62
+ });
63
+ }
64
+
65
+ /** Starts the SDK. Call once, early. Safe to call again. */
66
+ export function start(options: StartOptions): void {
67
+ try {
68
+ native()?.start(options.key, options.apiBase ?? null);
69
+ } catch {}
70
+ }
71
+
72
+ /**
73
+ * Gives the SDK a way to get the signed user token from your server. The function returns the token when someone is
74
+ * signed in and `null` only when nobody is. Throw (or reject) when you cannot get a token, for example when your token
75
+ * endpoint fails: nothing is shown then, and the person is not treated as a guest. No answer within 10 seconds also
76
+ * counts as a failure.
77
+ */
78
+ export function setUserToken(tokenProvider: TokenProvider | string | null): void {
79
+ try {
80
+ provider = typeof tokenProvider === 'function' ? tokenProvider : () => tokenProvider;
81
+ const n = native();
82
+ if (!n) return;
83
+ ensureTokenListener(n);
84
+ n.setTokenProviderEnabled(true);
85
+ } catch {}
86
+ }
87
+
88
+ /** Turns on the background check and asks for the notification permission. One notification a day at most. */
89
+ export function enableNotifications(): void {
90
+ try {
91
+ native()?.enableNotifications();
92
+ } catch {}
93
+ }
94
+
95
+ /** Looks for a matching study and shows it full screen. Resolves when the person is done. */
96
+ export async function show(): Promise<ShowResult> {
97
+ try {
98
+ return (await native()?.show()) ?? 'noFill';
99
+ } catch {
100
+ return 'noFill';
101
+ }
102
+ }
103
+
104
+ /** Call from your push handler with the message data. Resolves `true` if it was a FOUNTIS push (it has a `fountis` key). */
105
+ export async function handlePush(data: Record<string, unknown>): Promise<boolean> {
106
+ try {
107
+ const strings: Record<string, string> = {};
108
+ for (const [k, v] of Object.entries(data ?? {})) strings[k] = typeof v === 'string' ? v : String(v);
109
+ return (await native()?.handlePush(strings)) ?? false;
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ /** Pass the person's consent to be offered studies. Default: true. */
116
+ export function setUserConsent(granted: boolean): void {
117
+ try {
118
+ native()?.setUserConsent(granted);
119
+ } catch {}
120
+ }
121
+
122
+ /** Forget the signed-in person: removes their local state and pending notifications. */
123
+ export function signOut(): void {
124
+ try {
125
+ native()?.signOut();
126
+ } catch {}
127
+ }
128
+
129
+ /** Listens to anonymous lifecycle events. Returns a function that removes the listener. */
130
+ export function onEvent(listener: (event: ConnectEvent) => void): () => void {
131
+ const n = native();
132
+ if (!n) return () => {};
133
+ const sub = n.addListener('onFountisEvent', (e: ConnectEvent) => {
134
+ try {
135
+ listener(e);
136
+ } catch {}
137
+ });
138
+ return () => sub.remove();
139
+ }
140
+
141
+ const FountisConnect = { start, setUserToken, enableNotifications, show, handlePush, setUserConsent, signOut, onEvent };
142
+ export default FountisConnect;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * React Native Web: wraps the Web SDK (`@fountispanel/connect`). Same API as the native build.
3
+ * Notifications are an in-page invitation only, and there are no push messages on the web.
4
+ */
5
+ import * as web from '@fountispanel/connect';
6
+ import type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
7
+
8
+ export type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
9
+
10
+ export function start(options: StartOptions): void {
11
+ try {
12
+ web.start({ key: options.key, apiBase: options.apiBase, engineUrl: options.engineUrl });
13
+ } catch {}
14
+ }
15
+
16
+ export function setUserToken(tokenProvider: TokenProvider | string | null): void {
17
+ try {
18
+ web.setUserToken(
19
+ typeof tokenProvider === 'function' ? async () => (await tokenProvider()) ?? null : (tokenProvider ?? null),
20
+ );
21
+ } catch {}
22
+ }
23
+
24
+ export function enableNotifications(): void {
25
+ try {
26
+ web.enableNotifications();
27
+ } catch {}
28
+ }
29
+
30
+ export async function show(): Promise<ShowResult> {
31
+ try {
32
+ return await web.show();
33
+ } catch {
34
+ return 'noFill';
35
+ }
36
+ }
37
+
38
+ /** The web has no push messages. */
39
+ export async function handlePush(_data: Record<string, unknown>): Promise<boolean> {
40
+ return false;
41
+ }
42
+
43
+ export function setUserConsent(granted: boolean): void {
44
+ try {
45
+ web.setUserConsent(granted);
46
+ } catch {}
47
+ }
48
+
49
+ export function signOut(): void {
50
+ try {
51
+ web.signOut();
52
+ } catch {}
53
+ }
54
+
55
+ export function onEvent(listener: (event: ConnectEvent) => void): () => void {
56
+ try {
57
+ return web.onEvent((e) => listener(e as ConnectEvent));
58
+ } catch {
59
+ return () => {};
60
+ }
61
+ }
62
+
63
+ const FountisConnect = { start, setUserToken, enableNotifications, show, handlePush, setUserConsent, signOut, onEvent };
64
+ export default FountisConnect;
package/src/types.ts ADDED
@@ -0,0 +1,26 @@
1
+ /** What `show()` resolves to. Every failure is `noFill`; the SDK never throws into your app. */
2
+ export type ShowResult = 'noFill' | 'dismissed' | 'completed';
3
+
4
+ /** Anonymous lifecycle event. Carries no survey titles, topics or answers. */
5
+ export type ConnectEvent = {
6
+ type: 'shown' | 'started' | 'dismissed' | 'completed' | 'noFill' | 'notified';
7
+ offerId?: string;
8
+ };
9
+
10
+ /**
11
+ * Returns the signed user token from your server when someone is signed in.
12
+ * Return `null` (or `undefined`) only when nobody is signed in: the SDK then offers guest studies, if your app allows guests.
13
+ * Throw (or reject) when you cannot get a token, for example when your token endpoint fails: nothing is shown
14
+ * (`noFill`) and the person is never treated as a guest. No answer within 10 seconds also counts as a failure.
15
+ * Called on demand; the SDK does not keep the token longer than one check.
16
+ */
17
+ export type TokenProvider = () => Promise<string | null | undefined> | string | null | undefined;
18
+
19
+ export type StartOptions = {
20
+ /** Your publishable key, `pk_test_...` or `pk_live_...`. */
21
+ key: string;
22
+ /** Override the API base URL. Defaults to the FOUNTIS production API. */
23
+ apiBase?: string;
24
+ /** Web only: override the URL of the hosted survey engine. */
25
+ engineUrl?: string;
26
+ };