diff --git a/packages/cli/src/commands/play.ts b/packages/cli/src/commands/play.ts index 281a884438..8267678d62 100644 --- a/packages/cli/src/commands/play.ts +++ b/packages/cli/src/commands/play.ts @@ -38,6 +38,7 @@ import { listenOnFreePort, refuseUnknownHosts, sandboxForAnotherSite, + scriptsAfterWorkersDropped, refuseProxyWorkForAnotherSite, injectRuntime, injectMediaCodecMap, @@ -342,7 +343,7 @@ function buildPlayerPage(projectName: string): string {
${projectName} — hyperframes play
- + ${scriptsAfterWorkersDropped(["/player.js"])} `; } diff --git a/packages/cli/src/commands/present.ts b/packages/cli/src/commands/present.ts index 832457224d..80d2a933f9 100644 --- a/packages/cli/src/commands/present.ts +++ b/packages/cli/src/commands/present.ts @@ -30,6 +30,7 @@ import { refuseUnknownHosts, refuseFramingByOtherSites, sandboxForAnotherSite, + scriptsAfterWorkersDropped, assetContentType, } from "../utils/compositionServer.js"; import { isPrivateCompositionFile } from "../utils/privateProjectFile.js"; @@ -219,8 +220,7 @@ function buildPresentPage(projectName: string, islandJson: string): string { hyperframes-slideshow { display: block; position: relative; width: 100vw; height: 100vh; } hyperframes-player { position: absolute; inset: 0; } - - + ${scriptsAfterWorkersDropped(["/player.js", "/slideshow.js"])} diff --git a/packages/cli/src/utils/compositionServer.test.ts b/packages/cli/src/utils/compositionServer.test.ts index dc7b3db95f..876a437e1a 100644 --- a/packages/cli/src/utils/compositionServer.test.ts +++ b/packages/cli/src/utils/compositionServer.test.ts @@ -3,7 +3,11 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { hostname, networkInterfaces, tmpdir } from "node:os"; import { join } from "node:path"; import { Hono } from "hono"; -import { buildRangeResponse, refuseUnknownHosts } from "./compositionServer.js"; +import { + buildRangeResponse, + refuseUnknownHosts, + scriptsAfterWorkersDropped, +} from "./compositionServer.js"; const TAGGED_PNG = Buffer.from( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGNJQ1ABAQABlXPCVgAAAAxJREFUeJxj0NfXBwABHgCOTp25kgAAAABJRU5ErkJggg==", @@ -89,3 +93,25 @@ describe("refuseUnknownHosts", () => { expect(await res.text()).toBe("project file"); }); }); + +describe("scriptsAfterWorkersDropped", () => { + it("adds the page's scripts in order only after every worker on the origin is unregistered", async () => { + const steps: string[] = []; + const registrations = [{ unregister: async () => void steps.push("unregister") }]; + const navigator = { serviceWorker: { getRegistrations: async () => registrations } }; + const head = { append: (s: { src: string }) => void steps.push(`load ${s.src}`) }; + const document = { head, createElement: () => ({ src: "", async: true }) }; + const html = scriptsAfterWorkersDropped(["/player.js", "/slideshow.js"]); + const script = html.slice("".length); + await new Function("navigator", "document", `return ${script.replace(/;$/, "")}`)( + navigator, + document, + ); + expect(steps).toEqual(["unregister", "load /player.js", "load /slideshow.js"]); + }); + + it("keeps a source that holds a closing tag inside its one script", () => { + const html = scriptsAfterWorkersDropped(["/a.js"]); + expect(html.indexOf("")).toBe(html.length - "".length); + }); +}); diff --git a/packages/cli/src/utils/compositionServer.ts b/packages/cli/src/utils/compositionServer.ts index a2a7cc4d3c..8f83a17d4f 100644 --- a/packages/cli/src/utils/compositionServer.ts +++ b/packages/cli/src/utils/compositionServer.ts @@ -9,7 +9,10 @@ import { fileURLToPath } from "node:url"; import { getMimeType, openRangeEnd } from "@hyperframes/studio-server"; import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags"; import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document"; -import { PREVIEW_FOR_ANOTHER_SITE_META } from "@hyperframes/core/studio-preview-mark"; +import { + PREVIEW_FOR_ANOTHER_SITE_META, + dropServiceWorkers, +} from "@hyperframes/core/studio-preview-mark"; import { PREVIEW_ALLOWED_HOSTS_ENV, previewAllowedHostsFromEnv, @@ -299,3 +302,14 @@ export async function listenOnFreePort(server: PortBindable, startPort: number): } throw new Error(`No free port found in [${startPort}, ${startPort + 9}]`); } + +export function scriptsAfterWorkersDropped(srcs: readonly string[]): string { + const add = + 'var s=document.createElement("script");s.src=src;s.async=false;document.head.append(s)'; + const list = JSON.stringify(srcs).replace( + /[<>/\u2028\u2029]/g, + (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); + const load = `function(){${list}.forEach(function(src){${add}})}`; + return ``; +} diff --git a/packages/core/src/studioPreviewMark.test.ts b/packages/core/src/studioPreviewMark.test.ts index 4a04d7e3db..cebe2985e4 100644 --- a/packages/core/src/studioPreviewMark.test.ts +++ b/packages/core/src/studioPreviewMark.test.ts @@ -1,5 +1,9 @@ -import { describe, expect, it } from "vitest"; -import { refusedPreviewMessage, refusedPreviewStatus } from "./studioPreviewMark"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + dropServiceWorkers, + refusedPreviewMessage, + refusedPreviewStatus, +} from "./studioPreviewMark"; describe("refusedPreviewStatus", () => { it.each([404, 410, 500])("reads %i back out of the refused page's message", (status) => { @@ -14,3 +18,19 @@ describe("refusedPreviewStatus", () => { expect(refusedPreviewStatus(cause)).toBeNull(); }); }); + +describe("dropServiceWorkers", () => { + const stub = (workers: unknown) => vi.stubGlobal("navigator", { serviceWorker: workers }); + afterEach(() => vi.unstubAllGlobals()); + + it("unregisters every worker on the origin, and resolves when there is none or the browser refuses", async () => { + const all = [{ unregister: vi.fn(async () => true) }, { unregister: vi.fn(async () => true) }]; + stub({ getRegistrations: async () => all }); + await dropServiceWorkers(); + for (const each of all) expect(each.unregister).toHaveBeenCalledOnce(); + stub(undefined); + await expect(dropServiceWorkers()).resolves.toBeUndefined(); + stub({ getRegistrations: async () => Promise.reject(new Error("SecurityError")) }); + await expect(dropServiceWorkers()).resolves.toBeUndefined(); + }); +}); diff --git a/packages/core/src/studioPreviewMark.ts b/packages/core/src/studioPreviewMark.ts index 2e0db151eb..a06f7ac9a3 100644 --- a/packages/core/src/studioPreviewMark.ts +++ b/packages/core/src/studioPreviewMark.ts @@ -88,3 +88,15 @@ export function applyAuthoredTiming( for (const [name, value] of attrs) el.setAttribute(name, value); el.removeAttribute(RUNTIME_STAMPED_ATTR); } + +export function dropServiceWorkers(): Promise { + const workers = typeof navigator === "undefined" ? undefined : navigator.serviceWorker; + if (!workers) return Promise.resolve(); + return workers + .getRegistrations() + .then((all) => Promise.all(all.map((each) => each.unregister()))) + .then( + () => undefined, + () => undefined, + ); +} diff --git a/packages/studio/src/main.tsx b/packages/studio/src/main.tsx index ff8735e274..2231e52a1c 100644 --- a/packages/studio/src/main.tsx +++ b/packages/studio/src/main.tsx @@ -13,6 +13,7 @@ import { } from "./utils/rejectionTelemetry"; import { prefetchPreviewForHash } from "./utils/previewPrefetch"; import { bindThumbnailPageLifecycle } from "./player/lib/thumbnailPageLifecycle"; +import { dropServiceWorkers } from "@hyperframes/core/studio-preview-mark"; import "./styles/studio.css"; const unbindThumbnailPageLifecycle = bindThumbnailPageLifecycle(window, document); @@ -110,16 +111,18 @@ window.addEventListener("unhandledrejection", (event) => { trackStudioEvent("unhandled_promise_rejection", props); }); -createRoot(document.getElementById("root")!).render( - - {/* One icon size and weight for the whole app, taken from the theme file. +void dropServiceWorkers().then(() => + createRoot(document.getElementById("root")!).render( + + {/* One icon size and weight for the whole app, taken from the theme file. Icons that pass their own size or weight still win. */} - - - - - - - - , + + + + + + + + , + ), );