mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
feat(app): support building the web app under a base path (#64597)
Co-authored-by: Brendan <brendan@anoma.ly>
This commit is contained in:
committed by
GitHub
Unverified
parent
352c3df480
commit
a96327d3e8
@@ -10,13 +10,13 @@
|
||||
<title data-sm>OpenCode</title>
|
||||
<link rel="icon" type="image/x-icon" href="%OPENCODE_FAVICON%" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="%OPENCODE_APPLE_TOUCH_ICON%" />
|
||||
<link rel="manifest" href="/site.webmanifest" crossorigin="use-credentials" />
|
||||
<link rel="manifest" href="%BASE_URL%site.webmanifest" crossorigin="use-credentials" />
|
||||
<meta name="theme-color" content="#fafafa" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta property="og:image" content="/social-share.png" />
|
||||
<meta property="twitter:image" content="/social-share.png" />
|
||||
<meta property="twitter:image" content="%BASE_URL%social-share.png" />
|
||||
<script id="oc-theme-preload-script" src="/oc-theme-preload.js"></script>
|
||||
</head>
|
||||
<body
|
||||
|
||||
@@ -30,6 +30,7 @@ import { TabsProvider } from "@/shell/tabs/tabs"
|
||||
import { ErrorPage } from "@/shell/errors/error"
|
||||
import { AppRoutes, File, preloadRoute } from "@/shell/routes/routes"
|
||||
import { PluginRoot } from "@/runtime/plugin/root"
|
||||
import { baseRouter } from "@/runtime/platform/base-path-router"
|
||||
|
||||
export { preloadRoute }
|
||||
|
||||
@@ -125,7 +126,7 @@ export function AppInterface(props: {
|
||||
return (
|
||||
<ServersProvider canonicalLocalServer={props.canonicalLocalServer} servers={props.servers}>
|
||||
<SettingsProvider>
|
||||
<Dynamic component={props.router ?? Router} root={Root}>
|
||||
<Dynamic component={props.router ?? baseRouter ?? Router} root={Root}>
|
||||
<AppRoutes />
|
||||
</Dynamic>
|
||||
</SettingsProvider>
|
||||
|
||||
@@ -53,7 +53,9 @@ const clearAuthToken = () => {
|
||||
const web = createWebPlatform(import.meta.env.VITE_OPENCODE_VERSION ?? pkg.version)
|
||||
|
||||
if (import.meta.env.PROD && "serviceWorker" in navigator) {
|
||||
window.addEventListener("load", () => void navigator.serviceWorker.register("/sw.js"), { once: true })
|
||||
window.addEventListener("load", () => void navigator.serviceWorker.register(`${import.meta.env.BASE_URL}sw.js`), {
|
||||
once: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (import.meta.env.VITE_SENTRY_DSN) {
|
||||
|
||||
Vendored
+2
@@ -1,4 +1,6 @@
|
||||
interface ImportMetaEnv {
|
||||
/** Vite's `base`, the path the build is served under, such as `/opencode/`; `/` at the root. */
|
||||
readonly BASE_URL: string
|
||||
readonly VITE_OPENCODE_SERVER_MODE?: "none" | "origin"
|
||||
readonly VITE_OPENCODE_SERVER_HOST: string
|
||||
readonly VITE_OPENCODE_SERVER_PORT: string
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
type BaseRouterProps,
|
||||
createBeforeLeave,
|
||||
createRouter,
|
||||
keepDepth,
|
||||
notifyIfNotBlocked,
|
||||
saveCurrentDepth,
|
||||
} from "@solidjs/router"
|
||||
import { basePath, stripBasePath, withBasePath } from "@/runtime/platform/base-path"
|
||||
|
||||
/**
|
||||
* A history router for builds served under a base path. Unlike the router's own `base`, it keeps every route path the
|
||||
* app sees base-free, so code reading `useLocation().pathname` or navigating to it works the same under any base.
|
||||
*/
|
||||
export function BasePathRouter(props: BaseRouterProps) {
|
||||
const read = () => {
|
||||
const state = history.state
|
||||
|
||||
return {
|
||||
value: stripBasePath(location.pathname + location.search + location.hash),
|
||||
// The router marks its own entries with only a depth; that is not app state.
|
||||
state: state && state._depth && Object.keys(state).length === 1 ? undefined : state,
|
||||
}
|
||||
}
|
||||
|
||||
const beforeLeave = createBeforeLeave()
|
||||
|
||||
return createRouter({
|
||||
get: read,
|
||||
set({ value, replace, scroll, state }) {
|
||||
const url = withBasePath(value)
|
||||
|
||||
if (replace) history.replaceState(keepDepth(state), "", url)
|
||||
else history.pushState(state, "", url)
|
||||
|
||||
const hash = decodeURIComponent(location.hash.slice(1))
|
||||
const target = hash && document.getElementById(hash)
|
||||
|
||||
if (target) target.scrollIntoView()
|
||||
else if (scroll) window.scrollTo(0, 0)
|
||||
|
||||
saveCurrentDepth()
|
||||
},
|
||||
init: (notify) => {
|
||||
const handler = notifyIfNotBlocked(notify, (delta) => {
|
||||
if (delta) return !beforeLeave.confirm(delta)
|
||||
|
||||
const source = read()
|
||||
|
||||
return !beforeLeave.confirm(source.value, { state: source.state })
|
||||
})
|
||||
|
||||
window.addEventListener("popstate", handler)
|
||||
|
||||
return () => window.removeEventListener("popstate", handler)
|
||||
},
|
||||
utils: {
|
||||
go: (delta) => history.go(delta),
|
||||
renderPath: withBasePath,
|
||||
parsePath: stripBasePath,
|
||||
beforeLeave,
|
||||
},
|
||||
})(props)
|
||||
}
|
||||
|
||||
export const baseRouter = basePath ? BasePathRouter : undefined
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { normalizeBasePath, stripBasePath, withBasePath } from "./base-path"
|
||||
|
||||
describe("normalizeBasePath", () => {
|
||||
test("is empty at the root", () => {
|
||||
expect(normalizeBasePath(undefined)).toBe("")
|
||||
expect(normalizeBasePath("/")).toBe("")
|
||||
expect(normalizeBasePath("")).toBe("")
|
||||
})
|
||||
|
||||
test("has a leading slash and no trailing slash", () => {
|
||||
expect(normalizeBasePath("/opencode/")).toBe("/opencode")
|
||||
expect(normalizeBasePath("opencode")).toBe("/opencode")
|
||||
expect(normalizeBasePath("//a/b//")).toBe("/a/b")
|
||||
})
|
||||
})
|
||||
|
||||
describe("withBasePath", () => {
|
||||
test("leaves paths alone at the root", () => {
|
||||
expect(withBasePath("/new-session?x=1", "")).toBe("/new-session?x=1")
|
||||
})
|
||||
|
||||
test("prefixes paths with the base", () => {
|
||||
expect(withBasePath("/", "/opencode")).toBe("/opencode/")
|
||||
expect(withBasePath("/server/a/session/b#m", "/opencode")).toBe("/opencode/server/a/session/b#m")
|
||||
})
|
||||
})
|
||||
|
||||
describe("stripBasePath", () => {
|
||||
test("leaves paths alone at the root", () => {
|
||||
expect(stripBasePath("/new-session", "")).toBe("/new-session")
|
||||
})
|
||||
|
||||
test("removes the base", () => {
|
||||
expect(stripBasePath("/opencode", "/opencode")).toBe("/")
|
||||
expect(stripBasePath("/opencode/", "/opencode")).toBe("/")
|
||||
expect(stripBasePath("/opencode?draftId=1", "/opencode")).toBe("/?draftId=1")
|
||||
expect(stripBasePath("/opencode/new-session#top", "/opencode")).toBe("/new-session#top")
|
||||
})
|
||||
|
||||
test("keeps paths outside the base", () => {
|
||||
expect(stripBasePath("/opencode-other/x", "/opencode")).toBe("/opencode-other/x")
|
||||
expect(stripBasePath("/elsewhere", "/opencode")).toBe("/elsewhere")
|
||||
})
|
||||
|
||||
test("round-trips with withBasePath", () => {
|
||||
for (const path of ["/", "/new-session", "/server/a/session/b?q=1#h"])
|
||||
expect(stripBasePath(withBasePath(path, "/opencode"), "/opencode")).toBe(path)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
/** The path a build is served under, such as `/opencode`, without a trailing slash; empty at the root. */
|
||||
export const basePath = normalizeBasePath(import.meta.env.BASE_URL)
|
||||
|
||||
export function normalizeBasePath(base: string | undefined) {
|
||||
const trimmed = (base ?? "").replace(/^\/+|\/+$/g, "")
|
||||
|
||||
return trimmed ? `/${trimmed}` : ""
|
||||
}
|
||||
|
||||
/** The browser path for an app path, such as `/opencode/new-session` for `/new-session`. */
|
||||
export function withBasePath(path: string, base = basePath) {
|
||||
if (!base) return path
|
||||
|
||||
return path === "/" ? `${base}/` : `${base}${path}`
|
||||
}
|
||||
|
||||
/** The app path for a browser path, or the path itself when it lies outside the base. */
|
||||
export function stripBasePath(path: string, base = basePath) {
|
||||
if (!base || !path.startsWith(base)) return path
|
||||
|
||||
const rest = path.slice(base.length)
|
||||
|
||||
if (rest.startsWith("/")) return rest
|
||||
|
||||
if (rest === "" || rest.startsWith("?") || rest.startsWith("#")) return `/${rest}`
|
||||
|
||||
return path
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useLocation } from "@solidjs/router"
|
||||
import { createEffect } from "solid-js"
|
||||
import { stripBasePath, withBasePath } from "./base-path"
|
||||
|
||||
const LAST_ROUTE_KEY = "opencode.pwa.last-route"
|
||||
|
||||
@@ -11,7 +12,7 @@ export function isStandalone() {
|
||||
}
|
||||
|
||||
export function restorePwaRoute() {
|
||||
if (location.pathname !== "/" || location.search || location.hash) return
|
||||
if (stripBasePath(location.pathname) !== "/" || location.search || location.hash) return
|
||||
|
||||
try {
|
||||
const value = localStorage.getItem(LAST_ROUTE_KEY)
|
||||
@@ -27,7 +28,7 @@ export function restorePwaRoute() {
|
||||
!/^\/server\/[^/]+\/session\/[^/]+$/.test(url.pathname)
|
||||
)
|
||||
return
|
||||
history.replaceState(history.state, "", url.pathname + url.search + url.hash)
|
||||
history.replaceState(history.state, "", withBasePath(url.pathname) + url.search + url.hash)
|
||||
} catch {
|
||||
// Storage may be unavailable; keep the launch URL in that case.
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createBrowserDraftStore } from "@/runtime/persistence/drafts"
|
||||
import { basePath } from "./base-path"
|
||||
import type { Platform } from "./platform"
|
||||
|
||||
export function createWebPlatform(version: string) {
|
||||
@@ -57,5 +58,6 @@ function getCurrentServerUrl() {
|
||||
return `http://${host}:${import.meta.env.VITE_OPENCODE_SERVER_PORT ?? "4096"}`
|
||||
}
|
||||
|
||||
return location.origin
|
||||
// A build under a base path reaches the server through the same prefix.
|
||||
return location.origin + basePath
|
||||
}
|
||||
|
||||
@@ -229,7 +229,10 @@ export function createServerTransport(input: {
|
||||
http: ServerConnection.HttpBase
|
||||
fetch?: typeof globalThis.fetch
|
||||
}): ServerTransport {
|
||||
const queue = createRequestQueue({ fetch: input.fetch ?? globalThis.fetch })
|
||||
const queue = createRequestQueue({
|
||||
fetch: input.fetch ?? globalThis.fetch,
|
||||
prefix: () => serverPathPrefix(state.current.http.url),
|
||||
})
|
||||
|
||||
// Keeps the endpoint as plain values: a plugin's endpoint can be a store proxy that already reads the next password,
|
||||
// and the client built here keeps the one it started with.
|
||||
@@ -290,3 +293,10 @@ function createDirSdkContext(directory: string, serverSDK: ServerSDKBase): Locat
|
||||
event: serverSDK.event.location(directory),
|
||||
}
|
||||
}
|
||||
|
||||
/** The path a server URL sits under, such as `/opencode` for `https://host/opencode/`; empty at the root. */
|
||||
function serverPathPrefix(url: string) {
|
||||
if (!URL.canParse(url)) return ""
|
||||
|
||||
return new URL(url).pathname.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
classifyRequest,
|
||||
createRequestQueueState,
|
||||
selectInflightCount,
|
||||
selectQueuedCount,
|
||||
@@ -125,3 +126,26 @@ describe("transitionRequestQueue", () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("classifyRequest", () => {
|
||||
test("classifies API paths under a server path prefix like those at the root", () => {
|
||||
const paths = [
|
||||
["GET", "/api/event"],
|
||||
["GET", "/api/session"],
|
||||
["GET", "/api/session/ses_1/message"],
|
||||
["GET", "/api/vcs/diff"],
|
||||
["POST", "/api/worktree"],
|
||||
["GET", "/api/project"],
|
||||
] as const
|
||||
|
||||
for (const [method, path] of paths)
|
||||
expect(classifyRequest(method, new URL(`http://server/opencode${path}`), "/opencode")).toEqual(
|
||||
classifyRequest(method, new URL(`http://server${path}`)),
|
||||
)
|
||||
})
|
||||
|
||||
test("leaves paths outside the prefix alone", () => {
|
||||
expect(classifyRequest("GET", new URL("http://server/api/event"), "/opencode").bypass).toBe(true)
|
||||
expect(classifyRequest("GET", new URL("http://server/opencode-other/api/event"), "/opencode").bypass).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -149,9 +149,11 @@ export function isRequestInflight(state: RequestQueueState, id: number) {
|
||||
/**
|
||||
* The event stream bypasses the queue. Writes go first. Session lists and the first transcript page unblock
|
||||
* navigation, so they go ahead of location reads. Older pages and filtered indexes keep background priority.
|
||||
* `prefix` is the server URL's path, such as `/opencode`, when the server sits under one.
|
||||
*/
|
||||
export function classifyRequest(method: string, url: URL): RequestClassification {
|
||||
const pathname = url.pathname
|
||||
export function classifyRequest(method: string, url: URL, prefix = ""): RequestClassification {
|
||||
// A server behind a path prefix serves its API under it; classify the path the server sees.
|
||||
const pathname = prefix && url.pathname.startsWith(`${prefix}/`) ? url.pathname.slice(prefix.length) : url.pathname
|
||||
|
||||
// The event stream is long-lived; never count it against the request budget.
|
||||
if (pathname === "/api/event") return bypass
|
||||
|
||||
@@ -8,6 +8,7 @@ function setup(input?: {
|
||||
stallMs?: number
|
||||
headersTimeoutMs?: number
|
||||
setupHeadersTimeoutMs?: number
|
||||
prefix?: string
|
||||
}) {
|
||||
const pending: Array<{ url: string; signal: AbortSignal; resolve: () => void }> = []
|
||||
const logs: Array<{ message: string; data: RequestStallSnapshot }> = []
|
||||
@@ -19,6 +20,7 @@ function setup(input?: {
|
||||
stallMs: input?.stallMs,
|
||||
headersTimeoutMs: input?.headersTimeoutMs,
|
||||
setupHeadersTimeoutMs: input?.setupHeadersTimeoutMs,
|
||||
prefix: () => input?.prefix ?? "",
|
||||
now: () => clock,
|
||||
log: (message, data) => logs.push({ message, data }),
|
||||
fetch: Object.assign(
|
||||
@@ -159,6 +161,18 @@ describe("createRequestQueue", () => {
|
||||
expect(input.queue.inflight()).toBe(1)
|
||||
})
|
||||
|
||||
test("never counts the event stream of a server under a path prefix against the budget", async () => {
|
||||
const input = setup({ limit: 1, prefix: "/opencode" })
|
||||
void input.queue.fetch("http://server/opencode/api/session")
|
||||
void input.queue.fetch("http://server/opencode/api/event")
|
||||
await input.settle()
|
||||
expect(input.pending.map((item) => new URL(item.url).pathname).toSorted()).toEqual([
|
||||
"/opencode/api/event",
|
||||
"/opencode/api/session",
|
||||
])
|
||||
expect(input.queue.inflight()).toBe(1)
|
||||
})
|
||||
|
||||
test("a queued request leaves without being sent as soon as its caller aborts, while every slot stays stuck", async () => {
|
||||
const input = setup({ limit: 1, stallMs: 5 })
|
||||
const controller = new AbortController()
|
||||
|
||||
@@ -26,6 +26,8 @@ const setupRequestHeadersTimeoutMs = 10 * 60_000
|
||||
|
||||
export function createRequestQueue(input: {
|
||||
fetch: typeof globalThis.fetch
|
||||
/** The server URL's path, such as `/opencode`, when the server sits under a prefix. */
|
||||
prefix?: () => string
|
||||
limit?: number
|
||||
slowLimit?: number
|
||||
stallMs?: number
|
||||
@@ -106,7 +108,7 @@ export function createRequestQueue(input: {
|
||||
const fetch: typeof globalThis.fetch = Object.assign(
|
||||
async (resource: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(resource, init)
|
||||
const kind = classifyRequest(request.method, new URL(request.url))
|
||||
const kind = classifyRequest(request.method, new URL(request.url), input.prefix?.())
|
||||
|
||||
if (kind.bypass) return base(request)
|
||||
|
||||
|
||||
+26
-18
@@ -1,6 +1,6 @@
|
||||
import { sentryVitePlugin } from "@sentry/vite-plugin"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { defineConfig } from "vite"
|
||||
import { defineConfig, type Plugin, type UserConfig } from "vite"
|
||||
import desktopPlugin, { channel } from "./vite.js"
|
||||
import { icons } from "./vite.icons"
|
||||
import { serviceWorker } from "./vite.pwa"
|
||||
@@ -22,8 +22,32 @@ const sentry =
|
||||
})
|
||||
: false
|
||||
|
||||
// The app is built for the root by default; `vite build --base=/opencode/` serves it under that path. A base without
|
||||
// its trailing slash would reach `import.meta.env.BASE_URL` and `%BASE_URL%` as is and glue paths onto it.
|
||||
const basePath: Plugin = {
|
||||
name: "opencode-app:base-path",
|
||||
config(config) {
|
||||
if (config.base?.startsWith("/") && !config.base.endsWith("/")) return { base: `${config.base}/` }
|
||||
},
|
||||
}
|
||||
|
||||
// The e2e build also emits the fixture pages the tests open beside the app.
|
||||
const testFixtureInput = [
|
||||
"index.html",
|
||||
"e2e/utils/settings-wsl.html",
|
||||
"e2e/utils/app-direction.html",
|
||||
"e2e/utils/windows-menu.html",
|
||||
]
|
||||
|
||||
const build: UserConfig["build"] = { assetsDir: "_assets", target: "esnext", sourcemap: true }
|
||||
|
||||
if (process.env.VITE_OPENCODE_TEST_FIXTURES === "1") build.rolldownOptions = { input: testFixtureInput }
|
||||
|
||||
export default defineConfig({
|
||||
// SAFETY: the plugins are typed against the different Vite versions their packages depend on, but all of them only
|
||||
// use hooks this Vite runs.
|
||||
plugins: [
|
||||
basePath,
|
||||
desktopPlugin,
|
||||
icons(channel),
|
||||
serviceWorker(fileURLToPath(new URL("./dist", import.meta.url))),
|
||||
@@ -34,21 +58,5 @@ export default defineConfig({
|
||||
allowedHosts: true,
|
||||
port: 3000,
|
||||
},
|
||||
build: {
|
||||
...(process.env.VITE_OPENCODE_TEST_FIXTURES === "1"
|
||||
? {
|
||||
rolldownOptions: {
|
||||
input: [
|
||||
"index.html",
|
||||
"e2e/utils/settings-wsl.html",
|
||||
"e2e/utils/app-direction.html",
|
||||
"e2e/utils/windows-menu.html",
|
||||
],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
assetsDir: "_assets",
|
||||
target: "esnext",
|
||||
sourcemap: true,
|
||||
},
|
||||
build,
|
||||
})
|
||||
|
||||
@@ -33,6 +33,40 @@ test.each(["dev", "beta", "prod", "local"])("bundles %s app icons", async (chann
|
||||
})
|
||||
})
|
||||
|
||||
test("bundles app icons under a base path", async () => {
|
||||
const result = await build({
|
||||
root: import.meta.dirname,
|
||||
configFile: false,
|
||||
logLevel: "silent",
|
||||
base: "/opencode/",
|
||||
plugins: [
|
||||
icons("prod"),
|
||||
{
|
||||
name: "icons-only-fixture",
|
||||
transformIndexHtml: {
|
||||
order: "pre",
|
||||
handler: (html) => html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g, ""),
|
||||
},
|
||||
},
|
||||
],
|
||||
build: { write: false, copyPublicDir: false },
|
||||
})
|
||||
|
||||
if (!("output" in result)) throw new Error("Expected a single build output")
|
||||
|
||||
await check(
|
||||
"prod",
|
||||
async (path) => {
|
||||
const file = result.output.find((file) => `/${file.fileName}` === path)
|
||||
|
||||
if (file?.type !== "asset") throw new Error(`Missing asset: ${path}`)
|
||||
|
||||
return new Uint8Array(Buffer.from(file.source))
|
||||
},
|
||||
"/opencode/",
|
||||
)
|
||||
})
|
||||
|
||||
test.each(["dev", "beta", "prod"])("serves %s app icons", async (channel) => {
|
||||
const server = await createServer({
|
||||
root: import.meta.dirname,
|
||||
@@ -64,17 +98,20 @@ test.each(["dev", "beta", "prod"])("serves %s app icons", async (channel) => {
|
||||
}
|
||||
})
|
||||
|
||||
async function check(channel: string, read: (path: string) => Promise<Uint8Array>) {
|
||||
async function check(channel: string, read: (path: string) => Promise<Uint8Array>, base = "/") {
|
||||
const html = new TextDecoder().decode(await read("/index.html"))
|
||||
const actual: typeof manifest = JSON.parse(new TextDecoder().decode(await read("/site.webmanifest")))
|
||||
expect(actual.icons.some((icon) => icon.purpose === "maskable")).toBe(true)
|
||||
expect(actual).toEqual({
|
||||
...manifest,
|
||||
icons: manifest.icons.map((icon) => ({ ...icon, src: `/icons/${channel}${icon.src}` })),
|
||||
id: base,
|
||||
start_url: base,
|
||||
scope: base,
|
||||
icons: manifest.icons.map((icon) => ({ ...icon, src: `${base}icons/${channel}${icon.src}` })),
|
||||
})
|
||||
expect(html).toContain(`href="/icons/${channel}/favicon.ico"`)
|
||||
expect(html).toContain(`href="/icons/${channel}/apple-touch-icon.png"`)
|
||||
expect(html).toContain(`href="/site.webmanifest"`)
|
||||
expect(html).toContain(`href="${base}icons/${channel}/favicon.ico"`)
|
||||
expect(html).toContain(`href="${base}icons/${channel}/apple-touch-icon.png"`)
|
||||
expect(html).toContain(`href="${base}site.webmanifest"`)
|
||||
expect(html).not.toContain("%OPENCODE_")
|
||||
|
||||
await Promise.all(
|
||||
|
||||
+25
-13
@@ -6,7 +6,7 @@ export function icons(channel: string): Plugin {
|
||||
const selected = channel === "beta" || channel === "prod" ? channel : "dev"
|
||||
const prefix = `icons/${selected}`
|
||||
|
||||
const files = [
|
||||
const iconFiles = [
|
||||
...Object.entries({
|
||||
"favicon.ico": "icon.ico",
|
||||
"apple-touch-icon.png": "ios/AppIcon-60x60@3x.png",
|
||||
@@ -17,24 +17,36 @@ export function icons(channel: string): Plugin {
|
||||
source: readFileSync(new URL(`../desktop/icons/${selected}/${source}`, import.meta.url)),
|
||||
type: name.endsWith(".ico") ? "image/x-icon" : "image/png",
|
||||
})),
|
||||
{
|
||||
fileName: "site.webmanifest",
|
||||
source: JSON.stringify({
|
||||
...manifest,
|
||||
icons: manifest.icons.map((icon) => ({ ...icon, src: `/${prefix}${icon.src}` })),
|
||||
}),
|
||||
type: "application/manifest+json",
|
||||
},
|
||||
]
|
||||
|
||||
// Vite's resolved `base`, such as `/opencode/` for `vite build --base=/opencode/`.
|
||||
let base = "/"
|
||||
|
||||
const webManifest = () => ({
|
||||
fileName: "site.webmanifest",
|
||||
source: JSON.stringify({
|
||||
...manifest,
|
||||
id: base,
|
||||
start_url: base,
|
||||
scope: base,
|
||||
icons: manifest.icons.map((icon) => ({ ...icon, src: `${base}${prefix}${icon.src}` })),
|
||||
}),
|
||||
type: "application/manifest+json",
|
||||
})
|
||||
|
||||
const files = () => [...iconFiles, webManifest()]
|
||||
|
||||
return {
|
||||
name: "opencode-app:icons",
|
||||
configResolved(config) {
|
||||
base = config.base
|
||||
},
|
||||
generateBundle() {
|
||||
files.forEach((file) => this.emitFile({ type: "asset", fileName: file.fileName, source: file.source }))
|
||||
files().forEach((file) => this.emitFile({ type: "asset", fileName: file.fileName, source: file.source }))
|
||||
},
|
||||
configureServer(server) {
|
||||
server.middlewares.use((request, response, next) => {
|
||||
const file = files.find((file) => `/${file.fileName}` === request.url?.split("?")[0])
|
||||
const file = files().find((file) => `${base}${file.fileName}` === request.url?.split("?")[0])
|
||||
|
||||
if (!file) return next()
|
||||
response.setHeader("Content-Type", file.type)
|
||||
@@ -45,8 +57,8 @@ export function icons(channel: string): Plugin {
|
||||
order: "pre",
|
||||
handler(html) {
|
||||
return html
|
||||
.replace("%OPENCODE_FAVICON%", `/${prefix}/favicon.ico`)
|
||||
.replace("%OPENCODE_APPLE_TOUCH_ICON%", `/${prefix}/apple-touch-icon.png`)
|
||||
.replace("%OPENCODE_FAVICON%", `${base}${prefix}/favicon.ico`)
|
||||
.replace("%OPENCODE_APPLE_TOUCH_ICON%", `${base}${prefix}/apple-touch-icon.png`)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -19,6 +19,22 @@ export function serviceWorker(directory: string) {
|
||||
registerType: "prompt",
|
||||
injectRegister: false,
|
||||
manifest: false,
|
||||
integration: {
|
||||
// The fallback and denylist follow Vite's resolved `base`, such as `/opencode/` for `vite build --base=/opencode/`.
|
||||
configureOptions(config, options) {
|
||||
const prefix = config.base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
|
||||
options.workbox = {
|
||||
...options.workbox,
|
||||
navigateFallback: `${config.base}index.html`,
|
||||
// Pairing links must reach the server so it can set the session cookie.
|
||||
navigateFallbackDenylist: [
|
||||
new RegExp(`^${prefix}(?:api|auth)(?:/|$)`),
|
||||
new RegExp(`^${prefix}(?:_assets|assets)(?:/|$)`),
|
||||
],
|
||||
}
|
||||
},
|
||||
},
|
||||
workbox: {
|
||||
// Workbox runs after Sentry's upload and cleanup, so do not publish an unuploaded map.
|
||||
sourcemap: false,
|
||||
@@ -27,9 +43,6 @@ export function serviceWorker(directory: string) {
|
||||
// Keep each open tab on its complete build until all old clients close.
|
||||
skipWaiting: false,
|
||||
inlineWorkboxRuntime: true,
|
||||
navigateFallback: "/index.html",
|
||||
// Pairing links must reach the server so it can set the session cookie.
|
||||
navigateFallbackDenylist: [/^\/(?:api|auth)(?:\/|$)/, /^\/(?:_assets|assets)(?:\/|$)/],
|
||||
// Include lazy chunks and non-JS dependencies, not just the startup bundle.
|
||||
globPatterns: ["**/*"],
|
||||
globIgnores: ["**/*.map", "_headers", "_redirects"],
|
||||
|
||||
Reference in New Issue
Block a user