UNPKG

@stagewise/toolbar

Version:

stagewise toolbar SDK for AI Agent interaction.

1,334 lines (1,333 loc) 239 kB
import { l as l$1, x as x$2, _ as _$1, k as k$2, H as H$1, J as J$1, b, K as K$1, E as E$1, G as G$1, u as u$1 } from "./jsx-runtime-BDYu3_Il.js"; var t, r$1, u, i, o = 0, f = [], c = l$1, e = c.__b, a = c.__r, v = c.diffed, l = c.__c, m = c.unmount, s = c.__; function p(n, t2) { c.__h && c.__h(r$1, n, o || t2), o = 0; var u2 = r$1.__H || (r$1.__H = { __: [], __h: [] }); return n >= u2.__.length && u2.__.push({}), u2.__[n]; } function d(n) { return o = 1, h(D$1, n); } function h(n, u2, i2) { var o2 = p(t++, 2); if (o2.t = n, !o2.__c && (o2.__ = [i2 ? i2(u2) : D$1(void 0, u2), function(n2) { var t2 = o2.__N ? o2.__N[0] : o2.__[0], r2 = o2.t(t2, n2); t2 !== r2 && (o2.__N = [r2, o2.__[1]], o2.__c.setState({})); }], o2.__c = r$1, !r$1.__f)) { var f2 = function(n2, t2, r2) { if (!o2.__c.__H) return !0; var u3 = o2.__c.__H.__.filter(function(n3) { return !!n3.__c; }); if (u3.every(function(n3) { return !n3.__N; })) return !c2 || c2.call(this, n2, t2, r2); var i3 = o2.__c.props !== n2; return u3.forEach(function(n3) { if (n3.__N) { var t3 = n3.__[0]; n3.__ = n3.__N, n3.__N = void 0, t3 !== n3.__[0] && (i3 = !0); } }), c2 && c2.call(this, n2, t2, r2) || i3; }; r$1.__f = !0; var c2 = r$1.shouldComponentUpdate, e2 = r$1.componentWillUpdate; r$1.componentWillUpdate = function(n2, t2, r2) { if (this.__e) { var u3 = c2; c2 = void 0, f2(n2, t2, r2), c2 = u3; } e2 && e2.call(this, n2, t2, r2); }, r$1.shouldComponentUpdate = f2; } return o2.__N || o2.__; } function y(n, u2) { var i2 = p(t++, 3); !c.__s && C$1(i2.__H, u2) && (i2.__ = n, i2.u = u2, r$1.__H.__h.push(i2)); } function _(n, u2) { var i2 = p(t++, 4); !c.__s && C$1(i2.__H, u2) && (i2.__ = n, i2.u = u2, r$1.__h.push(i2)); } function A$1(n) { return o = 5, T$1(function() { return { current: n }; }, []); } function F$1(n, t2, r2) { o = 6, _(function() { if (typeof n == "function") { var r3 = n(t2()); return function() { n(null), r3 && typeof r3 == "function" && r3(); }; } if (n) return n.current = t2(), function() { return n.current = null; }; }, r2 == null ? r2 : r2.concat(n)); } function T$1(n, r2) { var u2 = p(t++, 7); return C$1(u2.__H, r2) && (u2.__ = n(), u2.__H = r2, u2.__h = n), u2.__; } function q$1(n, t2) { return o = 8, T$1(function() { return n; }, t2); } function x$1(n) { var u2 = r$1.context[n.__c], i2 = p(t++, 9); return i2.c = n, u2 ? (i2.__ == null && (i2.__ = !0, u2.sub(r$1)), u2.props.value) : n.__; } function P$1(n, t2) { c.useDebugValue && c.useDebugValue(t2 ? t2(n) : n); } function g$1() { var n = p(t++, 11); if (!n.__) { for (var u2 = r$1.__v; u2 !== null && !u2.__m && u2.__ !== null; ) u2 = u2.__; var i2 = u2.__m || (u2.__m = [0, 0]); n.__ = "P" + i2[0] + "-" + i2[1]++; } return n.__; } function j$1() { for (var n; n = f.shift(); ) if (n.__P && n.__H) try { n.__H.__h.forEach(z$2), n.__H.__h.forEach(B$1), n.__H.__h = []; } catch (t2) { n.__H.__h = [], c.__e(t2, n.__v); } } c.__b = function(n) { r$1 = null, e && e(n); }, c.__ = function(n, t2) { n && t2.__k && t2.__k.__m && (n.__m = t2.__k.__m), s && s(n, t2); }, c.__r = function(n) { a && a(n), t = 0; var i2 = (r$1 = n.__c).__H; i2 && (u === r$1 ? (i2.__h = [], r$1.__h = [], i2.__.forEach(function(n2) { n2.__N && (n2.__ = n2.__N), n2.u = n2.__N = void 0; })) : (i2.__h.forEach(z$2), i2.__h.forEach(B$1), i2.__h = [], t = 0)), u = r$1; }, c.diffed = function(n) { v && v(n); var t2 = n.__c; t2 && t2.__H && (t2.__H.__h.length && (f.push(t2) !== 1 && i === c.requestAnimationFrame || ((i = c.requestAnimationFrame) || w$1)(j$1)), t2.__H.__.forEach(function(n2) { n2.u && (n2.__H = n2.u), n2.u = void 0; })), u = r$1 = null; }, c.__c = function(n, t2) { t2.some(function(n2) { try { n2.__h.forEach(z$2), n2.__h = n2.__h.filter(function(n3) { return !n3.__ || B$1(n3); }); } catch (r2) { t2.some(function(n3) { n3.__h && (n3.__h = []); }), t2 = [], c.__e(r2, n2.__v); } }), l && l(n, t2); }, c.unmount = function(n) { m && m(n); var t2, r2 = n.__c; r2 && r2.__H && (r2.__H.__.forEach(function(n2) { try { z$2(n2); } catch (n3) { t2 = n3; } }), r2.__H = void 0, t2 && c.__e(t2, r2.__v)); }; var k$1 = typeof requestAnimationFrame == "function"; function w$1(n) { var t2, r2 = function() { clearTimeout(u2), k$1 && cancelAnimationFrame(t2), setTimeout(n); }, u2 = setTimeout(r2, 100); k$1 && (t2 = requestAnimationFrame(r2)); } function z$2(n) { var t2 = r$1, u2 = n.__c; typeof u2 == "function" && (n.__c = void 0, u2()), r$1 = t2; } function B$1(n) { var t2 = r$1; n.__c = n.__(), r$1 = t2; } function C$1(n, t2) { return !n || n.length !== t2.length || t2.some(function(t3, r2) { return t3 !== n[r2]; }); } function D$1(n, t2) { return typeof t2 == "function" ? t2(n) : t2; } function g(n, t2) { for (var e2 in t2) n[e2] = t2[e2]; return n; } function E(n, t2) { for (var e2 in n) if (e2 !== "__source" && !(e2 in t2)) return !0; for (var r2 in t2) if (r2 !== "__source" && n[r2] !== t2[r2]) return !0; return !1; } function C(n, t2) { var e2 = t2(), r2 = d({ t: { __: e2, u: t2 } }), u2 = r2[0].t, o2 = r2[1]; return _(function() { u2.__ = e2, u2.u = t2, x(u2) && o2({ t: u2 }); }, [n, e2, t2]), y(function() { return x(u2) && o2({ t: u2 }), n(function() { x(u2) && o2({ t: u2 }); }); }, [n]), e2; } function x(n) { var t2, e2, r2 = n.u, u2 = n.__; try { var o2 = r2(); return !((t2 = u2) === (e2 = o2) && (t2 !== 0 || 1 / t2 == 1 / e2) || t2 != t2 && e2 != e2); } catch { return !0; } } function R(n) { n(); } function w(n) { return n; } function k() { return [!1, R]; } var I = _; function N(n, t2) { this.props = n, this.context = t2; } function M(n, e2) { function r2(n2) { var t2 = this.props.ref, r3 = t2 == n2.ref; return !r3 && t2 && (t2.call ? t2(null) : t2.current = null), e2 ? !e2(this.props, n2) || !r3 : E(this.props, n2); } function u2(e3) { return this.shouldComponentUpdate = r2, _$1(n, e3); } return u2.displayName = "Memo(" + (n.displayName || n.name) + ")", u2.prototype.isReactComponent = !0, u2.__f = !0, u2; } (N.prototype = new x$2()).isPureReactComponent = !0, N.prototype.shouldComponentUpdate = function(n, t2) { return E(this.props, n) || E(this.state, t2); }; var T = l$1.__b; l$1.__b = function(n) { n.type && n.type.__f && n.ref && (n.props.ref = n.ref, n.ref = null), T && T(n); }; var A = typeof Symbol < "u" && Symbol.for && Symbol.for("react.forward_ref") || 3911; function D(n) { function t2(t3) { var e2 = g({}, t3); return delete e2.ref, n(e2, t3.ref || null); } return t2.$$typeof = A, t2.render = t2, t2.prototype.isReactComponent = t2.__f = !0, t2.displayName = "ForwardRef(" + (n.displayName || n.name) + ")", t2; } var L = function(n, t2) { return n == null ? null : H$1(H$1(n).map(t2)); }, O = { map: L, forEach: L, count: function(n) { return n ? H$1(n).length : 0; }, only: function(n) { var t2 = H$1(n); if (t2.length !== 1) throw "Children.only"; return t2[0]; }, toArray: H$1 }, F = l$1.__e; l$1.__e = function(n, t2, e2, r2) { if (n.then) { for (var u2, o2 = t2; o2 = o2.__; ) if ((u2 = o2.__c) && u2.__c) return t2.__e == null && (t2.__e = e2.__e, t2.__k = e2.__k), u2.__c(n, t2); } F(n, t2, e2, r2); }; var U = l$1.unmount; function V(n, t2, e2) { return n && (n.__c && n.__c.__H && (n.__c.__H.__.forEach(function(n2) { typeof n2.__c == "function" && n2.__c(); }), n.__c.__H = null), (n = g({}, n)).__c != null && (n.__c.__P === e2 && (n.__c.__P = t2), n.__c.__e = !0, n.__c = null), n.__k = n.__k && n.__k.map(function(n2) { return V(n2, t2, e2); })), n; } function W(n, t2, e2) { return n && e2 && (n.__v = null, n.__k = n.__k && n.__k.map(function(n2) { return W(n2, t2, e2); }), n.__c && n.__c.__P === t2 && (n.__e && e2.appendChild(n.__e), n.__c.__e = !0, n.__c.__P = e2)), n; } function P() { this.__u = 0, this.o = null, this.__b = null; } function j(n) { var t2 = n.__.__c; return t2 && t2.__a && t2.__a(n); } function z$1(n) { var e2, r2, u2; function o2(o3) { if (e2 || (e2 = n()).then(function(n2) { r2 = n2.default || n2; }, function(n2) { u2 = n2; }), u2) throw u2; if (!r2) throw e2; return _$1(r2, o3); } return o2.displayName = "Lazy", o2.__f = !0, o2; } function B() { this.i = null, this.l = null; } l$1.unmount = function(n) { var t2 = n.__c; t2 && t2.__R && t2.__R(), t2 && 32 & n.__u && (n.type = null), U && U(n); }, (P.prototype = new x$2()).__c = function(n, t2) { var e2 = t2.__c, r2 = this; r2.o == null && (r2.o = []), r2.o.push(e2); var u2 = j(r2.__v), o2 = !1, i2 = function() { o2 || (o2 = !0, e2.__R = null, u2 ? u2(l2) : l2()); }; e2.__R = i2; var l2 = function() { if (!--r2.__u) { if (r2.state.__a) { var n2 = r2.state.__a; r2.__v.__k[0] = W(n2, n2.__c.__P, n2.__c.__O); } var t3; for (r2.setState({ __a: r2.__b = null }); t3 = r2.o.pop(); ) t3.forceUpdate(); } }; r2.__u++ || 32 & t2.__u || r2.setState({ __a: r2.__b = r2.__v.__k[0] }), n.then(i2, i2); }, P.prototype.componentWillUnmount = function() { this.o = []; }, P.prototype.render = function(n, e2) { if (this.__b) { if (this.__v.__k) { var r2 = document.createElement("div"), o2 = this.__v.__k[0].__c; this.__v.__k[0] = V(this.__b, r2, o2.__O = o2.__P); } this.__b = null; } var i2 = e2.__a && _$1(k$2, null, n.fallback); return i2 && (i2.__u &= -33), [_$1(k$2, null, e2.__a ? null : n.children), i2]; }; var H = function(n, t2, e2) { if (++e2[1] === e2[0] && n.l.delete(t2), n.props.revealOrder && (n.props.revealOrder[0] !== "t" || !n.l.size)) for (e2 = n.i; e2; ) { for (; e2.length > 3; ) e2.pop()(); if (e2[1] < e2[0]) break; n.i = e2 = e2[2]; } }; function Z(n) { return this.getChildContext = function() { return n.context; }, n.children; } function Y(n) { var e2 = this, r2 = n.h; if (e2.componentWillUnmount = function() { E$1(null, e2.v), e2.v = null, e2.h = null; }, e2.h && e2.h !== r2 && e2.componentWillUnmount(), !e2.v) { for (var u2 = e2.__v; u2 !== null && !u2.__m && u2.__ !== null; ) u2 = u2.__; e2.h = r2, e2.v = { nodeType: 1, parentNode: r2, childNodes: [], __k: { __m: u2.__m }, contains: function() { return !0; }, appendChild: function(n2) { this.childNodes.push(n2), e2.h.appendChild(n2); }, insertBefore: function(n2, t2) { this.childNodes.push(n2), e2.h.insertBefore(n2, t2); }, removeChild: function(n2) { this.childNodes.splice(this.childNodes.indexOf(n2) >>> 1, 1), e2.h.removeChild(n2); } }; } E$1(_$1(Z, { context: e2.context }, n.__v), e2.v); } function $(n, e2) { var r2 = _$1(Y, { __v: n, h: e2 }); return r2.containerInfo = e2, r2; } (B.prototype = new x$2()).__a = function(n) { var t2 = this, e2 = j(t2.__v), r2 = t2.l.get(n); return r2[0]++, function(u2) { var o2 = function() { t2.props.revealOrder ? (r2.push(u2), H(t2, n, r2)) : u2(); }; e2 ? e2(o2) : o2(); }; }, B.prototype.render = function(n) { this.i = null, this.l = /* @__PURE__ */ new Map(); var t2 = H$1(n.children); n.revealOrder && n.revealOrder[0] === "b" && t2.reverse(); for (var e2 = t2.length; e2--; ) this.l.set(t2[e2], this.i = [1, 0, this.i]); return n.children; }, B.prototype.componentDidUpdate = B.prototype.componentDidMount = function() { var n = this; this.l.forEach(function(t2, e2) { H(n, e2, t2); }); }; var q = typeof Symbol < "u" && Symbol.for && Symbol.for("react.element") || 60103, G = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/, J = /^on(Ani|Tra|Tou|BeforeInp|Compo)/, K = /[A-Z0-9]/g, Q = typeof document < "u", X = function(n) { return (typeof Symbol < "u" && typeof Symbol() == "symbol" ? /fil|che|rad/ : /fil|che|ra/).test(n); }; function nn(n, t2, e2) { return t2.__k == null && (t2.textContent = ""), E$1(n, t2), typeof e2 == "function" && e2(), n ? n.__c : null; } function tn(n, t2, e2) { return G$1(n, t2), typeof e2 == "function" && e2(), n ? n.__c : null; } x$2.prototype.isReactComponent = {}, ["componentWillMount", "componentWillReceiveProps", "componentWillUpdate"].forEach(function(t2) { Object.defineProperty(x$2.prototype, t2, { configurable: !0, get: function() { return this["UNSAFE_" + t2]; }, set: function(n) { Object.defineProperty(this, t2, { configurable: !0, writable: !0, value: n }); } }); }); var en = l$1.event; function rn() { } function un() { return this.cancelBubble; } function on() { return this.defaultPrevented; } l$1.event = function(n) { return en && (n = en(n)), n.persist = rn, n.isPropagationStopped = un, n.isDefaultPrevented = on, n.nativeEvent = n; }; var ln, cn$1 = { enumerable: !1, configurable: !0, get: function() { return this.class; } }, fn = l$1.vnode; l$1.vnode = function(n) { typeof n.type == "string" && function(n2) { var t2 = n2.props, e2 = n2.type, u2 = {}, o2 = e2.indexOf("-") === -1; for (var i2 in t2) { var l2 = t2[i2]; if (!(i2 === "value" && "defaultValue" in t2 && l2 == null || Q && i2 === "children" && e2 === "noscript" || i2 === "class" || i2 === "className")) { var c2 = i2.toLowerCase(); i2 === "defaultValue" && "value" in t2 && t2.value == null ? i2 = "value" : i2 === "download" && l2 === !0 ? l2 = "" : c2 === "translate" && l2 === "no" ? l2 = !1 : c2[0] === "o" && c2[1] === "n" ? c2 === "ondoubleclick" ? i2 = "ondblclick" : c2 !== "onchange" || e2 !== "input" && e2 !== "textarea" || X(t2.type) ? c2 === "onfocus" ? i2 = "onfocusin" : c2 === "onblur" ? i2 = "onfocusout" : J.test(i2) && (i2 = c2) : c2 = i2 = "oninput" : o2 && G.test(i2) ? i2 = i2.replace(K, "-$&").toLowerCase() : l2 === null && (l2 = void 0), c2 === "oninput" && u2[i2 = c2] && (i2 = "oninputCapture"), u2[i2] = l2; } } e2 == "select" && u2.multiple && Array.isArray(u2.value) && (u2.value = H$1(t2.children).forEach(function(n3) { n3.props.selected = u2.value.indexOf(n3.props.value) != -1; })), e2 == "select" && u2.defaultValue != null && (u2.value = H$1(t2.children).forEach(function(n3) { n3.props.selected = u2.multiple ? u2.defaultValue.indexOf(n3.props.value) != -1 : u2.defaultValue == n3.props.value; })), t2.class && !t2.className ? (u2.class = t2.class, Object.defineProperty(u2, "className", cn$1)) : (t2.className && !t2.class || t2.class && t2.className) && (u2.class = u2.className = t2.className), n2.props = u2; }(n), n.$$typeof = q, fn && fn(n); }; var an = l$1.__r; l$1.__r = function(n) { an && an(n), ln = n.__c; }; var sn = l$1.diffed; l$1.diffed = function(n) { sn && sn(n); var t2 = n.props, e2 = n.__e; e2 != null && n.type === "textarea" && "value" in t2 && t2.value !== e2.value && (e2.value = t2.value == null ? "" : t2.value), ln = null; }; var hn = { ReactCurrentDispatcher: { current: { readContext: function(n) { return ln.__n[n.__c].props.value; }, useCallback: q$1, useContext: x$1, useDebugValue: P$1, useDeferredValue: w, useEffect: y, useId: g$1, useImperativeHandle: F$1, useInsertionEffect: I, useLayoutEffect: _, useMemo: T$1, useReducer: h, useRef: A$1, useState: d, useSyncExternalStore: C, useTransition: k } } }; function dn(n) { return _$1.bind(null, n); } function mn(n) { return !!n && n.$$typeof === q; } function pn(n) { return mn(n) && n.type === k$2; } function yn(n) { return !!n && !!n.displayName && (typeof n.displayName == "string" || n.displayName instanceof String) && n.displayName.startsWith("Memo("); } function _n(n) { return mn(n) ? J$1.apply(null, arguments) : n; } function bn(n) { return !!n.__k && (E$1(null, n), !0); } function Sn(n) { return n && (n.base || n.nodeType === 1 && n) || null; } var gn = function(n, t2) { return n(t2); }, En = function(n, t2) { return n(t2); }, Cn = k$2, xn = mn, Rn = { useState: d, useId: g$1, useReducer: h, useEffect: y, useLayoutEffect: _, useInsertionEffect: I, useTransition: k, useDeferredValue: w, useSyncExternalStore: C, startTransition: R, useRef: A$1, useImperativeHandle: F$1, useMemo: T$1, useCallback: q$1, useContext: x$1, useDebugValue: P$1, version: "18.3.1", Children: O, render: nn, hydrate: tn, unmountComponentAtNode: bn, createPortal: $, createElement: _$1, createContext: K$1, createFactory: dn, cloneElement: _n, createRef: b, Fragment: k$2, isValidElement: mn, isElement: xn, isFragment: pn, isMemo: yn, findDOMNode: Sn, Component: x$2, PureComponent: N, memo: M, forwardRef: D, flushSync: En, unstable_batchedUpdates: gn, StrictMode: Cn, Suspense: P, SuspenseList: B, lazy: z$1, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: hn }, generateId$1 = (length = 16) => Math.random().toString(36).substring(2, length + 2), DEFAULT_OPTIONS = { maxReconnectAttempts: 5, reconnectDelay: 1e3, requestTimeout: 3e4 // Extended timeout for longer operations }, WebSocketRpcBridge = class { constructor(options = {}) { this.ws = null, this.pendingRequests = /* @__PURE__ */ new Map(), this.reconnectAttempts = 0, this.methods = {}, this.isIntentionalClose = !1, this.options = { ...DEFAULT_OPTIONS, ...options }; } /** * Register RPC method handlers * @param methodHandlers Object containing method handlers */ register(methodHandlers) { Object.entries(methodHandlers).forEach(([methodName, handler]) => { this.methods[methodName] = { handler }; }); } /** * Generic method to call a remote procedure with support for streaming updates * @param method Method name to call * @param payload Request payload * @param onUpdate Optional callback for progress updates * @returns Promise resolving with the response */ callMethod(method, payload, onUpdate) { if (!this.ws) throw new Error("WebSocket is not connected"); const id = generateId$1(), requestMessage = { id, messageType: "request", method, payload }; return new Promise((resolve, reject) => { var _a; const timeout = setTimeout(() => { this.pendingRequests.delete(id), reject(new Error(`Request timed out: ${method}`)); }, this.options.requestTimeout); this.pendingRequests.set(id, { resolve, reject, timeout, onUpdate }), (_a = this.ws) == null || _a.send(JSON.stringify(requestMessage)); }); } /** * Sets up WebSocket event handlers * @param ws WebSocket instance */ setupWebSocketHandlers(ws) { ws.onmessage = (event) => { try { const message = JSON.parse(event.data); this.handleMessage(message); } catch (error) { console.error("Error handling WebSocket message:", error); } }, ws.onclose = () => { this.handleDisconnect(); }, ws.onerror = (event) => { console.error("WebSocket error:", event); }; } /** * Handles incoming WebSocket messages * @param message The message to handle */ handleMessage(message) { const { messageType, id } = message; switch (messageType) { case "request": this.handleRequest(message); break; case "response": this.handleResponse(id, message.payload); break; case "update": this.handleUpdate(id, message.payload); break; case "error": this.handleError(id, message.error.message); break; default: console.warn(`Unknown message type: ${messageType}`); } } /** * Handle incoming requests by invoking the registered method * @param message Request message */ async handleRequest(message) { const { id, method, payload } = message; if (!method) { this.sendError(id, "Method name is required"); return; } const methodDef = this.methods[method]; if (!methodDef) { this.sendError(id, `Method not found: ${method}`); return; } try { const sendUpdate = (update) => { this.sendUpdate(id, method, update); }, result = await methodDef.handler(payload, sendUpdate); this.sendResponse(id, method, result); } catch (error) { this.sendError( id, error instanceof Error ? error.message : String(error) ); } } /** * Handle response messages by resolving the pending request * @param id Request ID * @param payload Response payload */ handleResponse(id, payload) { const pendingRequest = this.pendingRequests.get(id); if (!pendingRequest) { console.warn(`Received response for unknown request ID: ${id}`); return; } clearTimeout(pendingRequest.timeout), this.pendingRequests.delete(id), pendingRequest.resolve(payload); } /** * Handle update messages by calling the update callback * @param id Request ID * @param payload Update payload */ handleUpdate(id, payload) { const pendingRequest = this.pendingRequests.get(id); if (!pendingRequest || !pendingRequest.onUpdate) { console.warn(`Received update for unknown request ID: ${id}`); return; } pendingRequest.onUpdate(payload); } /** * Handle error messages by rejecting the pending request * @param id Request ID * @param error Error message */ handleError(id, error) { const pendingRequest = this.pendingRequests.get(id); if (!pendingRequest) { console.warn(`Received error for unknown request ID: ${id}`); return; } clearTimeout(pendingRequest.timeout), this.pendingRequests.delete(id), pendingRequest.reject(new Error(error)); } /** * Send a response message * @param id Request ID * @param method Method name * @param payload Response payload */ sendResponse(id, method, payload) { if (!this.ws) throw new Error("WebSocket is not connected"); const responseMessage = { id, messageType: "response", method, payload }; this.ws.send(JSON.stringify(responseMessage)); } /** * Send an update message for streaming * @param id Request ID * @param method Method name * @param payload Update payload */ sendUpdate(id, method, payload) { if (!this.ws) throw new Error("WebSocket is not connected"); const updateMessage = { id, messageType: "update", method, payload }; this.ws.send(JSON.stringify(updateMessage)); } /** * Send an error message * @param id Request ID * @param errorMessage Error message */ sendError(id, errorMessage) { if (!this.ws) throw new Error("WebSocket is not connected"); const errorResponse = { id, messageType: "error", error: { message: errorMessage } }; this.ws.send(JSON.stringify(errorResponse)); } /** * Handle disconnection by attempting to reconnect */ handleDisconnect() { if (this.isIntentionalClose) { console.log( "WebSocket closed intentionally, not attempting to reconnect" ), this.clearPendingRequests(new Error("Connection closed by user")); return; } this.reconnectAttempts < this.options.maxReconnectAttempts ? (this.reconnectAttempts++, console.log( `Attempting to reconnect (${this.reconnectAttempts}/${this.options.maxReconnectAttempts})...` ), setTimeout( () => this.reconnect(), this.options.reconnectDelay * this.reconnectAttempts )) : (console.error("Max reconnection attempts reached"), this.clearPendingRequests(new Error("Connection closed"))); } /** * Clear all pending requests with an error * @param error Error to reject with */ clearPendingRequests(error) { this.pendingRequests.forEach(({ reject }) => { reject(error); }), this.pendingRequests.clear(); } /** * Close the WebSocket connection * @returns Promise that resolves when the connection is closed */ async close() { this.isIntentionalClose = !0, this.ws && (this.ws.close(), this.ws = null), this.clearPendingRequests(new Error("Connection closed by user")); } }; function validateWithZod(schema, data, context, silent = !1) { const result = schema.safeParse(data); if (!result.success) { const error = new Error( `Validation failed for ${context}: ${result.error.message}` ); if (silent) return console.error(error), data; throw error; } return result.data; } var ZodTypedBridge = class { constructor(bridge, contract2) { this.bridge = bridge, this.contract = contract2, this.call = new Proxy({}, { get: (target, prop) => (request, options) => this.callMethod(prop, request, options) }); } async callMethod(method, request, options) { const methodContract = this.contract.consumes[method]; if (!methodContract) throw new Error(`Method ${String(method)} not found in contract`); const validatedRequest = validateWithZod( methodContract.request, request, `request for method ${String(method)}` ), onUpdate = options != null && options.onUpdate && methodContract.update ? (update) => { var _a; if (methodContract.update) try { const validatedUpdate = validateWithZod( methodContract.update, update, `update for method ${String(method)}`, !0 // silently log validation errors ); (_a = options.onUpdate) == null || _a.call(options, validatedUpdate); } catch (error) { console.error("Update validation failed:", error); } } : void 0, response = await this.bridge.callMethod( method, validatedRequest, onUpdate ); return validateWithZod( methodContract.response, response, `response for method ${String(method)}` ); } register(implementations) { const wrappedImplementations = {}; for (const [method, implementation] of Object.entries(implementations)) { const methodContract = this.contract.serves[method]; if (!methodContract) throw new Error(`Method ${method} not found in contract`); wrappedImplementations[method] = async (request, sendUpdate) => { const validatedRequest = validateWithZod( methodContract.request, request, `request for method ${method}` ), wrappedSendUpdate = methodContract.update && sendUpdate ? (update) => { if (methodContract.update) try { const validatedUpdate = validateWithZod( methodContract.update, update, `update for method ${method}`, !0 // silently log validation errors ); sendUpdate(validatedUpdate); } catch (error) { console.error("Update validation failed:", error); } } : void 0, response = await implementation(validatedRequest, { sendUpdate: wrappedSendUpdate }); return validateWithZod( methodContract.response, response, `response for method ${method}` ); }; } this.bridge.register(wrappedImplementations); } async close() { await this.bridge.close(); } }, ClientBridge = class extends WebSocketRpcBridge { constructor(url, options) { super(options), this.reconnectTimer = null, this.url = url; } call(method, payload, onUpdate) { return this.callMethod(method, payload, onUpdate); } reconnect() { this.reconnectTimer && clearTimeout(this.reconnectTimer), this.reconnectTimer = setTimeout(async () => { try { await this.connect(); } catch { this.reconnect(); } }, this.options.reconnectDelay); } connect() { return new Promise((resolve, reject) => { try { const ws = new window.WebSocket(this.url); ws.onopen = () => { this.ws = ws, this.setupWebSocketHandlers(ws), resolve(); }, ws.onerror = () => { reject(new Error("Failed to connect to WebSocket server")); }; } catch (error) { reject(error); } }); } }, ZodClient = class extends ZodTypedBridge { constructor(url, contract2, options) { super(new ClientBridge(url, options), { serves: contract2.client || {}, consumes: contract2.server || {} }); } connect() { return this.bridge.connect(); } }; function createSRPCClientBridge(url, contract2, options) { return new ZodClient(url, contract2, options); } var util; (function(util2) { util2.assertEqual = (val) => val; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever, util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) obj[item] = item; return obj; }, util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] != "number"), filtered = {}; for (const k2 of validKeys) filtered[k2] = obj[k2]; return util2.objectValues(filtered); }, util2.objectValues = (obj) => util2.objectKeys(obj).map(function(e2) { return obj[e2]; }), util2.objectKeys = typeof Object.keys == "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) Object.prototype.hasOwnProperty.call(object, key) && keys.push(key); return keys; }, util2.find = (arr, checker) => { for (const item of arr) if (checker(item)) return item; }, util2.isInteger = typeof Number.isInteger == "function" ? (val) => Number.isInteger(val) : (val) => typeof val == "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val == "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues, util2.jsonStringifyReplacer = (_2, value) => typeof value == "bigint" ? value.toString() : value; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => ({ ...first, ...second // second overwrites first }); })(objectUtil || (objectUtil = {})); const ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]), getParsedType = (data) => { switch (typeof data) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": return Array.isArray(data) ? ZodParsedType.array : data === null ? ZodParsedType.null : data.then && typeof data.then == "function" && data.catch && typeof data.catch == "function" ? ZodParsedType.promise : typeof Map < "u" && data instanceof Map ? ZodParsedType.map : typeof Set < "u" && data instanceof Set ? ZodParsedType.set : typeof Date < "u" && data instanceof Date ? ZodParsedType.date : ZodParsedType.object; default: return ZodParsedType.unknown; } }, ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]), quotelessJson = (obj) => JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"); class ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(), this.issues = [], this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }, this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; Object.setPrototypeOf ? Object.setPrototypeOf(this, actualProto) : this.__proto__ = actualProto, this.name = "ZodError", this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }, fieldErrors = { _errors: [] }, processError = (error) => { for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError); else if (issue.code === "invalid_return_type") processError(issue.returnTypeError); else if (issue.code === "invalid_arguments") processError(issue.argumentsError); else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue)); else { let curr = fieldErrors, i2 = 0; for (; i2 < issue.path.length; ) { const el = issue.path[i2]; i2 === issue.path.length - 1 ? (curr[el] = curr[el] || { _errors: [] }, curr[el]._errors.push(mapper(issue))) : curr[el] = curr[el] || { _errors: [] }, curr = curr[el], i2++; } } }; return processError(this), fieldErrors; } static assert(value) { if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`); } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}, formErrors = []; for (const sub of this.issues) sub.path.length > 0 ? (fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [], fieldErrors[sub.path[0]].push(mapper(sub))) : formErrors.push(mapper(sub)); return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError.create = (issues) => new ZodError(issues); const errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: issue.received === ZodParsedType.undefined ? message = "Required" : message = `Expected ${issue.expected}, received ${issue.received}`; break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = "Invalid input"; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = "Invalid function arguments"; break; case ZodIssueCode.invalid_return_type: message = "Invalid function return type"; break; case ZodIssueCode.invalid_date: message = "Invalid date"; break; case ZodIssueCode.invalid_string: typeof issue.validation == "object" ? "includes" in issue.validation ? (message = `Invalid input: must include "${issue.validation.includes}"`, typeof issue.validation.position == "number" && (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)) : "startsWith" in issue.validation ? message = `Invalid input: must start with "${issue.validation.startsWith}"` : "endsWith" in issue.validation ? message = `Invalid input: must end with "${issue.validation.endsWith}"` : util.assertNever(issue.validation) : issue.validation !== "regex" ? message = `Invalid ${issue.validation}` : message = "Invalid"; break; case ZodIssueCode.too_small: issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(issue.minimum))}` : message = "Invalid input"; break; case ZodIssueCode.too_big: issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "bigint" ? message = `BigInt must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(issue.maximum))}` : message = "Invalid input"; break; case ZodIssueCode.custom: message = "Invalid input"; break; case ZodIssueCode.invalid_intersection_types: message = "Intersection results could not be merged"; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError, util.assertNever(issue); } return { message }; }; let overrideErrorMap = errorMap; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params, fullPath = [...path, ...issueData.path || []], fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) return { ...issueData, path: fullPath, message: issueData.message }; let errorMessage = ""; const maps = errorMaps.filter((m2) => !!m2).slice().reverse(); for (const map of maps) errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; return { ...issueData, path: fullPath, message: errorMessage }; }, EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(), issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === errorMap ? void 0 : errorMap // then global default map ].filter((x2) => !!x2) }); ctx.common.issues.push(issue); } class ParseStatus { constructor() { this.value = "valid"; } dirty() { this.value === "valid" && (this.value = "dirty"); } abort() { this.value !== "aborted" && (this.value = "aborted"); } static mergeArray(status, results) { const arrayValue = []; for (const s2 of results) { if (s2.status === "aborted") return INVALID; s2.status === "dirty" && status.dirty(), arrayValue.push(s2.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key, value = await pair.value; syncPairs.push({ key, value }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted" || value.status === "aborted") return INVALID; key.status === "dirty" && status.dirty(), value.status === "dirty" && status.dirty(), key.value !== "__proto__" && (typeof value.value < "u" || pair.alwaysSet) && (finalObject[key.value] = value.value); } return { status: status.value, value: finalObject }; } } const INVALID = Object.freeze({ status: "aborted" }), DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x2) => x2.status === "aborted", isDirty = (x2) => x2.status === "dirty", isValid = (x2) => x2.status === "valid", isAsync = (x2) => typeof Promise < "u" && x2 instanceof Promise; function __classPrivateFieldGet(receiver, state, kind, f2) { if (typeof state == "function" ? receiver !== state || !0 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f2) { if (typeof state == "function" ? receiver !== state || !0 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return state.set(receiver, value), value; } var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message == "string" ? { message } : message || {}, errorUtil2.toString = (message) => typeof message == "string" ? message : message == null ? void 0 : message.message; })(errorUtil || (errorUtil = {})); var _ZodEnum_cache, _ZodNativeEnum_cache; class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = [], this.parent = parent, this.data = value, this._path = path, this._key = key; } get path() { return this._cachedPath.length || (this._key instanceof Array ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath; } } const handleResult = (ctx, result) => { if (isValid(result)) return { success: !0, data: result.value }; if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected."); return { success: !1, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); return this._error = error, this._error; } }; }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); return errorMap2 ? { errorMap: errorMap2, description } : { errorMap: (iss, ctx) => { var _a, _b; const { message } = params; return iss.code === "invalid_enum_value" ? { message: message ?? ctx.defaultError } : typeof ctx.data > "u" ? { message: (_a = message ?? required_error) !== null && _a !== void 0 ? _a : ctx.defaultError } : iss.code !== "invalid_type" ? { message: ctx.defaultError } : { message: (_b = message ?? invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; }, description }; } class ZodType { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) throw new Error("Synchronous parse encountered promise."); return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params == null ? void 0 : params.async) !== null && _a !== void 0 ? _a : !1, contextualErrorMap: params == null ? void 0 : params.errorMap }, path: (params == null ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }, result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { var _a, _b; const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; if (!this["~standard"].async) try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err) { !((_b = (_a = err == null ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0) && _b.includes("encountered") && (this["~standard"].async = !0), ctx.common = { issues: [], async: !0 }; } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params == null ? void 0 : params.errorMap, async: !0 }, path: (params == null ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }, maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }), result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => typeof message == "string" || typeof message > "u" ? { message } : typeof message == "function" ? message(val) : message; return this._refinement((val, ctx) => { const result = check(val), setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val) }); return typeof Promise < "u" && result instanceof Promise ? result.then((data) => data ? !0 : (setError(), !1)) : result ? !0 : (setError(), !1); }); } refinement(check, refinementData) { return this._refinement((val, ctx) => check(val) ? !0 : (ctx.addIssue(typeof refinementData == "function" ? refinementData(val, ctx) : refinementData), !1)); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { this.spa = this.safeParseAsync, this._def = def, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this), this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional.create(this, this._def); } nullable() {