@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.
- package/CHANGELOG.md +29 -0
- package/LICENSE +24 -0
- package/README.md +92 -2
- package/android/build.gradle +37 -0
- package/android/connect-sdk/main/assets/fountis-connect/engine.html +47 -0
- package/android/connect-sdk/main/assets/fountis-connect/i18n/ar.json +70 -0
- package/android/connect-sdk/main/assets/fountis-connect/i18n/en.json +70 -0
- package/android/connect-sdk/main/assets/fountis-connect/i18n/kmr.json +70 -0
- package/android/connect-sdk/main/assets/fountis-connect/i18n/ku.json +70 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +179 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +234 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +641 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +321 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +143 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +167 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +144 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +109 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +70 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +74 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +45 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +72 -0
- package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +12 -0
- package/android/connect-sdk/main/res/values/fountis_styles.xml +13 -0
- package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +12 -0
- package/android/src/main/AndroidManifest.xml +18 -0
- package/android/src/main/java/org/fountis/connect/rn/FountisConnectModule.kt +113 -0
- package/app.plugin.js +41 -0
- package/build/index.d.ts +34 -0
- package/build/index.js +126 -0
- package/build/index.web.d.ts +22 -0
- package/build/index.web.js +57 -0
- package/build/types.d.ts +23 -0
- package/build/types.js +1 -0
- package/expo-module.config.json +10 -0
- package/ios/FountisConnectAppDelegateSubscriber.swift +16 -0
- package/ios/FountisConnectBundle.swift +15 -0
- package/ios/FountisConnectModule.swift +131 -0
- package/ios/FountisConnectReactNative.podspec +35 -0
- package/ios/FountisConnectSDK/ApiClient.swift +137 -0
- package/ios/FountisConnectSDK/Attestation.swift +276 -0
- package/ios/FountisConnectSDK/Engine/engine.html +47 -0
- package/ios/FountisConnectSDK/Engine/i18n/ar.json +70 -0
- package/ios/FountisConnectSDK/Engine/i18n/en.json +70 -0
- package/ios/FountisConnectSDK/Engine/i18n/kmr.json +70 -0
- package/ios/FountisConnectSDK/Engine/i18n/ku.json +70 -0
- package/ios/FountisConnectSDK/FountisConnect.swift +441 -0
- package/ios/FountisConnectSDK/LocalState.swift +81 -0
- package/ios/FountisConnectSDK/Matcher.swift +102 -0
- package/ios/FountisConnectSDK/Models.swift +133 -0
- package/ios/FountisConnectSDK/Notifier.swift +63 -0
- package/ios/FountisConnectSDK/PrivacyInfo.xcprivacy +23 -0
- package/ios/FountisConnectSDK/RequestDeadline.swift +93 -0
- package/ios/FountisConnectSDK/SheetController.swift +259 -0
- package/ios/FountisConnectSDK/Strings.swift +34 -0
- package/ios/FountisConnectSDK/TokenProviderCall.swift +91 -0
- package/package.json +67 -4
- package/scripts/vendor-native.sh +16 -0
- package/src/index.ts +142 -0
- package/src/index.web.ts +64 -0
- package/src/types.ts +26 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
package org.fountis.connect.rn
|
|
2
|
+
|
|
3
|
+
import expo.modules.kotlin.Promise
|
|
4
|
+
import expo.modules.kotlin.modules.Module
|
|
5
|
+
import expo.modules.kotlin.modules.ModuleDefinition
|
|
6
|
+
import java.util.UUID
|
|
7
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
8
|
+
import kotlinx.coroutines.CompletableDeferred
|
|
9
|
+
import kotlinx.coroutines.withTimeoutOrNull
|
|
10
|
+
import org.fountis.connect.FountisConnect
|
|
11
|
+
import org.fountis.connect.FountisEvent
|
|
12
|
+
import org.fountis.connect.FountisEventListener
|
|
13
|
+
import org.fountis.connect.FountisResult
|
|
14
|
+
|
|
15
|
+
/** JS bridge for the FOUNTIS Connect Android SDK. */
|
|
16
|
+
class FountisConnectModule : Module() {
|
|
17
|
+
private val tokenRequests = ConcurrentHashMap<String, CompletableDeferred<String?>>()
|
|
18
|
+
private val eventListener = FountisEventListener { e: FountisEvent ->
|
|
19
|
+
val body = mutableMapOf<String, Any?>("type" to e.type)
|
|
20
|
+
e.offerId?.let { body["offerId"] = it }
|
|
21
|
+
sendEvent("onFountisEvent", body)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
override fun definition() = ModuleDefinition {
|
|
25
|
+
Name("FountisConnect")
|
|
26
|
+
|
|
27
|
+
Events("onFountisEvent", "onTokenRequest")
|
|
28
|
+
|
|
29
|
+
OnCreate {
|
|
30
|
+
FountisConnect.onEvent(eventListener)
|
|
31
|
+
// Optional: the config plugin can write the key into the manifest so the SDK starts with the app.
|
|
32
|
+
val ctx = appContext.reactContext ?: return@OnCreate
|
|
33
|
+
try {
|
|
34
|
+
val meta = ctx.packageManager
|
|
35
|
+
.getApplicationInfo(ctx.packageName, android.content.pm.PackageManager.GET_META_DATA).metaData
|
|
36
|
+
val key = meta?.getString("org.fountis.connect.KEY")
|
|
37
|
+
if (!key.isNullOrEmpty()) FountisConnect.start(ctx, key, meta?.getString("org.fountis.connect.API_BASE"))
|
|
38
|
+
} catch (_: Throwable) {
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
Function("start") { key: String, apiBase: String? ->
|
|
43
|
+
appContext.reactContext?.let { FountisConnect.start(it, key, apiBase) }
|
|
44
|
+
Unit
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// JS owns the token function. The SDK asks for a token; we ask JS with an event and wait for resolveToken.
|
|
48
|
+
Function("setTokenProviderEnabled") { enabled: Boolean ->
|
|
49
|
+
if (enabled) {
|
|
50
|
+
FountisConnect.setUserToken {
|
|
51
|
+
val id = UUID.randomUUID().toString()
|
|
52
|
+
val d = CompletableDeferred<String?>()
|
|
53
|
+
tokenRequests[id] = d
|
|
54
|
+
try {
|
|
55
|
+
sendEvent("onTokenRequest", mapOf("id" to id))
|
|
56
|
+
// JS may not be running (a background check): give up after 10 s. That is a failure, not "signed out":
|
|
57
|
+
// an answer of null (nobody signed in) is wrapped so it cannot be mistaken for the timeout.
|
|
58
|
+
val answer = withTimeoutOrNull(10_000) { TokenAnswer(d.await()) }
|
|
59
|
+
?: throw TokenUnavailableException("token provider timed out")
|
|
60
|
+
answer.token
|
|
61
|
+
} finally {
|
|
62
|
+
tokenRequests.remove(id)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
Function("resolveToken") { id: String, token: String? ->
|
|
69
|
+
tokenRequests.remove(id)?.complete(token)
|
|
70
|
+
Unit
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The JS token function threw or rejected: the SDK gets an exception (noFill), not null (nobody is signed in).
|
|
74
|
+
Function("rejectToken") { id: String ->
|
|
75
|
+
tokenRequests.remove(id)?.completeExceptionally(TokenUnavailableException("token provider failed"))
|
|
76
|
+
Unit
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
Function("enableNotifications") {
|
|
80
|
+
appContext.currentActivity?.let { FountisConnect.enableNotifications(it) }
|
|
81
|
+
Unit
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
Function("setUserConsent") { granted: Boolean -> FountisConnect.setUserConsent(granted) }
|
|
85
|
+
|
|
86
|
+
Function("signOut") { FountisConnect.signOut() }
|
|
87
|
+
|
|
88
|
+
AsyncFunction("show") { promise: Promise ->
|
|
89
|
+
val activity = appContext.currentActivity
|
|
90
|
+
if (activity == null) {
|
|
91
|
+
promise.resolve("noFill")
|
|
92
|
+
} else {
|
|
93
|
+
FountisConnect.show(activity) { r: FountisResult ->
|
|
94
|
+
promise.resolve(
|
|
95
|
+
when (r) {
|
|
96
|
+
FountisResult.Completed -> "completed"
|
|
97
|
+
FountisResult.Dismissed -> "dismissed"
|
|
98
|
+
FountisResult.NoFill -> "noFill"
|
|
99
|
+
},
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
AsyncFunction("handlePush") { data: Map<String, String> -> FountisConnect.handlePush(data) }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Holds the token (null = nobody signed in) so a real answer of null differs from the timeout, which is also null. */
|
|
110
|
+
private class TokenAnswer(val token: String?)
|
|
111
|
+
|
|
112
|
+
/** The token could not be fetched. Not a CancellationException: the SDK rethrows those to the host app. */
|
|
113
|
+
private class TokenUnavailableException(message: String) : Exception(message)
|
package/app.plugin.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Expo config plugin for @fountispanel/connect-react-native.
|
|
3
|
+
*
|
|
4
|
+
* plugins: [["@fountispanel/connect-react-native", { key: "pk_test_..." }]]
|
|
5
|
+
*
|
|
6
|
+
* iOS: adds the `fetch` background mode and the background refresh task id to Info.plist.
|
|
7
|
+
* Android: nothing else is needed (permissions and the survey screen come with the library).
|
|
8
|
+
* `key` / `apiBase` are optional. With a key the SDK starts while the app launches, which iOS
|
|
9
|
+
* requires for background refresh. Without it, call start() from JS (background refresh stays off).
|
|
10
|
+
* The key is a publishable key (pk_...), safe to ship in the app.
|
|
11
|
+
*/
|
|
12
|
+
const { withInfoPlist, withAndroidManifest, AndroidConfig, createRunOncePlugin } = require('expo/config-plugins');
|
|
13
|
+
|
|
14
|
+
const TASK_ID = 'org.fountis.connect.refresh';
|
|
15
|
+
|
|
16
|
+
function withFountisConnect(config, options = {}) {
|
|
17
|
+
config = withInfoPlist(config, (c) => {
|
|
18
|
+
const plist = c.modResults;
|
|
19
|
+
const modes = new Set(plist.UIBackgroundModes ?? []);
|
|
20
|
+
modes.add('fetch');
|
|
21
|
+
plist.UIBackgroundModes = [...modes];
|
|
22
|
+
const ids = new Set(plist.BGTaskSchedulerPermittedIdentifiers ?? []);
|
|
23
|
+
ids.add(TASK_ID);
|
|
24
|
+
plist.BGTaskSchedulerPermittedIdentifiers = [...ids];
|
|
25
|
+
if (options.key) plist.FountisConnectKey = options.key;
|
|
26
|
+
if (options.apiBase) plist.FountisConnectApiBase = options.apiBase;
|
|
27
|
+
return c;
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
config = withAndroidManifest(config, (c) => {
|
|
31
|
+
const app = AndroidConfig.Manifest.getMainApplicationOrThrow(c.modResults);
|
|
32
|
+
if (options.key) AndroidConfig.Manifest.addMetaDataItemToMainApplication(app, 'org.fountis.connect.KEY', options.key);
|
|
33
|
+
if (options.apiBase) AndroidConfig.Manifest.addMetaDataItemToMainApplication(app, 'org.fountis.connect.API_BASE', options.apiBase);
|
|
34
|
+
return c;
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return config;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const pkg = require('./package.json');
|
|
41
|
+
module.exports = createRunOncePlugin(withFountisConnect, pkg.name, pkg.version);
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
|
|
2
|
+
export type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
|
|
3
|
+
/** Starts the SDK. Call once, early. Safe to call again. */
|
|
4
|
+
export declare function start(options: StartOptions): void;
|
|
5
|
+
/**
|
|
6
|
+
* Gives the SDK a way to get the signed user token from your server. The function returns the token when someone is
|
|
7
|
+
* signed in and `null` only when nobody is. Throw (or reject) when you cannot get a token, for example when your token
|
|
8
|
+
* endpoint fails: nothing is shown then, and the person is not treated as a guest. No answer within 10 seconds also
|
|
9
|
+
* counts as a failure.
|
|
10
|
+
*/
|
|
11
|
+
export declare function setUserToken(tokenProvider: TokenProvider | string | null): void;
|
|
12
|
+
/** Turns on the background check and asks for the notification permission. One notification a day at most. */
|
|
13
|
+
export declare function enableNotifications(): void;
|
|
14
|
+
/** Looks for a matching study and shows it full screen. Resolves when the person is done. */
|
|
15
|
+
export declare function show(): Promise<ShowResult>;
|
|
16
|
+
/** Call from your push handler with the message data. Resolves `true` if it was a FOUNTIS push (it has a `fountis` key). */
|
|
17
|
+
export declare function handlePush(data: Record<string, unknown>): Promise<boolean>;
|
|
18
|
+
/** Pass the person's consent to be offered studies. Default: true. */
|
|
19
|
+
export declare function setUserConsent(granted: boolean): void;
|
|
20
|
+
/** Forget the signed-in person: removes their local state and pending notifications. */
|
|
21
|
+
export declare function signOut(): void;
|
|
22
|
+
/** Listens to anonymous lifecycle events. Returns a function that removes the listener. */
|
|
23
|
+
export declare function onEvent(listener: (event: ConnectEvent) => void): () => void;
|
|
24
|
+
declare const FountisConnect: {
|
|
25
|
+
start: typeof start;
|
|
26
|
+
setUserToken: typeof setUserToken;
|
|
27
|
+
enableNotifications: typeof enableNotifications;
|
|
28
|
+
show: typeof show;
|
|
29
|
+
handlePush: typeof handlePush;
|
|
30
|
+
setUserConsent: typeof setUserConsent;
|
|
31
|
+
signOut: typeof signOut;
|
|
32
|
+
onEvent: typeof onEvent;
|
|
33
|
+
};
|
|
34
|
+
export default FountisConnect;
|
package/build/index.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
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
|
+
let cached;
|
|
10
|
+
/** The native module, or null (with one console warning) when it is missing, for example in Expo Go. */
|
|
11
|
+
function native() {
|
|
12
|
+
if (cached !== undefined)
|
|
13
|
+
return cached;
|
|
14
|
+
try {
|
|
15
|
+
cached = requireNativeModule('FountisConnect');
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
cached = null;
|
|
19
|
+
console.warn('[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.');
|
|
20
|
+
}
|
|
21
|
+
return cached;
|
|
22
|
+
}
|
|
23
|
+
let provider = null;
|
|
24
|
+
let tokenSub = null;
|
|
25
|
+
function ensureTokenListener(n) {
|
|
26
|
+
if (tokenSub)
|
|
27
|
+
return;
|
|
28
|
+
// The native SDK asks for a token when it needs one. We answer from the function the app gave us.
|
|
29
|
+
tokenSub = n.addListener('onTokenRequest', async (e) => {
|
|
30
|
+
let token;
|
|
31
|
+
try {
|
|
32
|
+
token = (await provider?.()) ?? null;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// A provider that throws could not get a token (a failed request, say). That is not "signed out", so never
|
|
36
|
+
// answer null here: null makes the SDK offer guest studies to someone who is signed in. Report the failure instead.
|
|
37
|
+
// An older native binary has no rejectToken: nothing is sent, the request times out as before and is read as null
|
|
38
|
+
// (the old behaviour). Rebuild the native app to get the fix.
|
|
39
|
+
if (typeof n.rejectToken === 'function')
|
|
40
|
+
n.rejectToken(e.id);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
n.resolveToken(e.id, token);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** Starts the SDK. Call once, early. Safe to call again. */
|
|
47
|
+
export function start(options) {
|
|
48
|
+
try {
|
|
49
|
+
native()?.start(options.key, options.apiBase ?? null);
|
|
50
|
+
}
|
|
51
|
+
catch { }
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Gives the SDK a way to get the signed user token from your server. The function returns the token when someone is
|
|
55
|
+
* signed in and `null` only when nobody is. Throw (or reject) when you cannot get a token, for example when your token
|
|
56
|
+
* endpoint fails: nothing is shown then, and the person is not treated as a guest. No answer within 10 seconds also
|
|
57
|
+
* counts as a failure.
|
|
58
|
+
*/
|
|
59
|
+
export function setUserToken(tokenProvider) {
|
|
60
|
+
try {
|
|
61
|
+
provider = typeof tokenProvider === 'function' ? tokenProvider : () => tokenProvider;
|
|
62
|
+
const n = native();
|
|
63
|
+
if (!n)
|
|
64
|
+
return;
|
|
65
|
+
ensureTokenListener(n);
|
|
66
|
+
n.setTokenProviderEnabled(true);
|
|
67
|
+
}
|
|
68
|
+
catch { }
|
|
69
|
+
}
|
|
70
|
+
/** Turns on the background check and asks for the notification permission. One notification a day at most. */
|
|
71
|
+
export function enableNotifications() {
|
|
72
|
+
try {
|
|
73
|
+
native()?.enableNotifications();
|
|
74
|
+
}
|
|
75
|
+
catch { }
|
|
76
|
+
}
|
|
77
|
+
/** Looks for a matching study and shows it full screen. Resolves when the person is done. */
|
|
78
|
+
export async function show() {
|
|
79
|
+
try {
|
|
80
|
+
return (await native()?.show()) ?? 'noFill';
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return 'noFill';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Call from your push handler with the message data. Resolves `true` if it was a FOUNTIS push (it has a `fountis` key). */
|
|
87
|
+
export async function handlePush(data) {
|
|
88
|
+
try {
|
|
89
|
+
const strings = {};
|
|
90
|
+
for (const [k, v] of Object.entries(data ?? {}))
|
|
91
|
+
strings[k] = typeof v === 'string' ? v : String(v);
|
|
92
|
+
return (await native()?.handlePush(strings)) ?? false;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Pass the person's consent to be offered studies. Default: true. */
|
|
99
|
+
export function setUserConsent(granted) {
|
|
100
|
+
try {
|
|
101
|
+
native()?.setUserConsent(granted);
|
|
102
|
+
}
|
|
103
|
+
catch { }
|
|
104
|
+
}
|
|
105
|
+
/** Forget the signed-in person: removes their local state and pending notifications. */
|
|
106
|
+
export function signOut() {
|
|
107
|
+
try {
|
|
108
|
+
native()?.signOut();
|
|
109
|
+
}
|
|
110
|
+
catch { }
|
|
111
|
+
}
|
|
112
|
+
/** Listens to anonymous lifecycle events. Returns a function that removes the listener. */
|
|
113
|
+
export function onEvent(listener) {
|
|
114
|
+
const n = native();
|
|
115
|
+
if (!n)
|
|
116
|
+
return () => { };
|
|
117
|
+
const sub = n.addListener('onFountisEvent', (e) => {
|
|
118
|
+
try {
|
|
119
|
+
listener(e);
|
|
120
|
+
}
|
|
121
|
+
catch { }
|
|
122
|
+
});
|
|
123
|
+
return () => sub.remove();
|
|
124
|
+
}
|
|
125
|
+
const FountisConnect = { start, setUserToken, enableNotifications, show, handlePush, setUserConsent, signOut, onEvent };
|
|
126
|
+
export default FountisConnect;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
|
|
2
|
+
export type { ConnectEvent, ShowResult, StartOptions, TokenProvider } from './types';
|
|
3
|
+
export declare function start(options: StartOptions): void;
|
|
4
|
+
export declare function setUserToken(tokenProvider: TokenProvider | string | null): void;
|
|
5
|
+
export declare function enableNotifications(): void;
|
|
6
|
+
export declare function show(): Promise<ShowResult>;
|
|
7
|
+
/** The web has no push messages. */
|
|
8
|
+
export declare function handlePush(_data: Record<string, unknown>): Promise<boolean>;
|
|
9
|
+
export declare function setUserConsent(granted: boolean): void;
|
|
10
|
+
export declare function signOut(): void;
|
|
11
|
+
export declare function onEvent(listener: (event: ConnectEvent) => void): () => void;
|
|
12
|
+
declare const FountisConnect: {
|
|
13
|
+
start: typeof start;
|
|
14
|
+
setUserToken: typeof setUserToken;
|
|
15
|
+
enableNotifications: typeof enableNotifications;
|
|
16
|
+
show: typeof show;
|
|
17
|
+
handlePush: typeof handlePush;
|
|
18
|
+
setUserConsent: typeof setUserConsent;
|
|
19
|
+
signOut: typeof signOut;
|
|
20
|
+
onEvent: typeof onEvent;
|
|
21
|
+
};
|
|
22
|
+
export default FountisConnect;
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
export function start(options) {
|
|
7
|
+
try {
|
|
8
|
+
web.start({ key: options.key, apiBase: options.apiBase, engineUrl: options.engineUrl });
|
|
9
|
+
}
|
|
10
|
+
catch { }
|
|
11
|
+
}
|
|
12
|
+
export function setUserToken(tokenProvider) {
|
|
13
|
+
try {
|
|
14
|
+
web.setUserToken(typeof tokenProvider === 'function' ? async () => (await tokenProvider()) ?? null : (tokenProvider ?? null));
|
|
15
|
+
}
|
|
16
|
+
catch { }
|
|
17
|
+
}
|
|
18
|
+
export function enableNotifications() {
|
|
19
|
+
try {
|
|
20
|
+
web.enableNotifications();
|
|
21
|
+
}
|
|
22
|
+
catch { }
|
|
23
|
+
}
|
|
24
|
+
export async function show() {
|
|
25
|
+
try {
|
|
26
|
+
return await web.show();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return 'noFill';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** The web has no push messages. */
|
|
33
|
+
export async function handlePush(_data) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
export function setUserConsent(granted) {
|
|
37
|
+
try {
|
|
38
|
+
web.setUserConsent(granted);
|
|
39
|
+
}
|
|
40
|
+
catch { }
|
|
41
|
+
}
|
|
42
|
+
export function signOut() {
|
|
43
|
+
try {
|
|
44
|
+
web.signOut();
|
|
45
|
+
}
|
|
46
|
+
catch { }
|
|
47
|
+
}
|
|
48
|
+
export function onEvent(listener) {
|
|
49
|
+
try {
|
|
50
|
+
return web.onEvent((e) => listener(e));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return () => { };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const FountisConnect = { start, setUserToken, enableNotifications, show, handlePush, setUserConsent, signOut, onEvent };
|
|
57
|
+
export default FountisConnect;
|
package/build/types.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** What `show()` resolves to. Every failure is `noFill`; the SDK never throws into your app. */
|
|
2
|
+
export type ShowResult = 'noFill' | 'dismissed' | 'completed';
|
|
3
|
+
/** Anonymous lifecycle event. Carries no survey titles, topics or answers. */
|
|
4
|
+
export type ConnectEvent = {
|
|
5
|
+
type: 'shown' | 'started' | 'dismissed' | 'completed' | 'noFill' | 'notified';
|
|
6
|
+
offerId?: string;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Returns the signed user token from your server when someone is signed in.
|
|
10
|
+
* Return `null` (or `undefined`) only when nobody is signed in: the SDK then offers guest studies, if your app allows guests.
|
|
11
|
+
* Throw (or reject) when you cannot get a token, for example when your token endpoint fails: nothing is shown
|
|
12
|
+
* (`noFill`) and the person is never treated as a guest. No answer within 10 seconds also counts as a failure.
|
|
13
|
+
* Called on demand; the SDK does not keep the token longer than one check.
|
|
14
|
+
*/
|
|
15
|
+
export type TokenProvider = () => Promise<string | null | undefined> | string | null | undefined;
|
|
16
|
+
export type StartOptions = {
|
|
17
|
+
/** Your publishable key, `pk_test_...` or `pk_live_...`. */
|
|
18
|
+
key: string;
|
|
19
|
+
/** Override the API base URL. Defaults to the FOUNTIS production API. */
|
|
20
|
+
apiBase?: string;
|
|
21
|
+
/** Web only: override the URL of the hosted survey engine. */
|
|
22
|
+
engineUrl?: string;
|
|
23
|
+
};
|
package/build/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
/// Starts the SDK while the app is still launching when the config plugin was given a key
|
|
5
|
+
/// (`FountisConnectKey` in Info.plist). iOS only accepts the background refresh registration at that moment.
|
|
6
|
+
/// Without a key here, `start()` from JS still works; only the background refresh is not registered.
|
|
7
|
+
public final class FountisConnectAppDelegateSubscriber: ExpoAppDelegateSubscriber {
|
|
8
|
+
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
|
|
9
|
+
let info = Bundle.main.infoDictionary ?? [:]
|
|
10
|
+
if let key = info["FountisConnectKey"] as? String, !key.isEmpty {
|
|
11
|
+
let base = (info["FountisConnectApiBase"] as? String).flatMap { URL(string: $0) }
|
|
12
|
+
MainActor.assumeIsolated { FountisConnect.start(key: key, apiBase: base) }
|
|
13
|
+
}
|
|
14
|
+
return true
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// The shared Swift sources look up their resources with SwiftPM's `Bundle.module`. CocoaPods has no such thing,
|
|
4
|
+
// so this file (compiled only in this pod, not in the Swift package) points it at the pod's resource bundle.
|
|
5
|
+
private final class FountisBundleToken {}
|
|
6
|
+
|
|
7
|
+
extension Bundle {
|
|
8
|
+
static var module: Bundle {
|
|
9
|
+
let here = Bundle(for: FountisBundleToken.self)
|
|
10
|
+
for base in [here.resourceURL, Bundle.main.resourceURL] {
|
|
11
|
+
if let url = base?.appendingPathComponent("FountisConnect.bundle"), let b = Bundle(url: url) { return b }
|
|
12
|
+
}
|
|
13
|
+
return here
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
/// JS bridge for the FOUNTIS Connect iOS SDK. All SDK calls run on the main thread, in the order JS made them.
|
|
5
|
+
public final class FountisConnectModule: Module {
|
|
6
|
+
private let tokens = TokenRequests()
|
|
7
|
+
|
|
8
|
+
public func definition() -> ModuleDefinition {
|
|
9
|
+
Name("FountisConnect")
|
|
10
|
+
|
|
11
|
+
Events("onFountisEvent", "onTokenRequest")
|
|
12
|
+
|
|
13
|
+
OnCreate {
|
|
14
|
+
DispatchQueue.main.async {
|
|
15
|
+
MainActor.assumeIsolated {
|
|
16
|
+
FountisConnect.onEvent { [weak self] e in
|
|
17
|
+
var body: [String: Any] = ["type": e.type]
|
|
18
|
+
if let id = e.offerId { body["offerId"] = id }
|
|
19
|
+
self?.sendEvent("onFountisEvent", body)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
Function("start") { (key: String, apiBase: String?) in
|
|
26
|
+
DispatchQueue.main.async {
|
|
27
|
+
MainActor.assumeIsolated {
|
|
28
|
+
FountisConnect.start(key: key, apiBase: apiBase.flatMap { URL(string: $0) })
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// JS owns the token function. The SDK asks for a token; we ask JS with an event and wait for resolveToken.
|
|
34
|
+
Function("setTokenProviderEnabled") { (enabled: Bool) in
|
|
35
|
+
DispatchQueue.main.async {
|
|
36
|
+
MainActor.assumeIsolated {
|
|
37
|
+
guard enabled else { return }
|
|
38
|
+
FountisConnect.setUserToken { [weak self] in
|
|
39
|
+
// A vanished bridge is a failure, not "signed out": throwing keeps the person off the guest path.
|
|
40
|
+
guard let self else { throw TokenBridgeError.bridgeGone }
|
|
41
|
+
return try await self.tokens.request { id in self.sendEvent("onTokenRequest", ["id": id]) }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
Function("resolveToken") { (id: String, token: String?) in
|
|
48
|
+
self.tokens.resolve(id, token)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The JS token function threw or rejected: tell the SDK the token is unavailable (not that nobody is signed in).
|
|
52
|
+
Function("rejectToken") { (id: String) in
|
|
53
|
+
self.tokens.reject(id)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
Function("enableNotifications") {
|
|
57
|
+
DispatchQueue.main.async { MainActor.assumeIsolated { FountisConnect.enableNotifications() } }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
Function("setUserConsent") { (granted: Bool) in
|
|
61
|
+
DispatchQueue.main.async { MainActor.assumeIsolated { FountisConnect.setUserConsent(granted) } }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
Function("signOut") {
|
|
65
|
+
DispatchQueue.main.async { MainActor.assumeIsolated { FountisConnect.signOut() } }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
AsyncFunction("show") { () async -> String in
|
|
69
|
+
let r = await FountisConnect.show()
|
|
70
|
+
switch r {
|
|
71
|
+
case .completed: return "completed"
|
|
72
|
+
case .dismissed: return "dismissed"
|
|
73
|
+
case .noFill: return "noFill"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
AsyncFunction("handlePush") { (data: [String: String]) async -> Bool in
|
|
78
|
+
await MainActor.run { FountisConnect.handlePush(data) }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// Why a token request did not produce an answer. The SDK treats any thrown error as "no session" (noFill),
|
|
84
|
+
/// which is different from a nil token (nobody is signed in, so guest studies when the app allows them).
|
|
85
|
+
enum TokenBridgeError: Error {
|
|
86
|
+
case providerFailed
|
|
87
|
+
case timedOut
|
|
88
|
+
case bridgeGone
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// Pending "give me a token" questions to JS. Each one is answered once: with the token (nil means nobody is signed in),
|
|
92
|
+
/// with a thrown error when the JS function failed, or with `timedOut` after 10 seconds (for example when the JS side is
|
|
93
|
+
/// not running during a background refresh).
|
|
94
|
+
final class TokenRequests: @unchecked Sendable {
|
|
95
|
+
private let lock = NSLock()
|
|
96
|
+
private var pending: [String: CheckedContinuation<String?, Error>] = [:]
|
|
97
|
+
private let timeout: TimeInterval
|
|
98
|
+
|
|
99
|
+
init(timeout: TimeInterval = 10) {
|
|
100
|
+
self.timeout = timeout
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
func request(send: @escaping (String) -> Void) async throws -> String? {
|
|
104
|
+
let id = UUID().uuidString
|
|
105
|
+
return try await withCheckedThrowingContinuation { (cont: CheckedContinuation<String?, Error>) in
|
|
106
|
+
lock.lock()
|
|
107
|
+
pending[id] = cont
|
|
108
|
+
lock.unlock()
|
|
109
|
+
send(id)
|
|
110
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + timeout) { [weak self] in
|
|
111
|
+
self?.finish(id, .failure(TokenBridgeError.timedOut))
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
func resolve(_ id: String, _ token: String?) {
|
|
117
|
+
finish(id, .success(token))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
func reject(_ id: String) {
|
|
121
|
+
finish(id, .failure(TokenBridgeError.providerFailed))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// Resumes the request once; a late or repeated answer finds nothing pending and does nothing.
|
|
125
|
+
private func finish(_ id: String, _ result: Result<String?, Error>) {
|
|
126
|
+
lock.lock()
|
|
127
|
+
let cont = pending.removeValue(forKey: id)
|
|
128
|
+
lock.unlock()
|
|
129
|
+
cont?.resume(with: result)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
require 'json'
|
|
2
|
+
require 'fileutils'
|
|
3
|
+
|
|
4
|
+
package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
|
|
5
|
+
|
|
6
|
+
# CocoaPods cannot read files outside the pod folder, so the Swift SDK is copied into ios/FountisConnectSDK
|
|
7
|
+
# when `pod install` reads this file inside the repository (re-run `pod install` after changing the SDK).
|
|
8
|
+
# The npm package already carries that copy (scripts/vendor-native.sh runs on `npm pack`).
|
|
9
|
+
repo_sdk = File.join(__dir__, '..', '..', 'ios', 'Sources', 'FountisConnect')
|
|
10
|
+
sdk = 'FountisConnectSDK'
|
|
11
|
+
if File.directory?(repo_sdk)
|
|
12
|
+
FileUtils.rm_rf(File.join(__dir__, sdk))
|
|
13
|
+
FileUtils.mkdir_p(File.join(__dir__, sdk))
|
|
14
|
+
FileUtils.cp_r(Dir.glob(File.join(repo_sdk, '*')), File.join(__dir__, sdk))
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
Pod::Spec.new do |s|
|
|
18
|
+
s.name = 'FountisConnectReactNative'
|
|
19
|
+
s.version = package['version']
|
|
20
|
+
s.summary = package['description']
|
|
21
|
+
s.description = package['description']
|
|
22
|
+
s.license = package['license']
|
|
23
|
+
s.author = 'FOUNTIS'
|
|
24
|
+
s.homepage = 'https://github.com/darbaz/fountis-connect'
|
|
25
|
+
s.platforms = { :ios => '15.1' }
|
|
26
|
+
s.swift_version = '5.9'
|
|
27
|
+
s.source = { :git => 'https://github.com/darbaz/fountis-connect.git' }
|
|
28
|
+
s.static_framework = true
|
|
29
|
+
|
|
30
|
+
s.dependency 'ExpoModulesCore'
|
|
31
|
+
|
|
32
|
+
s.source_files = ['*.swift', "#{sdk}/*.swift"]
|
|
33
|
+
s.resource_bundles = { 'FountisConnect' => ["#{sdk}/Engine", "#{sdk}/PrivacyInfo.xcprivacy"] }
|
|
34
|
+
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
|
|
35
|
+
end
|