UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

59 lines (57 loc) • 2.52 kB
import { logger } from "./logger.js"; import { softrApiUrl } from "./softr-api.js"; import { fetch } from "./fetch.js"; import { sessionConfig } from "./auth/config.js"; import { readCached } from "./cache.js"; import { z } from "zod"; import { createMiddleware } from "@tanstack/react-start"; //#region src/favicon.ts const FAVICON_PATH = "/favicon.ico"; const DEFAULT_FAVICON_URL = "https://assets.softr-files.com/assets/images/favicon.ico"; const TTL_MS = 6e4; const CACHE_CONTROL = "public, max-age=60"; const faviconSchema = z.object({ url: z.string() }); let cached; /** * The URL of the favicon set in Studio, or `null` when there is none. A * failure also reads as `null`, so the app shows the default icon. */ function readStudioFaviconUrl() { return readCached("the favicon setting", TTL_MS, () => cached, (entry) => cached = entry, async () => { const { applicationId } = sessionConfig(); const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${applicationId}/favicon`, { headers: { accept: "application/json" } }); if (response.status === 404) return null; if (!response.ok) throw new Error(`The platform answered ${response.status}`); return faviconSchema.parse(await response.json()).url; }); } /** * Serves the app's favicon at `/favicon.ico`: the one the builder set in * Studio, or the default Softr favicon when there is none. Every other request * passes through untouched. * * Proxied, not redirected: some clients do not follow a redirect for an icon. * * Static files come before request middleware, both in the Vite dev server and * on Cloudflare. So an app with its own `public/favicon.ico` keeps it, and this * answers only when the app has none. */ function faviconMiddleware() { return createMiddleware({ type: "request" }).server(async ({ next, pathname }) => { if (pathname !== FAVICON_PATH) return next(); const iconUrl = await readStudioFaviconUrl() ?? DEFAULT_FAVICON_URL; try { const iconResponse = await fetch(iconUrl); if (!iconResponse.ok) return new Response(null, { status: 404 }); const headers = new Headers({ "cache-control": CACHE_CONTROL }); const contentType = iconResponse.headers.get("content-type"); if (contentType !== null) headers.set("content-type", contentType); return new Response(iconResponse.body, { headers }); } catch (error) { logger.warn("Could not fetch the favicon:", error); return new Response(null, { status: 404 }); } }); } //#endregion export { faviconMiddleware };