@hyperframes/studio 0.9.53 → 0.9.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/assets/{hyperframes-player-z7r-N5fm.js → hyperframes-player-BroIQA4E.js} +1 -1
  2. package/dist/assets/{index-Dpo7Q_9-.js → index-Be7DZynj.js} +154 -154
  3. package/dist/assets/{index-2QPHxCxy.js → index-CiF0D62S.js} +1 -1
  4. package/dist/assets/{pausedVideoDecoder-BarDYEAf.js → pausedVideoDecoder-RXcvblHS.js} +1 -1
  5. package/dist/{chunk-F6EHWNZU.js → chunk-JMM2CSEL.js} +121 -94
  6. package/dist/{chunk-VHV2ZDKY.js → chunk-OOGQ5KCC.js} +7 -0
  7. package/dist/{chunk-GVW7AU57.js → chunk-UM4CLD4M.js} +1 -1
  8. package/dist/{domEditingLayers-SA5KLSSS.js → domEditingLayers-IHYA42AJ.js} +2 -2
  9. package/dist/index.d.ts +8 -2
  10. package/dist/index.html +1 -1
  11. package/dist/index.js +65 -21
  12. package/dist/player.d.ts +1 -0
  13. package/dist/player.js +2 -2
  14. package/package.json +8 -8
  15. package/src/components/editor/gsapLivePreview.test.ts +19 -0
  16. package/src/components/editor/gsapLivePreview.ts +2 -0
  17. package/src/components/editor/manualEditingAvailability.ts +7 -0
  18. package/src/components/nle/NLEPreview.test.ts +25 -0
  19. package/src/components/nle/NLEPreview.tsx +5 -0
  20. package/src/components/nle/PreviewPane.tsx +2 -0
  21. package/src/components/sidebar/CompositionsTab.tsx +4 -8
  22. package/src/hooks/gsapParsedTween.test.ts +19 -0
  23. package/src/hooks/gsapParsedTween.ts +3 -1
  24. package/src/hooks/useConsoleErrorCapture.test.tsx +69 -1
  25. package/src/hooks/useConsoleErrorCapture.ts +47 -11
  26. package/src/index.ts +1 -0
  27. package/src/player/components/Player.test.ts +55 -0
  28. package/src/player/components/Player.tsx +13 -4
  29. package/src/player/lib/frameToken.ts +20 -0
  30. package/src/player/lib/previewChannel.ts +10 -0
package/dist/player.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  Player
3
- } from "./chunk-F6EHWNZU.js";
3
+ } from "./chunk-JMM2CSEL.js";
4
4
  import "./chunk-G6FJSL7X.js";
5
- import "./chunk-VHV2ZDKY.js";
5
+ import "./chunk-OOGQ5KCC.js";
6
6
  import "./chunk-MLKGABMK.js";
7
7
  export {
8
8
  Player
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/studio",
3
- "version": "0.9.53",
3
+ "version": "0.9.55",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -64,12 +64,12 @@
64
64
  "dockview-react": "8.3.1",
65
65
  "gsap": "^3.13.0",
66
66
  "mediabunny": "^1.66.0",
67
- "@hyperframes/core": "0.9.53",
68
- "@hyperframes/parsers": "0.9.53",
69
- "@hyperframes/player": "0.9.53",
70
- "@hyperframes/sdk": "0.9.53",
71
- "@hyperframes/shader-transitions": "0.9.53",
72
- "@hyperframes/studio-server": "0.9.53"
67
+ "@hyperframes/player": "0.9.55",
68
+ "@hyperframes/core": "0.9.55",
69
+ "@hyperframes/sdk": "0.9.55",
70
+ "@hyperframes/shader-transitions": "0.9.55",
71
+ "@hyperframes/parsers": "0.9.55",
72
+ "@hyperframes/studio-server": "0.9.55"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@tailwindcss/vite": "^4.3.3",
@@ -86,7 +86,7 @@
86
86
  "vite": "^6.4.5",
87
87
  "vitest": "^4.1.12",
88
88
  "zustand": "^5.0.0",
89
- "@hyperframes/producer": "0.9.53"
89
+ "@hyperframes/producer": "0.9.55"
90
90
  },
91
91
  "peerDependencies": {
92
92
  "react": "19",
@@ -106,3 +106,22 @@ it.each([
106
106
  expect(props).toEqual(read);
107
107
  },
108
108
  );
109
+
110
+ /** A preview on an opaque origin: every read of its window but postMessage throws, as a browser's does. */
111
+ function sealedPreview(): HTMLIFrameElement {
112
+ const iframe = document.createElement("iframe");
113
+ const win = new Proxy({} as Record<string, unknown>, {
114
+ get: (_target, key) => {
115
+ if (key === "postMessage") return () => undefined;
116
+ throw new DOMException(`blocked read of ${String(key)}`, "SecurityError");
117
+ },
118
+ });
119
+ Object.defineProperty(iframe, "contentWindow", { value: win });
120
+ Object.defineProperty(iframe, "contentDocument", { value: null });
121
+ return iframe;
122
+ }
123
+
124
+ it("draws nothing on a sealed preview, whose window refuses the read", () => {
125
+ const preview = createGsapLivePreview({ current: sealedPreview() });
126
+ expect(() => preview({ id: "card" } as DomEditSelection, { x: 10 })).not.toThrow();
127
+ });
@@ -1,5 +1,6 @@
1
1
  import type { DomEditSelection } from "./domEditingTypes";
2
2
  import { findPreviewNode } from "./domEditingElement";
3
+ import { previewFrameOpaque } from "../../player/lib/previewChannel";
3
4
 
4
5
  /**
5
6
  * Build the "live preview" callback the 3D-transform sub-view fires while a
@@ -12,6 +13,7 @@ import { findPreviewNode } from "./domEditingElement";
12
13
  export function createGsapLivePreview(iframeRef: { readonly current: HTMLIFrameElement | null }) {
13
14
  return (el: DomEditSelection, props: Record<string, number>) => {
14
15
  const iframe = iframeRef.current;
16
+ if (!iframe || previewFrameOpaque(iframe)) return;
15
17
  const win = iframe?.contentWindow as
16
18
  | { gsap?: { set: (t: Element, v: Record<string, number>) => void } }
17
19
  | null
@@ -86,4 +86,11 @@ export const STUDIO_API_SAME_ORIGIN_CREDENTIALS = resolveStudioBooleanEnvFlag(
86
86
  false,
87
87
  );
88
88
 
89
+ // Off until every Studio reader of the preview frame has its editing-port path.
90
+ export const STUDIO_OPAQUE_PREVIEW_ENABLED = resolveStudioBooleanEnvFlag(
91
+ env,
92
+ ["VITE_STUDIO_OPAQUE_PREVIEW_ENABLED"],
93
+ false,
94
+ );
95
+
89
96
  import { resolveEnabledSdkFamilies } from "../../utils/sdkCutoverPolicy";
@@ -29,6 +29,7 @@ vi.mock("../../player", async () => {
29
29
  onReadyToShowChange?: (ready: boolean) => void;
30
30
  suppressLoadingOverlay?: boolean;
31
31
  style?: React.CSSProperties;
32
+ sandboxOrigin?: "opaque";
32
33
  },
33
34
  ref: React.ForwardedRef<HTMLIFrameElement>,
34
35
  ) {
@@ -41,6 +42,7 @@ vi.mock("../../player", async () => {
41
42
  return React.createElement("div", {
42
43
  ref: ref as React.ForwardedRef<HTMLDivElement>,
43
44
  "data-testid": "mock-player",
45
+ "data-sandbox-origin": props.sandboxOrigin,
44
46
  style: props.style,
45
47
  });
46
48
  }),
@@ -89,10 +91,12 @@ function renderPreview(
89
91
  box = { width: 800, height: 600 },
90
92
  fillBox,
91
93
  compositionSizeHint,
94
+ sandboxOrigin,
92
95
  }: {
93
96
  box?: { width: number; height: number };
94
97
  fillBox?: boolean;
95
98
  compositionSizeHint?: { width: number; height: number };
99
+ sandboxOrigin?: "opaque";
96
100
  } = {},
97
101
  ) {
98
102
  resizeCallbacks = [];
@@ -116,6 +120,7 @@ function renderPreview(
116
120
  resetPreviewSlots: () => {},
117
121
  fillBox,
118
122
  compositionSizeHint,
123
+ sandboxOrigin,
119
124
  }),
120
125
  );
121
126
  });
@@ -533,6 +538,26 @@ describe("NLEPreview", () => {
533
538
  view.cleanup();
534
539
  });
535
540
 
541
+ it.each([["opaque" as const], [undefined]])(
542
+ "gives every player it draws the host's sandbox origin (%s)",
543
+ (sandboxOrigin) => {
544
+ const view = renderPreview(
545
+ [
546
+ { gen: 0, role: "live" },
547
+ { gen: 1, role: "shadow", url: "/api/projects/p/preview?_t=1" },
548
+ ],
549
+ { sandboxOrigin },
550
+ );
551
+ view.render("/api/projects/p/preview/components/card.html", "p");
552
+ const players = [...view.stage.querySelectorAll('[data-testid="mock-player"]')];
553
+ expect(players).toHaveLength(3);
554
+ for (const player of players) {
555
+ expect(player.getAttribute("data-sandbox-origin")).toBe(sandboxOrigin ?? null);
556
+ }
557
+ view.cleanup();
558
+ },
559
+ );
560
+
536
561
  it("covers the live preview with the cached frame-0 poster until it is ready to show", () => {
537
562
  const view = renderPreview();
538
563
  const poster = () =>
@@ -58,6 +58,7 @@ interface NLEPreviewProps extends Pick<
58
58
  /** Draws the picture edge to edge in this box, without Studio's inset band. */
59
59
  fillBox?: boolean;
60
60
  compositionSizeHint?: PreviewCompositionSize;
61
+ sandboxOrigin?: "opaque";
61
62
  }
62
63
 
63
64
  export function getPreviewPlayerKey({
@@ -92,6 +93,7 @@ export const NLEPreview = memo(function NLEPreview({
92
93
  onCompositionSizeChange,
93
94
  fillBox,
94
95
  compositionSizeHint,
96
+ sandboxOrigin,
95
97
  }: NLEPreviewProps) {
96
98
  const activeKey = getPreviewPlayerKey({ projectId, directUrl });
97
99
  const viewportRef = useRef<HTMLDivElement>(null);
@@ -487,6 +489,7 @@ export const NLEPreview = memo(function NLEPreview({
487
489
  onLoad={() => {}}
488
490
  portrait={portrait}
489
491
  suppressLoadingOverlay
492
+ sandboxOrigin={sandboxOrigin}
490
493
  style={{ position: "absolute", inset: 0, zIndex: 0 }}
491
494
  />
492
495
  )}
@@ -509,6 +512,7 @@ export const NLEPreview = memo(function NLEPreview({
509
512
  portrait={portrait}
510
513
  suppressLoadingOverlay={suppressLoadingOverlay}
511
514
  loadingUi={loadingUi}
515
+ sandboxOrigin={sandboxOrigin}
512
516
  style={
513
517
  directUrl?.includes("/components/")
514
518
  ? { position: "absolute", inset: 0, zIndex: 1 }
@@ -528,6 +532,7 @@ export const NLEPreview = memo(function NLEPreview({
528
532
  portrait={portrait}
529
533
  suppressLoadingOverlay
530
534
  noLoadTimeout
535
+ sandboxOrigin={sandboxOrigin}
531
536
  style={SHADOW_IFRAME_STYLE}
532
537
  />
533
538
  ),
@@ -8,6 +8,7 @@ import { useNLEContext } from "./NLEContext";
8
8
  import { AssetPreviewOverlay } from "./AssetPreviewOverlay";
9
9
  import { PreviewGuides } from "../editor/PreviewGuides";
10
10
  import { PreviewOverlayProvider } from "../editor/PreviewOverlayProvider";
11
+ import { STUDIO_OPAQUE_PREVIEW_ENABLED } from "../editor/manualEditingAvailability";
11
12
 
12
13
  function subscribeFullscreen(cb: () => void) {
13
14
  document.addEventListener("fullscreenchange", cb);
@@ -150,6 +151,7 @@ export function PreviewPane({
150
151
  suppressLoadingOverlay={hasLoadedOnceRef.current}
151
152
  onStageRef={handleStageRef}
152
153
  onCompositionSizeChange={setPreviewCompositionSize}
154
+ sandboxOrigin={STUDIO_OPAQUE_PREVIEW_ENABLED ? "opaque" : undefined}
153
155
  />
154
156
  {previewDragOver && (
155
157
  <div className="absolute inset-2 z-40 rounded-lg border-2 border-dashed border-studio-accent/50 bg-studio-accent/4 pointer-events-none" />
@@ -1,5 +1,5 @@
1
1
  import { buildProjectApiPath } from "../../utils/projectRouting";
2
- import { studioApiFetch } from "../../utils/studioApiFetch";
2
+ import { fetchFrameToken } from "../../player/lib/frameToken";
3
3
  import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
4
4
  import { useThumbnailLease } from "../../hooks/useThumbnailLease";
5
5
  import {
@@ -72,13 +72,9 @@ function useFreshFrameToken(projectId: string, wanted: boolean): string | null |
72
72
  useEffect(() => {
73
73
  if (!wanted) return setKnown(undefined);
74
74
  let live = true;
75
- void studioApiFetch(buildProjectApiPath(projectId, "/frame-token"))
76
- .then((res) => (res.ok ? res.json() : null))
77
- .then((body: { token?: unknown } | null) =>
78
- typeof body?.token === "string" ? body.token : null,
79
- )
80
- .catch(() => null)
81
- .then((token) => live && setKnown({ token }));
75
+ void fetchFrameToken(buildProjectApiPath(projectId, "/frame-token")).then(
76
+ (token) => live && setKnown({ token }),
77
+ );
82
78
  return () => {
83
79
  live = false;
84
80
  };
@@ -60,3 +60,22 @@ describe("findParsedTween", () => {
60
60
  timeline.kill();
61
61
  });
62
62
  });
63
+
64
+ /** A preview on an opaque origin: every read of its window but postMessage throws, as a browser's does. */
65
+ function sealedPreview(): HTMLIFrameElement {
66
+ const iframe = document.createElement("iframe");
67
+ const win = new Proxy({} as Record<string, unknown>, {
68
+ get: (_target, key) => {
69
+ if (key === "postMessage") return () => undefined;
70
+ throw new DOMException(`blocked read of ${String(key)}`, "SecurityError");
71
+ },
72
+ });
73
+ Object.defineProperty(iframe, "contentWindow", { value: win });
74
+ Object.defineProperty(iframe, "contentDocument", { value: null });
75
+ return iframe;
76
+ }
77
+
78
+ it("finds no tween in a sealed preview, whose window refuses the read", () => {
79
+ const edit = tween({ method: "to", properties: { x: 300 }, resolvedStart: 0, duration: 2 });
80
+ expect(findParsedTween(sealedPreview(), document.createElement("div"), edit)).toBeNull();
81
+ });
@@ -2,6 +2,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
2
2
  import { elementTargets } from "../utils/elementGsap";
3
3
  import { resolveTweenStart } from "../utils/globalTimeCompiler";
4
4
  import { KEYFRAME_PCT_MATCH } from "./gsapShared";
5
+ import { previewFrameOpaque } from "../player/lib/previewChannel";
5
6
  import type { ImplicitEndValue } from "./gsapValueAtPlayhead";
6
7
  import type { ReadTween } from "./gsapRuntimeKeyframes";
7
8
 
@@ -81,7 +82,8 @@ export function findParsedTween(
81
82
  element: Element,
82
83
  anim: GsapAnimation,
83
84
  ): ParsedTween | null {
84
- const win = iframe?.contentWindow as GsapWindow | null;
85
+ if (!iframe || previewFrameOpaque(iframe)) return null;
86
+ const win = iframe.contentWindow as GsapWindow | null;
85
87
  const start = resolveTweenStart(anim);
86
88
  if (!win?.__timelines || start == null) return null;
87
89
  const steps = anim.keyframes?.keyframes.map((kf) => kf.properties) ?? [anim.properties];
@@ -2,10 +2,14 @@
2
2
 
3
3
  import React, { act } from "react";
4
4
  import { createRoot, type Root } from "react-dom/client";
5
- import { afterEach, expect, it } from "vitest";
5
+ import { afterEach, expect, it, vi } from "vitest";
6
6
  import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark";
7
7
  import { announcePreviewDocumentLoaded } from "../player/sceneSwap";
8
8
  import { useConsoleErrorCapture } from "./useConsoleErrorCapture";
9
+ import {
10
+ detachedFakeIframe,
11
+ serveEditingRequests,
12
+ } from "../player/hooks/timelinePlayerTestHarness";
9
13
 
10
14
  Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
11
15
 
@@ -24,10 +28,42 @@ function previewFrame() {
24
28
 
25
29
  const shown = () => capture.consoleErrors?.map((finding) => finding.message);
26
30
 
31
+ /** A frame whose window refuses Studio's reads; its runtime answers `console-errors` from `raised`. */
32
+ function sealedFrame(
33
+ raised: string[],
34
+ page = (from: number) => {
35
+ const errors = raised.slice(from, from + 2);
36
+ return { errors, truncated: from + errors.length < raised.length };
37
+ },
38
+ ) {
39
+ const frame: Record<string, unknown> = {};
40
+ const iframe = detachedFakeIframe(frame);
41
+ Object.defineProperty(iframe, "contentDocument", { value: null });
42
+ Object.defineProperty(frame, "document", {
43
+ get: () => {
44
+ throw new DOMException("blocked", "SecurityError");
45
+ },
46
+ });
47
+ const asked: number[] = [];
48
+ const askedAt: number[] = [];
49
+ closers.push(
50
+ serveEditingRequests(frame, (kind, params) => {
51
+ if (kind !== "console-errors") return null;
52
+ const { from } = params as { from: number };
53
+ asked.push(from);
54
+ askedAt.push(performance.now());
55
+ return page(from);
56
+ }),
57
+ );
58
+ return { iframe, asked, askedAt };
59
+ }
60
+
61
+ const closers: Array<() => void> = [];
27
62
  let root: Root | null = null;
28
63
  afterEach(async () => {
29
64
  await act(async () => root?.unmount());
30
65
  root = null;
66
+ closers.splice(0).forEach((close) => close());
31
67
  });
32
68
 
33
69
  it("shows the errors a preview raised before its load, once each", async () => {
@@ -104,3 +140,35 @@ it("keeps a page's errors through its own late load, and clears them for the nex
104
140
  await act(async () => announcePreviewDocumentLoaded(iframe));
105
141
  expect(shown()).toEqual(["Uncaught Error: new page"]);
106
142
  });
143
+
144
+ it("shows a sealed preview's errors, read over its editing port a page at a time", async () => {
145
+ const raised = ["Uncaught Error: a", "Uncaught Error: b", "Uncaught Error: c"];
146
+ const { iframe, asked } = sealedFrame(raised);
147
+ root = createRoot(document.createElement("div"));
148
+ await act(async () => root?.render(React.createElement(Harness, { iframe })));
149
+ await act(async () => announcePreviewDocumentLoaded(iframe));
150
+
151
+ const shows = (expected: string[]) =>
152
+ vi.waitFor(
153
+ async () => {
154
+ await act(async () => {});
155
+ expect(shown()).toEqual(expected);
156
+ },
157
+ { timeout: 3_000 },
158
+ );
159
+ await shows(raised);
160
+ expect(asked).toContain(2);
161
+
162
+ raised.push("Uncaught Error: later");
163
+ await shows(raised);
164
+ });
165
+
166
+ it("waits for its next read when a sealed preview's page says more but brings nothing", async () => {
167
+ const { iframe, askedAt } = sealedFrame([], () => ({ errors: [], truncated: true }));
168
+ root = createRoot(document.createElement("div"));
169
+ await act(async () => root?.render(React.createElement(Harness, { iframe })));
170
+ await act(async () => announcePreviewDocumentLoaded(iframe));
171
+
172
+ await vi.waitFor(() => expect(askedAt.length).toBeGreaterThanOrEqual(3), { timeout: 3_000 });
173
+ expect(askedAt[2] - askedAt[1]).toBeGreaterThan(500);
174
+ });
@@ -1,8 +1,14 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
- import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark";
2
+ import {
3
+ previewConsoleErrorText,
4
+ STUDIO_PREVIEW_ERRORS,
5
+ } from "@hyperframes/core/studio-preview-mark";
3
6
  import { onPreviewDocumentLoaded } from "../player/sceneSwap";
7
+ import { previewConsoleErrors, previewFrameOpaque } from "../player/lib/previewChannel";
4
8
  import type { LintFinding } from "../components/LintModal";
5
9
 
10
+ const SEALED_POLL_MS = 1_000;
11
+
6
12
  /**
7
13
  * Captures `console.error` and `window.onerror` events from a preview iframe
8
14
  * and exposes them as LintFinding[] for the console errors modal.
@@ -24,8 +30,42 @@ export function useConsoleErrorCapture(previewIframe: HTMLIFrameElement | null)
24
30
  let patchedWin: (Window & typeof globalThis) | null = null;
25
31
  let origConsoleError: ((...args: unknown[]) => void) | null = null;
26
32
  let errorHandler: ((e: ErrorEvent) => void) | null = null;
33
+ let stopSealedReads: (() => void) | null = null;
34
+
35
+ const record = (texts: readonly string[]) => {
36
+ if (texts.length === 0) return;
37
+ consoleErrorsRef.current = [
38
+ ...consoleErrorsRef.current,
39
+ ...texts.map((message) => ({ severity: "error" as const, message })),
40
+ ];
41
+ setConsoleErrors([...consoleErrorsRef.current]);
42
+ };
43
+
44
+ const readSealedErrors = (iframe: HTMLIFrameElement) => {
45
+ let live = true;
46
+ let read = 0;
47
+ let timer: ReturnType<typeof setTimeout> | undefined;
48
+ const poll = async () => {
49
+ for (;;) {
50
+ const page = await previewConsoleErrors(iframe, read);
51
+ if (!live) return;
52
+ if (!page) break;
53
+ read += page.errors.length;
54
+ record(page.errors);
55
+ if (!page.truncated || page.errors.length === 0) break;
56
+ }
57
+ timer = setTimeout(poll, SEALED_POLL_MS);
58
+ };
59
+ void poll();
60
+ return () => {
61
+ live = false;
62
+ clearTimeout(timer);
63
+ };
64
+ };
27
65
 
28
66
  const detachErrorCapture = () => {
67
+ stopSealedReads?.();
68
+ stopSealedReads = null;
29
69
  const win = patchedWin;
30
70
  if (!win) return;
31
71
  patchedWin = null;
@@ -44,25 +84,21 @@ export function useConsoleErrorCapture(previewIframe: HTMLIFrameElement | null)
44
84
  const attachErrorCapture = () => {
45
85
  detachErrorCapture();
46
86
  resetErrors();
87
+ if (previewFrameOpaque(previewIframe)) {
88
+ stopSealedReads = readSealedErrors(previewIframe);
89
+ return;
90
+ }
47
91
  try {
48
92
  const win = previewIframe.contentWindow as (Window & typeof globalThis) | null;
49
93
  if (!win) return;
50
94
  if ((win as unknown as Record<string, unknown>).__hfErrorCapture) return;
51
95
  (win as unknown as Record<string, unknown>).__hfErrorCapture = true;
52
96
  patchedWin = win;
53
- const record = (texts: readonly string[]) => {
54
- if (texts.length === 0) return;
55
- consoleErrorsRef.current = [
56
- ...consoleErrorsRef.current,
57
- ...texts.map((message) => ({ severity: "error" as const, message })),
58
- ];
59
- setConsoleErrors([...consoleErrorsRef.current]);
60
- };
61
97
  origConsoleError = win.console.error.bind(win.console);
62
98
  win.console.error = function (...args: unknown[]) {
63
99
  origConsoleError!(...args);
64
- const text = args.map((a) => (a instanceof Error ? a.message : String(a))).join(" ");
65
- if (!text.includes("favicon")) record([text]);
100
+ const text = previewConsoleErrorText(args);
101
+ if (text !== null) record([text]);
66
102
  };
67
103
  errorHandler = (e: ErrorEvent) => record([e.message || String(e)]);
68
104
  win.addEventListener("error", errorHandler);
package/src/index.ts CHANGED
@@ -45,6 +45,7 @@ export {
45
45
  formatTime,
46
46
  } from "./player";
47
47
  export { usePreviewIframeStore } from "./player/store/previewIframeStore";
48
+ export { previewEditingClient, previewFrameOpaque } from "./player/lib/previewChannel";
48
49
  export { PREVIEW_QUALITY_LEVELS, type PreviewQuality } from "@hyperframes/core/preview-quality";
49
50
  export type {
50
51
  PlaybackHealth,
@@ -198,6 +198,61 @@ describe("preview errors", () => {
198
198
  });
199
199
  });
200
200
 
201
+ describe("a host's sandbox origin", () => {
202
+ const token = "T".repeat(43);
203
+ const stubFrameToken = (body: { token?: string } | null) =>
204
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
205
+ expect(String(input)).toBe("/api/projects/demo/frame-token");
206
+ return { ok: body !== null, json: async () => body } as Response;
207
+ });
208
+ const settle = () =>
209
+ act(async () => {
210
+ for (let i = 0; i < 10; i += 1) await Promise.resolve();
211
+ });
212
+ afterEach(() => vi.restoreAllMocks());
213
+
214
+ it.each([
215
+ ["/api/projects/demo/preview", `/api/projects/demo/preview/~${token}`],
216
+ [
217
+ "/api/projects/demo/preview/comp/scene.html",
218
+ `/api/projects/demo/preview/~${token}/comp/scene.html`,
219
+ ],
220
+ ["/api/projects/demo/preview?_t=1", `/api/projects/demo/preview/~${token}?_t=1`],
221
+ // A reload starts from the frame's own src, which already carries a token, maybe a stale one.
222
+ [`/api/projects/demo/preview/~${token}?_t=2`, `/api/projects/demo/preview/~${token}?_t=2`],
223
+ [
224
+ `/api/projects/demo/preview/~${"S".repeat(43)}/comp/scene.html`,
225
+ `/api/projects/demo/preview/~${token}/comp/scene.html`,
226
+ ],
227
+ ])(
228
+ "seals an opaque preview of %s and loads it under its project's frame token",
229
+ async (directUrl, sealed) => {
230
+ stubFrameToken({ token });
231
+ const { player } = await mountPlayer({ directUrl, sandboxOrigin: "opaque" });
232
+ await settle();
233
+ expect(player.hasAttribute("sandbox-origin")).toBe(true);
234
+ expect(player.getAttribute("src")).toBe(sealed);
235
+ },
236
+ );
237
+
238
+ it("still seals the preview when the project has no frame token to give", async () => {
239
+ stubFrameToken(null);
240
+ const { player } = await mountPlayer({ sandboxOrigin: "opaque" });
241
+ await settle();
242
+ expect(player.hasAttribute("sandbox-origin")).toBe(true);
243
+ expect(player.getAttribute("src")).toBe("/api/projects/demo/preview");
244
+ });
245
+
246
+ it("leaves a same-origin preview on its plain path without asking for a token", async () => {
247
+ const fetch = vi.spyOn(globalThis, "fetch");
248
+ const { player } = await mountPlayer();
249
+ await settle();
250
+ expect(player.hasAttribute("sandbox-origin")).toBe(false);
251
+ expect(player.getAttribute("src")).toBe("/api/projects/demo/preview");
252
+ expect(fetch).not.toHaveBeenCalled();
253
+ });
254
+ });
255
+
201
256
  describe("callbacks after the player is already mounted", () => {
202
257
  it("runs the latest onLoad on a later load, not the one captured at mount", async () => {
203
258
  const first = vi.fn();
@@ -9,6 +9,7 @@ import { usePlayerStore } from "../store/playerStore";
9
9
  import { announcePreviewDocumentLoaded } from "../sceneSwap";
10
10
  import type { IframeWindow } from "../lib/playbackTypes";
11
11
  import { watchPreviewFrame } from "../lib/bridgePlayback";
12
+ import { previewUnderFrameToken } from "../lib/frameToken";
12
13
  // Importing "@hyperframes/player" registers a class extending HTMLElement at
13
14
  // module load, which throws under SSR, hence the dynamic import behind a
14
15
  // `typeof window` guard. Kicking it here rather than in the mount effect puts
@@ -43,6 +44,7 @@ interface PlayerProps {
43
44
  suppressLoadingOverlay?: boolean;
44
45
  loadingUi?: "studio" | "host";
45
46
  noLoadTimeout?: boolean;
47
+ sandboxOrigin?: "opaque";
46
48
  }
47
49
 
48
50
  interface HyperframesPlayerElement extends HTMLElement {
@@ -139,6 +141,13 @@ export function hasUnloadedAssets(iframe: HTMLIFrameElement, lastResult: boolean
139
141
  }
140
142
  }
141
143
 
144
+ async function playerSrc(previewSource: string, opaque: boolean): Promise<string> {
145
+ const url = new URL(previewSource, window.location.origin);
146
+ applyPreviewVariablesToUrl(url);
147
+ const src = url.pathname + url.search;
148
+ return opaque ? previewUnderFrameToken(src) : src;
149
+ }
150
+
142
151
  const runtimeBootedIn = (iframe: HTMLIFrameElement) =>
143
152
  (iframe.contentWindow as IframeWindow | null)?.__playerReady === true;
144
153
 
@@ -219,14 +228,13 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
219
228
  let canceled = false;
220
229
  let cleanup: (() => void) | undefined;
221
230
 
222
- void loadPlayerModule().then(() => {
231
+ const opaque = host.sandboxOrigin === "opaque";
232
+
233
+ void Promise.all([loadPlayerModule(), playerSrc(previewSource, opaque)]).then(([, src]) => {
223
234
  if (canceled) return;
224
235
 
225
236
  // Create the web component imperatively to avoid JSX custom-element typing.
226
237
  const player = document.createElement("hyperframes-player") as HyperframesPlayerElement;
227
- const srcUrl = new URL(previewSource, window.location.origin);
228
- applyPreviewVariablesToUrl(srcUrl);
229
- const src = srcUrl.pathname + srcUrl.search;
230
238
  const retryPreview = () => {
231
239
  retryCountRef.current += 1;
232
240
  const retryUrl = new URL(src, window.location.origin);
@@ -344,6 +352,7 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
344
352
  player.setAttribute("shader-loading", "player");
345
353
  player.setAttribute("low-power-idle", "");
346
354
  player.toggleAttribute("no-load-timeout", noLoadTimeout === true);
355
+ player.toggleAttribute("sandbox-origin", opaque);
347
356
  player.setAttribute("width", String(portrait ? 1080 : 1920));
348
357
  player.setAttribute("height", String(portrait ? 1920 : 1080));
349
358
  player.style.width = "100%";
@@ -0,0 +1,20 @@
1
+ import { studioApiFetch } from "../../utils/studioApiFetch";
2
+
3
+ const PREVIEW_PATH = /^(\/api\/projects\/[^/?#]+)\/preview(?:\/~[\w-]{43})?(?=[/?#]|$)/;
4
+
5
+ export function fetchFrameToken(frameTokenPath: string): Promise<string | null> {
6
+ return studioApiFetch(frameTokenPath)
7
+ .then((res) => (res.ok ? res.json() : null))
8
+ .then((body: { token?: unknown } | null) =>
9
+ typeof body?.token === "string" ? body.token : null,
10
+ )
11
+ .catch(() => null);
12
+ }
13
+
14
+ /** The preview path under its project's frame token, where an opaque frame's own loads are let through. */
15
+ export async function previewUnderFrameToken(src: string): Promise<string> {
16
+ const project = PREVIEW_PATH.exec(src)?.[1];
17
+ if (!project) return src;
18
+ const token = await fetchFrameToken(`${project}/frame-token`);
19
+ return token ? src.replace(PREVIEW_PATH, `$1/preview/~${token}`) : src;
20
+ }
@@ -97,6 +97,16 @@ export async function previewClipManifest(iframe: HTMLIFrameElement): Promise<Cl
97
97
  return manifest as ClipManifest;
98
98
  }
99
99
 
100
+ export async function previewConsoleErrors(
101
+ iframe: HTMLIFrameElement,
102
+ from: number,
103
+ ): Promise<{ errors: string[]; truncated: boolean } | null> {
104
+ const reply = await previewRequest(iframe, "console-errors", { from });
105
+ const errors: unknown = reply?.errors;
106
+ if (!Array.isArray(errors) || typeof reply?.truncated !== "boolean") return null;
107
+ return { errors: errors.map(String), truncated: reply.truncated };
108
+ }
109
+
100
110
  /** The runtime's computed `properties` for the element `target` names; null when it has none. */
101
111
  export async function previewComputedStyles(
102
112
  iframe: HTMLIFrameElement,