repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/web/components/widget-bridge.js.ts

Raw
File outline
export type WidgetBridgeMessage =
	| {
			type: "widget_action";
			widgetId: string;
			label: string;
			payload?: unknown;
	  }
	| { type: "widget_prompt"; widgetId: string; text: string }
	| { type: "widget_notify"; widgetId: string; message: string }
	| { type: "widget_error"; widgetId: string; message: string };

export type WidgetAttributionEvent = {
	type: "widget_action";
	widgetId: string;
	label: string;
	payload?: unknown;
	at: number;
};

export function widgetActionMessage(
	widgetId: string,
	label: string,
	payload?: unknown,
): WidgetBridgeMessage {
	return { type: "widget_action", widgetId, label, payload };
}

export function attributionEventFromWidgetMessage(
	message: WidgetBridgeMessage,
	now: () => number = Date.now,
): WidgetAttributionEvent {
	if (message.type === "widget_prompt") {
		return {
			type: "widget_action",
			widgetId: message.widgetId,
			label: "prompt",
			payload: { text: message.text },
			at: now(),
		};
	}
	if (message.type === "widget_notify") {
		return {
			type: "widget_action",
			widgetId: message.widgetId,
			label: "notify",
			payload: { message: message.message },
			at: now(),
		};
	}
	if (message.type === "widget_error") {
		return {
			type: "widget_action",
			widgetId: message.widgetId,
			label: "error",
			payload: { message: message.message },
			at: now(),
		};
	}
	return { ...message, at: now() };
}

export function renderWidgetBridgeScript(widgetId: string): string {
	return `<script>
(() => {
	const widgetId = ${JSON.stringify(widgetId)};
	function send(message) { parent.postMessage({ ...message, widgetId }, '*'); }
	window.pi = {
		action(label, payload) { send({ type: 'widget_action', label, payload }); },
		prompt(text) { send({ type: 'widget_prompt', text }); },
		steer(text) { send({ type: 'widget_prompt', text }); },
		followUp(text) { send({ type: 'widget_prompt', text }); },
		notify(message) { send({ type: 'widget_notify', message }); },
		state() { return { widgetId }; },
		on() {},
		update(payload) { send({ type: 'widget_action', label: 'update', payload }); },
		requestAttachment() { send({ type: 'widget_action', label: 'attachment-request' }); },
	};
	window.addEventListener('error', event => send({ type: 'widget_error', message: event.message }));
})();
</script>`;
}