standalone-host-bridge.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. (() => {
  2. const root = document.documentElement;
  3. const mediaQuery = globalThis.matchMedia("(prefers-color-scheme: dark)");
  4. const apply = Reflect.apply;
  5. const isArray = Array.isArray;
  6. const hasOwn = Object.hasOwn;
  7. const parentWindow = globalThis.parent;
  8. const stringify = JSON.stringify;
  9. const parse = JSON.parse;
  10. const encode = TextEncoder.prototype.encode.bind(new TextEncoder());
  11. const initialStateElement = document.getElementById("zcode-visualization-widget-state");
  12. const initialGlobals = parse(initialStateElement?.textContent ?? "{}");
  13. initialStateElement?.remove();
  14. /** @type {Record<string, unknown> | null} */
  15. let state = initialGlobals.widgetState ?? null;
  16. const statePersistence = initialGlobals.statePersistence ?? "none";
  17. let nextStateRequestId = 0;
  18. /** @type {Map<number, { resolve: () => void; reject: (error: Error) => void; timeout: ReturnType<typeof globalThis.setTimeout>; serializedState: string }>} */
  19. const pendingStateWrites = new Map();
  20. const persistenceError = () =>
  21. Object.assign(new Error("The host could not persist the widget state update"), {
  22. code: -32000,
  23. data: { code: "widget_state_persistence_failed", retryable: false },
  24. });
  25. /**
  26. * @param {object} prototype
  27. * @param {string} property
  28. */
  29. const getPrototypeGetter = (prototype, property) => {
  30. // oxlint-disable-next-line typescript/unbound-method -- invoked through captured Reflect.apply
  31. const getter = Object.getOwnPropertyDescriptor(prototype, property)?.get;
  32. if (getter == null) {
  33. throw new Error(`Missing ${property} getter`);
  34. }
  35. return getter;
  36. };
  37. const getMessageData = getPrototypeGetter(MessageEvent.prototype, "data");
  38. const getMessagePorts = getPrototypeGetter(MessageEvent.prototype, "ports");
  39. const getMessageSource = getPrototypeGetter(MessageEvent.prototype, "source");
  40. // oxlint-disable-next-line typescript/unbound-method -- captured before the untrusted fragment runs
  41. const addHostMessageListener = MessagePort.prototype.addEventListener;
  42. // oxlint-disable-next-line typescript/unbound-method -- captured before the untrusted fragment runs
  43. const postHostMessage = MessagePort.prototype.postMessage;
  44. // oxlint-disable-next-line typescript/unbound-method -- captured before the untrusted fragment runs
  45. const startHostPort = MessagePort.prototype.start;
  46. // oxlint-disable-next-line typescript/unbound-method -- captured before the untrusted fragment runs
  47. const stopMessagePropagation = Event.prototype.stopImmediatePropagation;
  48. /** @type {MessagePort | null} */
  49. let hostPort = null;
  50. const postToHost = (type, payload) => {
  51. if (hostPort != null) {
  52. apply(postHostMessage, hostPort, [{ type, ...payload }]);
  53. }
  54. };
  55. const openExternal = ({ href }) => {
  56. if (globalThis.navigator.userActivation?.isActive === true) {
  57. postToHost("open-external", { href });
  58. }
  59. };
  60. const sendFollowUpMessage = ({ context, prompt, title }) => {
  61. if (globalThis.navigator.userActivation?.isActive === true) {
  62. postToHost("follow-up", { context, prompt, title });
  63. }
  64. return Promise.resolve();
  65. };
  66. /**
  67. * @param {Record<string, unknown> | ((previous: Record<string, unknown> | null) => Record<string, unknown>)} next
  68. * @returns {Promise<void>}
  69. */
  70. const setWidgetState = async (next) => {
  71. const nextState = typeof next === "function" ? next(state) : next;
  72. if (nextState == null || typeof nextState !== "object" || isArray(nextState)) {
  73. throw new TypeError("Widget state must be a JSON object");
  74. }
  75. const inputState = stringify(nextState, (_key, /** @type {unknown} */ value) => {
  76. if (
  77. typeof value === "undefined" ||
  78. typeof value === "function" ||
  79. typeof value === "symbol" ||
  80. (typeof value === "number" && !Number.isFinite(value))
  81. ) {
  82. throw new TypeError("Widget state must be a JSON object");
  83. }
  84. return value;
  85. });
  86. const parsedState = parse(inputState);
  87. if (parsedState == null || typeof parsedState !== "object" || isArray(parsedState)) {
  88. throw new TypeError("Widget state must be a JSON object");
  89. }
  90. const storedState = {
  91. modelContent: null,
  92. privateContent: null,
  93. ...parsedState,
  94. };
  95. const serializedState = stringify(storedState);
  96. if (encode(serializedState).length > 16 * 1024) {
  97. throw new TypeError("Widget state must be a JSON object of at most 16 KiB");
  98. }
  99. if (
  100. hasOwn(storedState, "imageIds") &&
  101. (!isArray(storedState.imageIds) ||
  102. storedState.imageIds.some((/** @type {unknown} */ id) => typeof id !== "string"))
  103. ) {
  104. throw new TypeError("Widget state imageIds must be an array of strings");
  105. }
  106. if (storedState.imageIds?.length > 0) {
  107. throw Object.assign(new TypeError("Visualization state does not support image attachments"), {
  108. code: -32602,
  109. data: { code: "images_unsupported" },
  110. });
  111. }
  112. state = storedState;
  113. globalThis.zcode.widgetState = state;
  114. globalThis.dispatchEvent(
  115. new CustomEvent("zcode:set_globals", {
  116. detail: { globals: { widgetState: state } },
  117. }),
  118. );
  119. if (statePersistence === "none") {
  120. throw persistenceError();
  121. }
  122. const id = ++nextStateRequestId;
  123. return new Promise((resolve, reject) => {
  124. const timeout = globalThis.setTimeout(() => {
  125. pendingStateWrites.delete(id);
  126. reject(persistenceError());
  127. }, 30_000);
  128. pendingStateWrites.set(id, { resolve, reject, timeout, serializedState });
  129. postToHost("widget-state-write", { id, state: serializedState });
  130. });
  131. };
  132. const syncTheme = () => {
  133. const theme = mediaQuery.matches ? "dark" : "light";
  134. root.dataset.theme = theme;
  135. globalThis.zcode = {
  136. ...globalThis.zcode,
  137. openExternal,
  138. sendFollowUpMessage,
  139. setWidgetState,
  140. theme,
  141. visualizationStyleVariables: {},
  142. visualizationTheme: theme,
  143. widgetState: state,
  144. statePersistence,
  145. stateModelContext: "none",
  146. };
  147. globalThis.dispatchEvent(
  148. new CustomEvent("zcode:set_globals", {
  149. detail: { globals: globalThis.zcode },
  150. }),
  151. );
  152. };
  153. const sendHeight = () => {
  154. postToHost("height", {
  155. height: Math.ceil(
  156. Math.max(document.body.scrollHeight, document.body.getBoundingClientRect().height),
  157. ),
  158. });
  159. };
  160. globalThis.addEventListener(
  161. "message",
  162. (event) => {
  163. const data = apply(getMessageData, event, []);
  164. const ports = apply(getMessagePorts, event, []);
  165. const source = apply(getMessageSource, event, []);
  166. if (
  167. hostPort != null ||
  168. source !== parentWindow ||
  169. typeof data !== "object" ||
  170. data?.type !== "zcode-visualization-initialize" ||
  171. !isArray(ports) ||
  172. ports.length !== 1
  173. ) {
  174. return;
  175. }
  176. apply(stopMessagePropagation, event, []);
  177. const nextHostPort = ports[0];
  178. try {
  179. apply(addHostMessageListener, nextHostPort, [
  180. "message",
  181. (event) => {
  182. const data = apply(getMessageData, event, []);
  183. if (typeof data === "object" && data?.type === "measure") {
  184. sendHeight();
  185. } else if (typeof data === "object" && data?.type === "widget-state-result") {
  186. /** @type {unknown} */
  187. const id = data.id;
  188. if (typeof id !== "number") {
  189. return;
  190. }
  191. const pending = pendingStateWrites.get(id);
  192. if (pending != null) {
  193. pendingStateWrites.delete(id);
  194. globalThis.clearTimeout(pending.timeout);
  195. if (data.ok === true) {
  196. pending.resolve();
  197. } else {
  198. pending.reject(persistenceError());
  199. }
  200. }
  201. }
  202. },
  203. ]);
  204. apply(startHostPort, nextHostPort, []);
  205. } catch {
  206. return;
  207. }
  208. hostPort = nextHostPort;
  209. for (const [id, { serializedState }] of pendingStateWrites) {
  210. postToHost("widget-state-write", { id, state: serializedState });
  211. }
  212. sendHeight();
  213. },
  214. { capture: true },
  215. );
  216. document.currentScript?.remove();
  217. mediaQuery.addEventListener("change", syncTheme);
  218. globalThis.addEventListener("click", (event) => {
  219. if (event.defaultPrevented) {
  220. return;
  221. }
  222. let element = null;
  223. if (event.target instanceof globalThis.Element) {
  224. element = event.target;
  225. } else if (event.target instanceof globalThis.Node) {
  226. element = event.target.parentElement;
  227. }
  228. const link = element?.closest("a[href]");
  229. const href = link?.getAttribute("href");
  230. if (href == null) {
  231. return;
  232. }
  233. if (href.startsWith("#")) {
  234. let id;
  235. try {
  236. id = decodeURIComponent(href.slice(1));
  237. } catch {
  238. return;
  239. }
  240. const target = id.length === 0 ? root : document.getElementById(id);
  241. if (target == null || globalThis.navigator.userActivation?.isActive !== true) {
  242. return;
  243. }
  244. event.preventDefault();
  245. postToHost("scroll-to", {
  246. top: target.getBoundingClientRect().top + globalThis.scrollY,
  247. });
  248. return;
  249. }
  250. event.preventDefault();
  251. openExternal({ href });
  252. });
  253. new ResizeObserver(sendHeight).observe(document.body);
  254. syncTheme();
  255. })();