// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The page's guest network: the SDK's NetStack over Wisp servers, with the // plain-HTTP hosts of the route table (config.ts DEFAULT_ROUTES) answered by // fetch() (the SDK's fetchRoutes()). import { NetStack, fetchRoutes, wispBackend, type NetSpec, type TailscaleSpec } from "./sdk.ts"; /** The project's Wisp server. It accepts only the page's origins (unkernel.dev, and localhost for the dev server). */ const PROJECT_WISP_SERVERS = ["wss://wisp.unkernel.dev:6680/"]; /** A build's Wisp URL: a relative one (`/wisp/`) is on the page's own origin, over ws: or wss: as the page is http: or https:. */ function wispUrl(u: string): string { if (/^wss?:\/\//i.test(u) || typeof location === "undefined") return u; const url = new URL(u, location.href); if (url.protocol === "https:" || url.protocol === "http:") url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; return url.href; } /** * The page's Wisp servers: the build's (KW_WISP, vite.config.ts), else the * project's. A page served elsewhere needs its own: built with KW_WISP, or * loaded with ?wisp=, which overrides both. */ export const DEFAULT_WISP_SERVERS: readonly string[] = Object.freeze(__KW_WISP__.length ? __KW_WISP__.map(wispUrl) : PROJECT_WISP_SERVERS); /** Guest-visible host name to base URL; null or empty: none. */ type Routes = Record | null; /** * The page's network: a NetStack whose backend is the fastest of the Wisp * servers (default: DEFAULT_WISP_SERVERS), or none when `enabled` is * false (config.ts: `?net=0`, `?wisp=0`; `?wisp=URL[,URL...]` sets `servers`; * `routes` is config.ts DEFAULT_ROUTES unless `?routes=0`). */ export function browserNet(opts: { enabled: boolean; servers: string[] | null; routes: Routes; log?: (m: string) => void }): NetStack | undefined { if (!opts.enabled) return undefined; const wisp = wispBackend(opts.servers ?? [...DEFAULT_WISP_SERVERS], { log: opts.log }); const backend = opts.routes && Object.keys(opts.routes).length ? fetchRoutes(wisp, opts.routes, { log: opts.log }) : wisp; return new NetStack({ backend, log: opts.log }); } /** * The same network as a spec, for worker mode (?worker=1: the worker builds * the NetStack and opens the WebSocket), and in both modes with `tailscale` * (tailscale.ts; the SDK runs the node on this thread). */ export function browserNetSpec(opts: { enabled: boolean; servers: string[] | null; routes: Routes; tailscale?: TailscaleSpec }): NetSpec | undefined { if (!opts.enabled) return undefined; return { kind: "net", backend: { kind: "wisp", servers: opts.servers ?? [...DEFAULT_WISP_SERVERS], routes: opts.routes ?? undefined }, ...(opts.tailscale ? { tailscale: opts.tailscale } : {}) }; }