@returningai/react-native-widget-sdk 0.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 +49 -0
- package/LICENSE +4 -0
- package/README.md +111 -0
- package/package.json +60 -0
- package/src/ReturningAIWidget.tsx +601 -0
- package/src/authentication/ReturningAIAccessTokenCache.ts +90 -0
- package/src/authentication/ReturningAIAuthenticationClient.ts +379 -0
- package/src/authentication/nonce.ts +26 -0
- package/src/authentication/sessionAuthClient.ts +35 -0
- package/src/authentication/types.ts +50 -0
- package/src/bridge/ReturningAIBridgeCodec.ts +452 -0
- package/src/bridge/ReturningAIBridgeIdentity.ts +87 -0
- package/src/configuration/ReturningAIFirstPaintColors.ts +46 -0
- package/src/configuration/ReturningAIWidgetConfiguration.ts +488 -0
- package/src/configuration/ReturningAIWidgetContent.ts +59 -0
- package/src/configuration/ReturningAIWidgetDescriptor.ts +54 -0
- package/src/configuration/ReturningAIWidgetDisplayOptions.ts +59 -0
- package/src/configuration/ReturningAIWidgetDomainKey.ts +44 -0
- package/src/configuration/ReturningAIWidgetEndpoints.ts +157 -0
- package/src/configuration/ReturningAIWidgetTheme.ts +25 -0
- package/src/configuration/urls.ts +133 -0
- package/src/controller/ReturningAIWidgetController.ts +149 -0
- package/src/controller/ReturningAIWidgetSessionSnapshot.ts +49 -0
- package/src/coordinator/ReturningAIWidgetCoordinator.ts +787 -0
- package/src/crypto/fillRandomBytes.ts +28 -0
- package/src/errors/ReturningAIWidgetError.ts +150 -0
- package/src/errors/json.ts +227 -0
- package/src/events/ReturningAIWidgetEvent.ts +131 -0
- package/src/index.ts +79 -0
- package/src/navigation/ReturningAINavigationPolicy.ts +89 -0
- package/src/packageInfo.ts +23 -0
- package/src/rendering/htmlRenderer.ts +351 -0
- package/src/rendering/theme.ts +57 -0
- package/src/webview/ReturningAIReactNativeWebViewDriver.ts +136 -0
- package/src/webview/ReturningAIWebViewDriver.ts +141 -0
- package/src/webview/bridgeBootstrap.ts +26 -0
- package/src/webview/errorPolicy.ts +27 -0
- package/src/webview/originWhitelist.ts +22 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Decides allow / delegate / reject for WebView navigation against configured hosts.
|
|
3
|
+
*
|
|
4
|
+
* Layer: navigation
|
|
5
|
+
* Role: Allows HTTPS (or debug localhost HTTP) to required hosts; delegates unknown HTTPS main-frame
|
|
6
|
+
* URLs to the host; rejects everything else. Does not open URLs or show UI.
|
|
7
|
+
* Security: Enforces HTTPS + host allowlist; HTTP only when configuration.debug and localhost.
|
|
8
|
+
* See also: configuration/ReturningAIWidgetConfiguration.ts, webview/ReturningAIWebViewDriver.ts
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { type ReturningAIWidgetConfiguration } from "../configuration/ReturningAIWidgetConfiguration";
|
|
12
|
+
import { isLocalhost } from "../configuration/urls";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Navigation decision returned by {@link ReturningAINavigationPolicy.decide}.
|
|
16
|
+
* - `allow`: WebView may load the URL
|
|
17
|
+
* - `delegate`: Host should open externally (main-frame unknown HTTPS)
|
|
18
|
+
* - `reject`: Block the load (and emit error for main-frame rejects)
|
|
19
|
+
*/
|
|
20
|
+
export const ReturningAINavigationAction = {
|
|
21
|
+
/** Permit the WebView navigation. */
|
|
22
|
+
allow: "allow",
|
|
23
|
+
/** Hand the URL to the host via external-navigation callbacks. */
|
|
24
|
+
delegate: "delegate",
|
|
25
|
+
/** Block the navigation. */
|
|
26
|
+
reject: "reject",
|
|
27
|
+
} as const;
|
|
28
|
+
|
|
29
|
+
/** Union of {@link ReturningAINavigationAction} values. */
|
|
30
|
+
export type ReturningAINavigationAction =
|
|
31
|
+
(typeof ReturningAINavigationAction)[keyof typeof ReturningAINavigationAction];
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Host/navigation policy that gates WebView loads against required HTTPS hosts.
|
|
35
|
+
*/
|
|
36
|
+
export class ReturningAINavigationPolicy {
|
|
37
|
+
private readonly configuration: ReturningAIWidgetConfiguration;
|
|
38
|
+
private readonly allowedHosts: ReadonlySet<string>;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Creates a policy from a validated configuration's required + allowed hosts.
|
|
42
|
+
* @param configuration - Widget configuration (validated on construct)
|
|
43
|
+
*/
|
|
44
|
+
constructor(configuration: ReturningAIWidgetConfiguration) {
|
|
45
|
+
this.configuration = configuration.validated();
|
|
46
|
+
this.allowedHosts = new Set(
|
|
47
|
+
[...this.configuration.requiredNavigationHosts].map((host) => host.toLowerCase()),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Decides whether a navigation URI should load, be delegated, or be rejected.
|
|
53
|
+
* @param uri - Absolute navigation URL
|
|
54
|
+
* @param isMainFrame - Whether the request targets the main frame
|
|
55
|
+
* @returns `allow`, `delegate`, or `reject`
|
|
56
|
+
*/
|
|
57
|
+
decide(uri: URL, isMainFrame: boolean): ReturningAINavigationAction {
|
|
58
|
+
const scheme = uri.protocol.replace(/:$/, "").toLowerCase();
|
|
59
|
+
if (scheme === "about" && uri.href === "about:blank") {
|
|
60
|
+
return ReturningAINavigationAction.allow;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const host = uri.hostname.toLowerCase();
|
|
64
|
+
if (host.length === 0) {
|
|
65
|
+
return ReturningAINavigationAction.reject;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (scheme === "https") {
|
|
69
|
+
if (this.allowedHosts.has(host)) {
|
|
70
|
+
return ReturningAINavigationAction.allow;
|
|
71
|
+
}
|
|
72
|
+
// Unknown HTTPS main-frame → host opens externally; subframe stays blocked.
|
|
73
|
+
return isMainFrame
|
|
74
|
+
? ReturningAINavigationAction.delegate
|
|
75
|
+
: ReturningAINavigationAction.reject;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (
|
|
79
|
+
scheme === "http" &&
|
|
80
|
+
this.configuration.debug &&
|
|
81
|
+
isLocalhost(host) &&
|
|
82
|
+
this.allowedHosts.has(host)
|
|
83
|
+
) {
|
|
84
|
+
return ReturningAINavigationAction.allow;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return ReturningAINavigationAction.reject;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Declares published package version and peer runtime compatibility pins.
|
|
3
|
+
*
|
|
4
|
+
* Layer: package
|
|
5
|
+
* Role: Single source for SDK version plus Expo / React Native / WebView version metadata.
|
|
6
|
+
* Does not gate runtime features or perform version checks at load time.
|
|
7
|
+
* See also: index.ts
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Published package metadata and documented peer runtime pins.
|
|
12
|
+
* Values are informational for hosts and docs; they are not enforced at import time.
|
|
13
|
+
*/
|
|
14
|
+
export const RETURNING_AI_REACT_NATIVE_PACKAGE = {
|
|
15
|
+
/** Semver of `@returningai/react-native-widget-sdk`. */
|
|
16
|
+
version: "0.1.0",
|
|
17
|
+
/** Documented Expo SDK major this package targets. */
|
|
18
|
+
expoSdk: 57,
|
|
19
|
+
/** Documented React Native minor this package targets. */
|
|
20
|
+
reactNative: "0.86",
|
|
21
|
+
/** Documented `react-native-webview` version this package targets. */
|
|
22
|
+
reactNativeWebView: "16.0.0",
|
|
23
|
+
} as const;
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Deterministically renders the local HTML shell that hosts the ReturningAI runtime and custom element.
|
|
3
|
+
*
|
|
4
|
+
* Layer: rendering
|
|
5
|
+
* Role: Emits HTML/CSS/JS with bridge identity, globals, callbacks, theme, and element attributes;
|
|
6
|
+
* never embeds embed tokens. Does not load the WebView or exchange auth.
|
|
7
|
+
* Security: Access tokens arrive later via native auth interception; embed tokens never appear in HTML.
|
|
8
|
+
* See also: rendering/theme.ts, bridge/ReturningAIBridgeIdentity.ts, Flutter HTML renderer layer
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
type ReturningAIBridgeIdentity,
|
|
13
|
+
RETURNING_AI_REACT_NATIVE_BRIDGE_NAME,
|
|
14
|
+
} from "../bridge/ReturningAIBridgeIdentity";
|
|
15
|
+
import { type ReturningAIWidgetConfiguration } from "../configuration/ReturningAIWidgetConfiguration";
|
|
16
|
+
import { domainKeyAttributeValue } from "../configuration/ReturningAIWidgetDomainKey";
|
|
17
|
+
import { formatEndpointUrl } from "../configuration/ReturningAIWidgetEndpoints";
|
|
18
|
+
import { encodeReturningAIJson, encodeReturningAIJsonForScript } from "../errors/json";
|
|
19
|
+
import {
|
|
20
|
+
argbToRadixString,
|
|
21
|
+
escapeAttribute,
|
|
22
|
+
formatUrl,
|
|
23
|
+
originOf,
|
|
24
|
+
siblingResource,
|
|
25
|
+
} from "../configuration/urls";
|
|
26
|
+
import { returningAIShellBackgroundColor, type ReturningAIResolvedTheme } from "./theme";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Pseudo-URL intercepted by the shell `fetch` hook to trigger native auth over the bridge.
|
|
30
|
+
* Not a network URL; the WebView never receives an embed token through this path.
|
|
31
|
+
*/
|
|
32
|
+
export const NATIVE_AUTH_URL = "rai-native-auth://token";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Renders the deterministic local HTML shell for one widget session.
|
|
36
|
+
* Embeds bridge identity, globals, callbacks, and element attributes.
|
|
37
|
+
* Security: never writes embed tokens into HTML; access tokens arrive later via bridge auth replies.
|
|
38
|
+
* @param input.configuration - Validated host configuration
|
|
39
|
+
* @param input.resolvedTheme - Concrete light/dark theme for first paint
|
|
40
|
+
* @param input.callbackNames - Allowlisted callback names registered on the element
|
|
41
|
+
* @param input.bridgeIdentity - Per-session instanceId + bridgeToken
|
|
42
|
+
* @returns Complete HTML document string
|
|
43
|
+
*/
|
|
44
|
+
export function renderReturningAIHtml(input: {
|
|
45
|
+
configuration: ReturningAIWidgetConfiguration;
|
|
46
|
+
resolvedTheme: ReturningAIResolvedTheme;
|
|
47
|
+
callbackNames: Iterable<string>;
|
|
48
|
+
bridgeIdentity: ReturningAIBridgeIdentity;
|
|
49
|
+
}): string {
|
|
50
|
+
const validated = input.configuration.validated();
|
|
51
|
+
const theme = input.resolvedTheme;
|
|
52
|
+
const globals = renderGlobals(validated);
|
|
53
|
+
const element = renderElement(validated, theme);
|
|
54
|
+
const callbacks = encodeReturningAIJsonForScript([...input.callbackNames].sort());
|
|
55
|
+
const instanceId = encodeReturningAIJsonForScript(input.bridgeIdentity.instanceId);
|
|
56
|
+
const bridgeToken = encodeReturningAIJsonForScript(input.bridgeIdentity.bridgeToken);
|
|
57
|
+
const lightBackground = shellBackgroundCss(validated, "light");
|
|
58
|
+
const darkBackground = shellBackgroundCss(validated, "dark");
|
|
59
|
+
const pageBackground = theme === "dark" ? darkBackground : lightBackground;
|
|
60
|
+
const htmlLang = escapeAttribute(validated.locale ?? "en");
|
|
61
|
+
const runtimeSrc = escapeAttribute(formatUrl(validated.runtimeUrl));
|
|
62
|
+
const nativeAuthJson = encodeReturningAIJsonForScript(NATIVE_AUTH_URL);
|
|
63
|
+
const elementTagJson = encodeReturningAIJsonForScript(validated.widget.elementTag);
|
|
64
|
+
const lightJson = encodeReturningAIJson(lightBackground);
|
|
65
|
+
const darkJson = encodeReturningAIJson(darkBackground);
|
|
66
|
+
const bridgeName = RETURNING_AI_REACT_NATIVE_BRIDGE_NAME;
|
|
67
|
+
|
|
68
|
+
return `<!doctype html>
|
|
69
|
+
<html lang="${htmlLang}" data-theme="${theme}">
|
|
70
|
+
<head>
|
|
71
|
+
<meta charset="utf-8">
|
|
72
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
|
|
73
|
+
${renderResourceHints(validated)}
|
|
74
|
+
<style>
|
|
75
|
+
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: ${pageBackground}; }
|
|
76
|
+
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
|
77
|
+
#returning-ai-widget-root { display: block; width: 100%; height: 100%; }
|
|
78
|
+
</style>
|
|
79
|
+
<script>
|
|
80
|
+
(() => {
|
|
81
|
+
"use strict";
|
|
82
|
+
const version = 1;
|
|
83
|
+
const instanceId = ${instanceId};
|
|
84
|
+
const bridgeToken = ${bridgeToken};
|
|
85
|
+
const nativeAuthURL = ${nativeAuthJson};
|
|
86
|
+
const pending = new Map();
|
|
87
|
+
const requestTimeoutMilliseconds = ${Math.max(validated.authenticationTimeoutMilliseconds, validated.callbackTimeoutMilliseconds) + 1000};
|
|
88
|
+
const originalFetch = window.fetch.bind(window);
|
|
89
|
+
|
|
90
|
+
function randomId() {
|
|
91
|
+
if (window.crypto && typeof window.crypto.randomUUID === "function") return window.crypto.randomUUID();
|
|
92
|
+
const bytes = new Uint8Array(16);
|
|
93
|
+
if (window.crypto && typeof window.crypto.getRandomValues === "function") window.crypto.getRandomValues(bytes);
|
|
94
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function post(body, requestId) {
|
|
98
|
+
if (window.top !== window) return;
|
|
99
|
+
window.${bridgeName}.postMessage(JSON.stringify({ version, instanceId, bridgeToken, requestId, body }));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
window.__returningAIResolveBridge = (encoded) => {
|
|
103
|
+
const response = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0))));
|
|
104
|
+
const entry = pending.get(response.requestId);
|
|
105
|
+
if (!entry) return;
|
|
106
|
+
clearTimeout(entry.timer);
|
|
107
|
+
pending.delete(response.requestId);
|
|
108
|
+
if (response.ok) entry.resolve(response.value === undefined ? null : response.value);
|
|
109
|
+
else entry.reject(new Error(response.error || "Bridge request failed."));
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
function request(body) {
|
|
113
|
+
if (pending.size >= 64) return Promise.reject(new Error("Too many pending bridge requests."));
|
|
114
|
+
const requestId = randomId();
|
|
115
|
+
if (pending.has(requestId)) return Promise.reject(new Error("Bridge request identifier was duplicated."));
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
const timer = setTimeout(() => {
|
|
118
|
+
pending.delete(requestId);
|
|
119
|
+
reject(new Error("Bridge request timed out."));
|
|
120
|
+
}, requestTimeoutMilliseconds);
|
|
121
|
+
pending.set(requestId, { resolve, reject, timer });
|
|
122
|
+
try {
|
|
123
|
+
post(body, requestId);
|
|
124
|
+
} catch (_) {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
pending.delete(requestId);
|
|
127
|
+
reject(new Error("Bridge request could not be sent."));
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
window.addEventListener("pagehide", () => {
|
|
132
|
+
pending.forEach((entry) => {
|
|
133
|
+
clearTimeout(entry.timer);
|
|
134
|
+
entry.reject(new Error("Bridge document was closed."));
|
|
135
|
+
});
|
|
136
|
+
pending.clear();
|
|
137
|
+
});
|
|
138
|
+
window.__returningAIBridgeRequest = request;
|
|
139
|
+
|
|
140
|
+
window.fetch = async (input, init) => {
|
|
141
|
+
const requestURL = typeof input === "string" ? input : input && input.url;
|
|
142
|
+
if (requestURL !== nativeAuthURL) return originalFetch(input, init);
|
|
143
|
+
try {
|
|
144
|
+
const value = await request({ type: "authenticate" });
|
|
145
|
+
return new Response(JSON.stringify(value), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
146
|
+
} catch (error) {
|
|
147
|
+
return new Response(JSON.stringify({ error: String(error && error.message ? error.message : error) }), { status: 502, headers: { "Content-Type": "application/json" } });
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
function forwardEvent(event) {
|
|
152
|
+
post({ name: event.type, detail: event.detail === undefined ? null : event.detail });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
["rai-mounted", "rai-ready", "rai-height-change", "rai-error", "rai-logout", "rai-session-expired"].forEach((name) => {
|
|
156
|
+
document.addEventListener(name, forwardEvent, true);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
window.addEventListener("error", (event) => {
|
|
160
|
+
post({ name: "javascript-error", detail: { message: event.message || "Unknown JavaScript error" } });
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
window.addEventListener("unhandledrejection", (event) => {
|
|
164
|
+
post({ name: "javascript-error", detail: { message: String(event.reason || "Unhandled promise rejection") } });
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const originalOpen = window.open;
|
|
168
|
+
window.open = (url) => {
|
|
169
|
+
post({ name: "rai-external-navigation", detail: { url: String(url || "") } });
|
|
170
|
+
return null;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
document.addEventListener("click", (event) => {
|
|
174
|
+
const anchor = event.target && event.target.closest ? event.target.closest("a[target='_blank']") : null;
|
|
175
|
+
if (!anchor || !anchor.href) return;
|
|
176
|
+
event.preventDefault();
|
|
177
|
+
post({ name: "rai-external-navigation", detail: { url: anchor.href } });
|
|
178
|
+
}, true);
|
|
179
|
+
|
|
180
|
+
${globals}
|
|
181
|
+
window.__RETURNINGAI_MOBILE_SDK__ = true;
|
|
182
|
+
window.__returningAIUpdateTheme = (nextTheme) => {
|
|
183
|
+
document.documentElement.dataset.theme = nextTheme;
|
|
184
|
+
const backgrounds = { light: ${lightJson}, dark: ${darkJson} };
|
|
185
|
+
const background = backgrounds[nextTheme];
|
|
186
|
+
if (background) {
|
|
187
|
+
document.documentElement.style.background = background;
|
|
188
|
+
document.body.style.background = background;
|
|
189
|
+
}
|
|
190
|
+
const widget = document.getElementById("returning-ai-widget-root");
|
|
191
|
+
if (widget) widget.setAttribute("theme", nextTheme);
|
|
192
|
+
};
|
|
193
|
+
window.__returningAILogout = async () => {
|
|
194
|
+
const widget = document.getElementById("returning-ai-widget-root");
|
|
195
|
+
if (widget && typeof widget.logoutPublic === "function") {
|
|
196
|
+
await widget.logoutPublic();
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (window.ReturningAIWidget && typeof window.ReturningAIWidget.logout === "function") {
|
|
200
|
+
await window.ReturningAIWidget.logout();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
document.dispatchEvent(new CustomEvent("rai-logout", { detail: null }));
|
|
204
|
+
};
|
|
205
|
+
})();
|
|
206
|
+
</script>
|
|
207
|
+
<script src="${runtimeSrc}"></script>
|
|
208
|
+
</head>
|
|
209
|
+
<body>
|
|
210
|
+
${element}
|
|
211
|
+
<script>
|
|
212
|
+
(() => {
|
|
213
|
+
"use strict";
|
|
214
|
+
const widget = document.getElementById("returning-ai-widget-root");
|
|
215
|
+
const callbackNames = ${callbacks};
|
|
216
|
+
customElements.whenDefined(${elementTagJson}).then(() => {
|
|
217
|
+
if (!widget || typeof widget.registerCallback !== "function") return;
|
|
218
|
+
callbackNames.forEach((callbackName) => {
|
|
219
|
+
widget.registerCallback(callbackName, async (payload) => {
|
|
220
|
+
return window.__returningAIBridgeRequest({ callbackName, payload: payload === undefined ? null : payload });
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
if (typeof widget.lockCallbacks === "function") widget.lockCallbacks();
|
|
224
|
+
});
|
|
225
|
+
})();
|
|
226
|
+
</script>
|
|
227
|
+
</body>
|
|
228
|
+
</html>
|
|
229
|
+
`;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Renders the custom element markup with sorted, escaped attributes.
|
|
234
|
+
* Uses `auth-url={NATIVE_AUTH_URL}` so auth goes through the native bridge, not HTML tokens.
|
|
235
|
+
*/
|
|
236
|
+
function renderElement(
|
|
237
|
+
configuration: ReturningAIWidgetConfiguration,
|
|
238
|
+
theme: ReturningAIResolvedTheme,
|
|
239
|
+
): string {
|
|
240
|
+
const attributes: Record<string, string> = {
|
|
241
|
+
...configuration.widget.attributes,
|
|
242
|
+
"api-url": formatEndpointUrl(configuration.endpoints.widgetAuthUrl),
|
|
243
|
+
"auth-url": NATIVE_AUTH_URL,
|
|
244
|
+
"auto-refresh": configuration.display.autoRefresh ? "true" : "false",
|
|
245
|
+
"domain-key": domainKeyAttributeValue(configuration.domainKey),
|
|
246
|
+
debug: configuration.debug ? "true" : "false",
|
|
247
|
+
eager: "",
|
|
248
|
+
height: "100%",
|
|
249
|
+
"height-debounce": String(configuration.heightDebounceMilliseconds),
|
|
250
|
+
id: "returning-ai-widget-root",
|
|
251
|
+
"max-retries": String(configuration.maxRetries),
|
|
252
|
+
"retry-delay": String(configuration.retryDelayMilliseconds),
|
|
253
|
+
"storage-prefix": configuration.storagePrefix,
|
|
254
|
+
theme,
|
|
255
|
+
"v2-api-url": formatEndpointUrl(configuration.endpoints.apiV2Url),
|
|
256
|
+
width: "100%",
|
|
257
|
+
};
|
|
258
|
+
if (configuration.display.loadingText.length > 0) {
|
|
259
|
+
attributes["loading-text"] = configuration.display.loadingText;
|
|
260
|
+
}
|
|
261
|
+
if (configuration.content.kind === "bundle") {
|
|
262
|
+
attributes["bundle-url"] = formatUrl(configuration.content.url);
|
|
263
|
+
} else {
|
|
264
|
+
attributes["widget-url"] = formatUrl(configuration.content.url);
|
|
265
|
+
}
|
|
266
|
+
if (configuration.customData !== undefined) {
|
|
267
|
+
attributes["custom-data"] = encodeReturningAIJson(configuration.customData);
|
|
268
|
+
}
|
|
269
|
+
if (configuration.firstPaintColors?.background) {
|
|
270
|
+
attributes.bg = configuration.firstPaintColors.background;
|
|
271
|
+
}
|
|
272
|
+
if (configuration.firstPaintColors?.text) {
|
|
273
|
+
attributes.text = configuration.firstPaintColors.text;
|
|
274
|
+
}
|
|
275
|
+
if (configuration.firstPaintColors?.accent) {
|
|
276
|
+
attributes.accent = configuration.firstPaintColors.accent;
|
|
277
|
+
}
|
|
278
|
+
if (configuration.firstPaintFont) {
|
|
279
|
+
attributes.font = configuration.firstPaintFont;
|
|
280
|
+
}
|
|
281
|
+
if (configuration.locale !== undefined) {
|
|
282
|
+
attributes.locale = configuration.locale;
|
|
283
|
+
attributes.language = configuration.locale;
|
|
284
|
+
}
|
|
285
|
+
const attributeText = Object.entries(attributes)
|
|
286
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
287
|
+
.map(([key, value]) => `${key}="${escapeAttribute(value)}"`)
|
|
288
|
+
.join("\n ");
|
|
289
|
+
return `<${configuration.widget.elementTag}\n ${attributeText}>\n </${configuration.widget.elementTag}>`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Preconnect/preload hints for runtime and bundle siblings (`app.js` / `style.css`). */
|
|
293
|
+
function renderResourceHints(configuration: ReturningAIWidgetConfiguration): string {
|
|
294
|
+
const origins = new Set<string>();
|
|
295
|
+
const runtimeOrigin = originOf(configuration.runtimeUrl);
|
|
296
|
+
const contentOrigin = originOf(configuration.content.url);
|
|
297
|
+
if (runtimeOrigin) origins.add(runtimeOrigin);
|
|
298
|
+
if (contentOrigin) origins.add(contentOrigin);
|
|
299
|
+
const hints: string[] = [];
|
|
300
|
+
for (const origin of [...origins].sort()) {
|
|
301
|
+
hints.push(`<link rel="preconnect" href="${escapeAttribute(origin)}">`);
|
|
302
|
+
}
|
|
303
|
+
hints.push(
|
|
304
|
+
`<link rel="preload" as="script" href="${escapeAttribute(formatUrl(configuration.runtimeUrl))}">`,
|
|
305
|
+
);
|
|
306
|
+
if (configuration.content.kind === "bundle") {
|
|
307
|
+
const bundle = configuration.content.url;
|
|
308
|
+
hints.push(`<link rel="preload" as="script" href="${escapeAttribute(formatUrl(bundle))}">`);
|
|
309
|
+
const segments = bundle.pathname.split("/").filter((part) => part.length > 0);
|
|
310
|
+
const fileName = segments[segments.length - 1] ?? "";
|
|
311
|
+
if (fileName === "widget.js") {
|
|
312
|
+
hints.push(
|
|
313
|
+
`<link rel="modulepreload" href="${escapeAttribute(siblingResource(bundle, "app.js"))}" crossorigin>`,
|
|
314
|
+
);
|
|
315
|
+
hints.push(
|
|
316
|
+
`<link rel="preload" as="style" href="${escapeAttribute(siblingResource(bundle, "style.css"))}">`,
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return hints.join("\n ");
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Emits `window[...] = "..."` assignments for endpoint JavaScript globals. */
|
|
324
|
+
function renderGlobals(configuration: ReturningAIWidgetConfiguration): string {
|
|
325
|
+
const entries = Object.entries(configuration.endpoints.javaScriptGlobals).sort(
|
|
326
|
+
([left], [right]) => (left < right ? -1 : left > right ? 1 : 0),
|
|
327
|
+
);
|
|
328
|
+
return entries
|
|
329
|
+
.map(
|
|
330
|
+
([key, value]) =>
|
|
331
|
+
`window[${encodeReturningAIJsonForScript(key)}] = ${encodeReturningAIJsonForScript(formatUrl(value))};`,
|
|
332
|
+
)
|
|
333
|
+
.join("\n ");
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function shellBackgroundCss(
|
|
337
|
+
configuration: ReturningAIWidgetConfiguration,
|
|
338
|
+
theme: ReturningAIResolvedTheme,
|
|
339
|
+
): string {
|
|
340
|
+
return cssColor(returningAIShellBackgroundColor(theme, configuration.display.backgroundColor));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Converts ARGB to `rgba(...)` CSS for the shell background. */
|
|
344
|
+
function cssColor(value: number): string {
|
|
345
|
+
const hex = argbToRadixString(value).padStart(8, "0");
|
|
346
|
+
const alpha = parseInt(hex.slice(0, 2), 16) / 255;
|
|
347
|
+
const red = parseInt(hex.slice(2, 4), 16);
|
|
348
|
+
const green = parseInt(hex.slice(4, 6), 16);
|
|
349
|
+
const blue = parseInt(hex.slice(6, 8), 16);
|
|
350
|
+
return `rgba(${red}, ${green}, ${blue}, ${alpha.toFixed(3)})`;
|
|
351
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Resolves light/dark theme and default shell background colors for the native chrome.
|
|
3
|
+
*
|
|
4
|
+
* Layer: rendering
|
|
5
|
+
* Role: Maps configuration theme + platform brightness to a resolved theme; picks shell background
|
|
6
|
+
* when display background alpha is zero. Does not generate HTML.
|
|
7
|
+
* See also: configuration/ReturningAIWidgetTheme.ts, rendering/htmlRenderer.ts
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { ReturningAIWidgetTheme } from "../configuration/ReturningAIWidgetTheme";
|
|
11
|
+
|
|
12
|
+
/** Default dark shell ARGB background when display background alpha is zero. */
|
|
13
|
+
export const RETURNING_AI_DARK_SHELL_COLOR = 0xff111827;
|
|
14
|
+
/** Default light shell ARGB background when display background alpha is zero. */
|
|
15
|
+
export const RETURNING_AI_LIGHT_SHELL_COLOR = 0xffffffff;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Theme after resolving `system` against platform brightness.
|
|
19
|
+
*/
|
|
20
|
+
export type ReturningAIResolvedTheme = "light" | "dark";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Resolves a host theme preference against the current platform color scheme.
|
|
24
|
+
* @param theme - Light, dark, or system preference
|
|
25
|
+
* @param platformBrightness - Current OS / RN color scheme
|
|
26
|
+
* @returns Concrete `light` or `dark` theme
|
|
27
|
+
*/
|
|
28
|
+
export function resolveReturningAIWidgetTheme(
|
|
29
|
+
theme: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme],
|
|
30
|
+
platformBrightness: ReturningAIResolvedTheme,
|
|
31
|
+
): ReturningAIResolvedTheme {
|
|
32
|
+
if (theme === ReturningAIWidgetTheme.light) {
|
|
33
|
+
return "light";
|
|
34
|
+
}
|
|
35
|
+
if (theme === ReturningAIWidgetTheme.dark) {
|
|
36
|
+
return "dark";
|
|
37
|
+
}
|
|
38
|
+
return platformBrightness;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Picks the native shell background color for the current resolved theme.
|
|
43
|
+
* When `displayBackgroundColor` has nonzero alpha it wins; otherwise theme defaults apply.
|
|
44
|
+
* @param resolvedTheme - Concrete light/dark theme
|
|
45
|
+
* @param displayBackgroundColor - ARGB from display options
|
|
46
|
+
* @returns ARGB color for the RN shell
|
|
47
|
+
*/
|
|
48
|
+
export function returningAIShellBackgroundColor(
|
|
49
|
+
resolvedTheme: ReturningAIResolvedTheme,
|
|
50
|
+
displayBackgroundColor: number,
|
|
51
|
+
): number {
|
|
52
|
+
const alpha = (displayBackgroundColor >>> 24) & 0xff;
|
|
53
|
+
if (alpha !== 0) {
|
|
54
|
+
return displayBackgroundColor;
|
|
55
|
+
}
|
|
56
|
+
return resolvedTheme === "dark" ? RETURNING_AI_DARK_SHELL_COLOR : RETURNING_AI_LIGHT_SHELL_COLOR;
|
|
57
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview react-native-webview adapter that loads HTML sources and injects JavaScript for the coordinator.
|
|
3
|
+
*
|
|
4
|
+
* Layer: webview
|
|
5
|
+
* Role: Implements ReturningAIWebViewDriver via source-change callbacks, queued injects, and reload
|
|
6
|
+
* tagging to defeat referential HTML equality. Does not parse bridge messages.
|
|
7
|
+
* See also: ReturningAIWebViewDriver.ts, ReturningAIWidget.tsx, webview/bridgeBootstrap.ts
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ReturningAIWebViewDriver } from "./ReturningAIWebViewDriver";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* HTML source object passed to `react-native-webview`'s `source` prop.
|
|
14
|
+
*/
|
|
15
|
+
export type ReturningAIHtmlSource = {
|
|
16
|
+
/** Generated shell HTML (must not contain embed tokens). */
|
|
17
|
+
html: string;
|
|
18
|
+
/** Optional secure document base URL. */
|
|
19
|
+
baseUrl?: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Minimal WebView handle surface required by the driver (inject + reload).
|
|
24
|
+
*/
|
|
25
|
+
export type ReturningAIWebViewHandle = {
|
|
26
|
+
injectJavaScript(script: string): void;
|
|
27
|
+
reload(): void;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* `ReturningAIWebViewDriver` backed by react-native-webview source updates and inject queues.
|
|
32
|
+
*/
|
|
33
|
+
export class ReturningAIReactNativeWebViewDriver implements ReturningAIWebViewDriver {
|
|
34
|
+
private loadedHtml: string | undefined;
|
|
35
|
+
private loadedBaseUrl: string | undefined;
|
|
36
|
+
private handle: ReturningAIWebViewHandle | null = null;
|
|
37
|
+
private pendingScripts: string[] = [];
|
|
38
|
+
private disposed = false;
|
|
39
|
+
private reloadGeneration = 0;
|
|
40
|
+
private readonly onSourceChange: (source: ReturningAIHtmlSource) => void;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param input.onSourceChange - Called whenever the WebView `source` should update
|
|
44
|
+
*/
|
|
45
|
+
constructor(input: { onSourceChange: (source: ReturningAIHtmlSource) => void }) {
|
|
46
|
+
this.onSourceChange = input.onSourceChange;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Attaches (or clears) the native WebView handle and flushes queued scripts.
|
|
51
|
+
* @param handle - WebView ref instance, or `null` on detach
|
|
52
|
+
*/
|
|
53
|
+
attach(handle: ReturningAIWebViewHandle | null): void {
|
|
54
|
+
this.handle = handle;
|
|
55
|
+
if (handle === null || this.disposed) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const queued = this.pendingScripts;
|
|
59
|
+
this.pendingScripts = [];
|
|
60
|
+
for (const script of queued) {
|
|
61
|
+
handle.injectJavaScript(script);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Publishes a new HTML source to the React tree.
|
|
67
|
+
* @param html - Shell HTML
|
|
68
|
+
* @param baseUrl - Optional document base
|
|
69
|
+
*/
|
|
70
|
+
async loadHtmlString(html: string, baseUrl?: string): Promise<void> {
|
|
71
|
+
this.loadedHtml = html;
|
|
72
|
+
this.loadedBaseUrl = baseUrl;
|
|
73
|
+
this.onSourceChange({ html, baseUrl });
|
|
74
|
+
await Promise.resolve();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Replays the loaded shell with a unique HTML tag so RN WebView applies the update.
|
|
79
|
+
* Native `reload()` after `baseUrl` would incorrectly fetch `/`.
|
|
80
|
+
*/
|
|
81
|
+
async reload(): Promise<void> {
|
|
82
|
+
const html = this.loadedHtml;
|
|
83
|
+
if (html === undefined) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// Replay the local shell. Native WebView.reload() after loading HTML with a
|
|
87
|
+
// content-origin baseUrl fetches `/`. react-native-webview also skips an
|
|
88
|
+
// update when `source.html` is referentially unchanged, so tag each replay.
|
|
89
|
+
this.reloadGeneration += 1;
|
|
90
|
+
this.onSourceChange({
|
|
91
|
+
html: `${html}\n<!--returningai-reload:${this.reloadGeneration}-->`,
|
|
92
|
+
baseUrl: this.loadedBaseUrl,
|
|
93
|
+
});
|
|
94
|
+
await Promise.resolve();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Injects JavaScript immediately, or queues it until a handle attaches.
|
|
99
|
+
* @param source - Script source
|
|
100
|
+
*/
|
|
101
|
+
async runJavaScript(source: string): Promise<void> {
|
|
102
|
+
const script = returningAIInjectableScript(source);
|
|
103
|
+
const handle = this.handle;
|
|
104
|
+
if (handle === null || this.disposed) {
|
|
105
|
+
if (!this.disposed) {
|
|
106
|
+
this.pendingScripts.push(script);
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
handle.injectJavaScript(script);
|
|
111
|
+
await Promise.resolve();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Marks the driver disposed and drops the handle + pending scripts.
|
|
116
|
+
*/
|
|
117
|
+
async dispose(): Promise<void> {
|
|
118
|
+
this.disposed = true;
|
|
119
|
+
this.handle = null;
|
|
120
|
+
this.pendingScripts = [];
|
|
121
|
+
await Promise.resolve();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Ensures injectable scripts end with `true;` as required by react-native-webview.
|
|
127
|
+
* @param source - Raw script
|
|
128
|
+
* @returns Script ending in `true;`
|
|
129
|
+
*/
|
|
130
|
+
export function returningAIInjectableScript(source: string): string {
|
|
131
|
+
const trimmed = source.trim();
|
|
132
|
+
if (trimmed.endsWith("true;")) {
|
|
133
|
+
return trimmed;
|
|
134
|
+
}
|
|
135
|
+
return `${trimmed}\ntrue;`;
|
|
136
|
+
}
|