Open History to see the last commit
1import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
2import type { DevicePlatform } from "@t3tools/contracts";
3
4export interface DeviceStreamConfiguration {
5 readonly access: DeviceHubAccess;
6 readonly platform: DevicePlatform;
7 readonly deviceId: string;
8 readonly colors: {
9 readonly background: string;
10 readonly foreground: string;
11 readonly muted: string;
12 readonly buttonBackground: string;
13 readonly buttonForeground: string;
14 readonly buttonBorder: string;
15 };
16}
17
18export function deviceStreamDocument(configuration: string, script: string) {
19 const safeConfiguration = configuration.replace(/</g, "\\u003c");
20 const safeScript = script.replace(/<\/script/gi, "<\\/script");
21 const failure = `window.ReactNativeWebView.postMessage(JSON.stringify({type:"status",status:"error",detail:"Device viewer stopped unexpectedly."}));`;
22 return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"></head><body><script>window.addEventListener("error",function(){${failure}});window.addEventListener("unhandledrejection",function(){${failure}});\n${safeScript}\ntry{T3DeviceStream.start(${safeConfiguration});}catch{${failure}}</script></body></html>`;
23}
24
25export function deviceStreamMessage(data: string) {
26 try {
27 const message: unknown = JSON.parse(data);
28 if (typeof message !== "object" || message === null || !("type" in message)) return null;
29 if (message.type === "unauthorized" || message.type === "retry") {
30 return { type: message.type } as const;
31 }
32 if (
33 message.type === "input" &&
34 "connected" in message &&
35 typeof message.connected === "boolean"
36 ) {
37 return { type: message.type, connected: message.connected } as const;
38 }
39 if (
40 message.type === "status" &&
41 "status" in message &&
42 (message.status === "connecting" ||
43 message.status === "streaming" ||
44 message.status === "error") &&
45 (!("detail" in message) || typeof message.detail === "string")
46 ) {
47 return {
48 type: message.type,
49 status: message.status,
50 detail:
51 "detail" in message && typeof message.detail === "string" ? message.detail : undefined,
52 } as const;
53 }
54 } catch {}
55 return null;
56}