Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
require("../chunk-9hOWP6kD.cjs");
const require_FluidProvider = require("../FluidProvider-D2ZXrmtu.cjs");
require("../FluidThemeProvider-DMfCMPLp.cjs");
require("../ScreenRenderer-B-ZfGmhX.cjs");
require("../use-account-C596ARpR.cjs");
require("../use-optional-store-DT54mwJS.cjs");
require("../mysite-api-context-SWweFE49.cjs");
require("../ContactsTranslationBridge-DpGjYCrP.cjs");
require("../translation-adapter-CuwhmVgY.cjs");
require("../hook-types-B8cS7ta0.cjs");
require("../registry-context-D737a2Jb.cjs");
require("../WidgetInteractionContext-DUJhDVnC.cjs");
require("../RepUserContext-sbdiHHIr.cjs");
require("../QuickLinksWidget-DpsH0cSD.cjs");
require("../WidgetRenderStateContext-3Yk--4Nt.cjs");
require("../static-dict-adapter-BCgoKiVT.cjs");
require("../SearchSort-BW1co5BK.cjs");
require("../use-share-link-CRRJj2zA.cjs");
require("../translation-api-context-factory-mbsJk2UU.cjs");
require("../shell-translation-api-context-BxZ1W6Eb.cjs");
require("../error-state-BY6if4vN.cjs");
require("../PointsWidget-Dm_gKGfF.cjs");
require("../task-composer-form-BMw6N_M4.cjs");
require("../LayoutWidget-dn5ftAss.cjs");
require("../registries-DgzzKX8_.cjs");
require("../fields-DSSM7CHZ.cjs");
require("../TextWidget-B2AKgxsS.cjs");
require("../AlertWidget-BZXjM9Mo.cjs");
require("../BulletListWidget-mdfW_E1z.cjs");
require("../preview-context-J_Viyhgm.cjs");
require("../CalendarWidget-Bnc8WbBi.cjs");
require("../CardWidget-BjSOmo4v.cjs");
require("../purify.es-ESRydCt8.cjs");
require("../MediaRenderer-BI_FoJAZ.cjs");
require("../CarouselWidget-osrUhPQT.cjs");
require("../CatchUpWidget-DiRqSIym.cjs");
require("../src-CMer7k-Y.cjs");
require("../ChartWidget-B0UAkgu6.cjs");
require("../ContainerWidget-VRJ-V8sJ.cjs");
require("../EmbedWidget-CI2A8btB.cjs");
require("../ImageWidget-nXyTe8cq.cjs");
require("../LinkWidget-CgKuDiIk.cjs");
require("../ListWidget-CzPjtPwJ.cjs");
require("../MySiteWidget-CVujw15Y.cjs");
require("../NestedWidget-DRxCABVj.cjs");
require("../QuickShareWidget-DJFk8HSc.cjs");
require("../RecentActivityWidget-DsxCjjYA.cjs");
require("../SeparatorWidget-aDlzY5PY.cjs");
require("../SpacerWidget-CT9EwEJU.cjs");
require("../TableWidget-BOCbvfNj.cjs");
require("../ToDoWidget-DUWIEc9d.cjs");
require("../VideoWidget-D2o3UgOe.cjs");
require("../ShopWidget-Cy3Ix3Dx.cjs");
require("../translation-adapter-D2la7T-e.cjs");
require("../translation-adapter-Bi9lcWv1.cjs");
const require_widget_package_utils = require("../widget-package-utils-CygmmEmW.cjs");
const require_protocol = require("../protocol-DIE_XooL.cjs");
let react = require("react");
let react_jsx_runtime = require("react/jsx-runtime");
let react_dom_client = require("react-dom/client");
//#region src/preview/PreviewRenderer.tsx
/**
* Renders a single widget inside the preview iframe, driven by
* postMessage commands from the builder.
*
* Lifecycle:
*   1. Sends `ready` event on mount
*   2. Waits for `auth` command → calls onAuth()
*   3. Waits for `render-widget` command → renders the widget
*   4. Reports dimensions via ResizeObserver
*/
function PreviewRenderer({ widgetRegistry, onAuth, builderOrigin, skipReady = false }) {
	const [widget, setWidget] = (0, react.useState)(null);
	const [error, setError] = (0, react.useState)(null);
	const containerRef = (0, react.useRef)(null);
	const sentReady = (0, react.useRef)(false);
	const sendToBuilder = (0, react.useCallback)((event) => {
		if (!builderOrigin) return;
		window.parent.postMessage(event, builderOrigin);
	}, [builderOrigin]);
	(0, react.useEffect)(() => {
		if (skipReady) return;
		if (sentReady.current) return;
		sentReady.current = true;
		sendToBuilder({ type: "ready" });
	}, [sendToBuilder, skipReady]);
	const sentAuthReady = (0, react.useRef)(false);
	(0, react.useEffect)(() => {
		if (!skipReady) return;
		if (sentAuthReady.current) return;
		sentAuthReady.current = true;
		sendToBuilder({ type: "auth-ready" });
	}, [sendToBuilder, skipReady]);
	(0, react.useEffect)(() => {
		if (!builderOrigin) return;
		function handleMessage(event) {
			if (event.origin !== builderOrigin) return;
			if (!require_protocol.isPreviewCommand(event.data)) return;
			const command = event.data;
			switch (command.type) {
				case "auth":
					onAuth(command.token);
					if (!sentAuthReady.current) {
						sentAuthReady.current = true;
						sendToBuilder({ type: "auth-ready" });
					}
					break;
				case "render-widget":
					setError(null);
					setWidget({
						widgetType: command.widgetType,
						props: command.props
					});
					break;
				case "select-widget": break;
				case "unmount-widget":
					setWidget(null);
					setError(null);
					break;
				default:
			}
		}
		window.addEventListener("message", handleMessage);
		return () => window.removeEventListener("message", handleMessage);
	}, [
		builderOrigin,
		onAuth,
		sendToBuilder
	]);
	(0, react.useEffect)(() => {
		const container = containerRef.current;
		if (!container || !widget) return;
		const observer = new ResizeObserver((entries) => {
			const entry = entries[0];
			if (!entry) return;
			const { width, height } = entry.contentRect;
			sendToBuilder({
				type: "widget-rendered",
				widgetType: widget.widgetType,
				dimensions: {
					width: Math.ceil(width),
					height: Math.ceil(height)
				}
			});
		});
		observer.observe(container);
		return () => observer.disconnect();
	}, [widget, sendToBuilder]);
	(0, react.useEffect)(() => {
		const hot = {}.hot;
		if (hot) {
			const handler = () => sendToBuilder({ type: "widget-hmr" });
			hot.on("vite:afterUpdate", handler);
			return () => hot.off("vite:afterUpdate", handler);
		}
	}, [sendToBuilder]);
	const WidgetComponent = widget ? widgetRegistry[widget.widgetType] : void 0;
	(0, react.useEffect)(() => {
		if (!widget) return;
		if (!widgetRegistry[widget.widgetType]) sendToBuilder({
			type: "widget-error",
			widgetType: widget.widgetType,
			error: `Unknown widget type: ${widget.widgetType}`
		});
	}, [
		widget,
		widgetRegistry,
		sendToBuilder
	]);
	if (!widget) return null;
	if (!WidgetComponent) return null;
	if (error) return null;
	return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
		ref: containerRef,
		onClick: () => sendToBuilder({
			type: "widget-clicked",
			widgetType: widget.widgetType
		}),
		children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorBoundary, {
			widgetType: widget.widgetType,
			onError: (err) => {
				setError(err);
				sendToBuilder({
					type: "widget-error",
					widgetType: widget.widgetType,
					error: err
				});
			},
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WidgetComponent, { ...widget.props })
		}, widget.widgetType)
	});
}
var ErrorBoundary = class extends react.Component {
	constructor(props) {
		super(props);
		this.state = { hasError: false };
	}
	static getDerivedStateFromError() {
		return { hasError: true };
	}
	componentDidCatch(error) {
		this.props.onError(error.message);
	}
	render() {
		if (this.state.hasError) return null;
		return this.props.children;
	}
};
//#endregion
//#region src/preview/preview-entry.tsx
/**
* Preview iframe bootstrap function.
*
* Called from the portal project's src/preview-entry.tsx with the
* customWidgets array from portal.config.ts. Mirrors the createPortal()
* pattern — SDK handles the wiring, user project provides the widgets.
*
* Two-phase auth handshake:
*   Phase 1: Send `ready`, wait for `auth` command, store token
*   Phase 2: Mount provider stack + PreviewRenderer, send `auth-ready`
*/
function createPreview(options = {}) {
	const { customWidgets = [], widgetPackages = [], rootId = "preview-root" } = options;
	const dedupedWidgetPackages = require_widget_package_utils.dedupeWidgetPackagesByPackageIdAndVersion(widgetPackages);
	const initialWidgetRegistry = require_widget_package_utils.mergeRegisteredWidgetsIntoRegistry(require_widget_package_utils.buildWidgetRegistry(customWidgets), require_widget_package_utils.installAndReadFluidWidgetsRegistry());
	const rawBuilderOrigin = new URLSearchParams(window.location.search).get("builderOrigin");
	const builderOrigin = rawBuilderOrigin && require_protocol.isAllowedOrigin(rawBuilderOrigin) ? rawBuilderOrigin : null;
	if (builderOrigin) window.parent.postMessage({ type: "ready" }, builderOrigin);
	function handleAuthMessage(event) {
		if (event.origin !== builderOrigin) return;
		if (typeof event.data !== "object" || event.data === null || event.data.type !== "auth") return;
		window.removeEventListener("message", handleAuthMessage);
		const command = event.data;
		mountApp({
			initialWidgetRegistry,
			widgetPackages: dedupedWidgetPackages,
			builderOrigin,
			rootId,
			authToken: command.token
		});
	}
	if (builderOrigin) window.addEventListener("message", handleAuthMessage);
	else {
		const rootElement = document.getElementById(rootId);
		if (rootElement) {
			rootElement.style.cssText = "display:flex;align-items:center;justify-content:center;height:100vh;font-family:system-ui;color:#888;font-size:14px";
			rootElement.textContent = rawBuilderOrigin ? `Preview unavailable — origin "${rawBuilderOrigin}" is not allowed` : "Preview unavailable — missing builderOrigin parameter";
		}
	}
}
function mountApp({ initialWidgetRegistry, widgetPackages, builderOrigin, rootId, authToken }) {
	const rootElement = document.getElementById(rootId);
	if (!rootElement) return;
	const iframeOrigin = window.location.origin;
	const tree = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.StrictMode, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreviewRuntimeWidgetBootstrap, {
		fluidConfig: require_widget_package_utils.createDefaultFluidConfig({
			baseUrl: iframeOrigin,
			getAuthToken: () => authToken
		}),
		initialWidgetRegistry,
		widgetPackageLoadPromise: builderOrigin && widgetPackages.length ? require_widget_package_utils.loadWidgetPackages(widgetPackages) : void 0,
		builderOrigin
	}) });
	(0, react_dom_client.createRoot)(rootElement).render(tree);
}
function PreviewRuntimeWidgetBootstrap({ fluidConfig, initialWidgetRegistry, widgetPackageLoadPromise, builderOrigin }) {
	const [runtimeWidgetState, setRuntimeWidgetState] = (0, react.useState)(() => ({
		widgetRegistry: initialWidgetRegistry,
		packageLoadSettled: !widgetPackageLoadPromise
	}));
	(0, react.useEffect)(() => {
		if (!widgetPackageLoadPromise) {
			setRuntimeWidgetState({
				widgetRegistry: initialWidgetRegistry,
				packageLoadSettled: true
			});
			return;
		}
		let cancelled = false;
		setRuntimeWidgetState({
			widgetRegistry: initialWidgetRegistry,
			packageLoadSettled: false
		});
		widgetPackageLoadPromise.then((summary) => {
			if (cancelled) return;
			setRuntimeWidgetState({
				widgetRegistry: require_widget_package_utils.mergeRegisteredWidgetsIntoRegistry(initialWidgetRegistry, summary.registeredWidgets),
				packageLoadSettled: true
			});
		}).catch((error) => {
			if (cancelled) return;
			console.error("[portal] Failed to load preview widget packages:", error);
			setRuntimeWidgetState({
				widgetRegistry: initialWidgetRegistry,
				packageLoadSettled: true
			});
		});
		return () => {
			cancelled = true;
		};
	}, [initialWidgetRegistry, widgetPackageLoadPromise]);
	return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_FluidProvider.FluidProvider, {
		config: fluidConfig,
		widgetRegistry: runtimeWidgetState.widgetRegistry,
		children: runtimeWidgetState.packageLoadSettled ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreviewRenderer, {
			widgetRegistry: runtimeWidgetState.widgetRegistry,
			onAuth: () => {},
			builderOrigin,
			skipReady: true
		}) : null
	});
}
//#endregion
exports.createPreview = createPreview;

//# sourceMappingURL=preview-entry.cjs.map