1import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
2import type { EnvironmentId } from "@t3tools/contracts";
3import { Atom } from "effect/reactivity";
4import { isLoopbackHostname } from "../environments/primary/target";
5import { environmentPresentations } from "./presentation";
6import { hostEnvironmentIdAtom } from "./primaryEnvironment";
7
8export function isClientHostEnvironment(
9 environmentId: EnvironmentId,
10 hostEnvironmentId: string | null,
11 target: ConnectionTarget | null,
12 isDesktopRenderer: boolean,
13): boolean {
14 if (isDesktopRenderer && environmentId === hostEnvironmentId) return true;
15 if (target?._tag !== "PrimaryConnectionTarget") return false;
16 if (isDesktopRenderer) return true;
17 try {
18 return isLoopbackHostname(new URL(target.httpBaseUrl).hostname);
19 } catch {
20 return false;
21 }
22}
23
24export const clientHostEnvironmentAtom = Atom.family((environmentId: EnvironmentId | null) =>
25 Atom.make((get) => {
26 if (environmentId === null) return false;
27 return isClientHostEnvironment(
28 environmentId,
29 get(hostEnvironmentIdAtom),
30 get(environmentPresentations.presentationAtom(environmentId))?.entry.target ?? null,
31 window.desktopBridge !== undefined,
32 );
33 }),
34);