@pixelmatters/markup 1.6.1 → 1.6.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widget.js","names":["l","u","t","i","r","o","e","f","c","s","a","h","p","v","y","d","w","m","k","C","q","D","A","T","j","z","B","u","i","o","f","n","i","Base64.fromByteArray","Base64.toByteArray","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","Base64.toByteArray","Base64.fromByteArray","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","r"],"sources":["../../../node_modules/.pnpm/preact@10.29.1/node_modules/preact/dist/preact.module.js","../src/styles.css?inline","../../../node_modules/.pnpm/preact@10.29.1/node_modules/preact/hooks/dist/hooks.module.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/index.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/values/base64.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/common/index.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/values/value.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/values/errors.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/logging.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/udf_path_utils.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/local_state.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/request_manager.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/server/functionName.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/server/components/paths.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/server/api.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/optimistic_updates_impl.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/vendor/long.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/remote_query_set.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/protocol.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/web_socket_manager.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/session.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/vendor/jwt-decode/index.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/authentication_manager.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/metrics.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/client.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/pagination.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/sync/paginated_query_client.js","../../../node_modules/.pnpm/convex@1.38.0_react@19.2.6/node_modules/convex/dist/esm/browser/simple_client.js","../src/lib/machine.ts","../src/lib/use-async-action.ts","../../../node_modules/.pnpm/@medv+finder@4.0.2/node_modules/@medv/finder/finder.js","../src/runtime/anchor.ts","../src/runtime/api.ts","../src/runtime/history-observer.ts","../src/runtime/identity-store.ts","../src/runtime/popup-auth.ts","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/util.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/clone-pseudos.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/mimes.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/dataurl.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/clone-node.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/embed-resources.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/embed-images.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/apply-style.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/embed-webfonts.js","../../../node_modules/.pnpm/html-to-image@1.11.13/node_modules/html-to-image/es/index.js","../src/runtime/screenshot.ts","../src/runtime/use-subscription-token.ts","../src/runtime/utils.ts","../src/runtime/use-drag.ts","../../../node_modules/.pnpm/preact@10.29.1/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js","../src/runtime/ui/icons.tsx","../src/runtime/ui/fab.tsx","../src/runtime/use-focus-trap.ts","../src/runtime/use-object-url.ts","../src/runtime/ui/author-prompt.tsx","../src/runtime/ui/composer.tsx","../src/runtime/ui/new-thread-popover.tsx","../src/runtime/ui/pin.tsx","../src/runtime/ui/placement-overlay.tsx","../src/runtime/ui/thread-popover.tsx","../src/runtime/ui/app.tsx","../src/runtime/mount.tsx","../src/widget.ts"],"sourcesContent":["var n,l,u,t,i,r,o,e,f,c,s,a,h,p,v,y,d={},w=[],_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,g=Array.isArray;function m(n,l){for(var u in l)n[u]=l[u];return n}function b(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function k(l,u,t){var i,r,o,e={};for(o in u)\"key\"==o?i=u[o]:\"ref\"==o?r=u[o]:e[o]=u[o];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):t),\"function\"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===e[o]&&(e[o]=l.defaultProps[o]);return x(l,e,i,r,null)}function x(n,t,i,r,o){var e={type:n,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o?++u:o,__i:-1,__u:0};return null==o&&null!=l.vnode&&l.vnode(e),e}function M(){return{current:null}}function S(n){return n.children}function C(n,l){this.props=n,this.context=l}function $(n,l){if(null==l)return n.__?$(n.__,n.__i+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return\"function\"==typeof n.type?$(n):null}function I(n){if(n.__P&&n.__d){var u=n.__v,t=u.__e,i=[],r=[],o=m({},u);o.__v=u.__v+1,l.vnode&&l.vnode(o),q(n.__P,o,u,n.__n,n.__P.namespaceURI,32&u.__u?[t]:null,i,null==t?$(u):t,!!(32&u.__u),r),o.__v=u.__v,o.__.__k[o.__i]=o,D(i,o,r),u.__e=u.__=null,o.__e!=t&&P(o)}}function P(n){if(null!=(n=n.__)&&null!=n.__c)return n.__e=n.__c.base=null,n.__k.some(function(l){if(null!=l&&null!=l.__e)return n.__e=n.__c.base=l.__e}),P(n)}function A(n){(!n.__d&&(n.__d=!0)&&i.push(n)&&!H.__r++||r!=l.debounceRendering)&&((r=l.debounceRendering)||o)(H)}function H(){try{for(var n,l=1;i.length;)i.length>l&&i.sort(e),n=i.shift(),l=i.length,I(n)}finally{i.length=H.__r=0}}function L(n,l,u,t,i,r,o,e,f,c,s){var a,h,p,v,y,_,g,m=t&&t.__k||w,b=l.length;for(f=T(u,l,m,f,b),a=0;a<b;a++)null!=(p=u.__k[a])&&(h=-1!=p.__i&&m[p.__i]||d,p.__i=a,_=q(n,p,h,i,r,o,e,f,c,s),v=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&J(h.ref,null,p),s.push(p.ref,p.__c||v,p)),null==y&&null!=v&&(y=v),(g=!!(4&p.__u))||h.__k===p.__k?(f=j(p,f,n,g),g&&h.__e&&(h.__e=null)):\"function\"==typeof p.type&&void 0!==_?f=_:v&&(f=v.nextSibling),p.__u&=-7);return u.__e=y,f}function T(n,l,u,t,i){var r,o,e,f,c,s=u.length,a=s,h=0;for(n.__k=new Array(i),r=0;r<i;r++)null!=(o=l[r])&&\"boolean\"!=typeof o&&\"function\"!=typeof o?(\"string\"==typeof o||\"number\"==typeof o||\"bigint\"==typeof o||o.constructor==String?o=n.__k[r]=x(null,o,null,null,null):g(o)?o=n.__k[r]=x(S,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?o=n.__k[r]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):n.__k[r]=o,f=r+h,o.__=n,o.__b=n.__b+1,e=null,-1!=(c=o.__i=O(o,u,f,a))&&(a--,(e=u[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>s?h--:i<s&&h++),\"function\"!=typeof o.type&&(o.__u|=4)):c!=f&&(c==f-1?h--:c==f+1?h++:(c>f?h--:h++,o.__u|=4))):n.__k[r]=null;if(a)for(r=0;r<s;r++)null!=(e=u[r])&&0==(2&e.__u)&&(e.__e==t&&(t=$(e)),K(e,e));return t}function j(n,l,u,t){var i,r;if(\"function\"==typeof n.type){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,l=j(i[r],l,u,t));return l}n.__e!=l&&(t&&(l&&n.type&&!l.parentNode&&(l=$(n)),u.insertBefore(n.__e,l||null)),l=n.__e);do{l=l&&l.nextSibling}while(null!=l&&8==l.nodeType);return l}function F(n,l){return l=l||[],null==n||\"boolean\"==typeof n||(g(n)?n.some(function(n){F(n,l)}):l.push(n)),l}function O(n,l,u,t){var i,r,o,e=n.key,f=n.type,c=l[u],s=null!=c&&0==(2&c.__u);if(null===c&&null==e||s&&e==c.key&&f==c.type)return u;if(t>(s?1:0))for(i=u-1,r=u+1;i>=0||r<l.length;)if(null!=(c=l[o=i>=0?i--:r++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return o;return-1}function z(n,l,u){\"-\"==l[0]?n.setProperty(l,null==u?\"\":u):n[l]=null==u?\"\":\"number\"!=typeof u||_.test(l)?u:u+\"px\"}function N(n,l,u,t,i){var r,o;n:if(\"style\"==l)if(\"string\"==typeof u)n.style.cssText=u;else{if(\"string\"==typeof t&&(n.style.cssText=t=\"\"),t)for(l in t)u&&l in u||z(n.style,l,\"\");if(u)for(l in u)t&&u[l]==t[l]||z(n.style,l,u[l])}else if(\"o\"==l[0]&&\"n\"==l[1])r=l!=(l=l.replace(a,\"$1\")),o=l.toLowerCase(),l=o in n||\"onFocusOut\"==l||\"onFocusIn\"==l?o.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+r]=u,u?t?u[s]=t[s]:(u[s]=h,n.addEventListener(l,r?v:p,r)):n.removeEventListener(l,r?v:p,r);else{if(\"http://www.w3.org/2000/svg\"==i)l=l.replace(/xlink(H|:h)/,\"h\").replace(/sName$/,\"s\");else if(\"width\"!=l&&\"height\"!=l&&\"href\"!=l&&\"list\"!=l&&\"form\"!=l&&\"tabIndex\"!=l&&\"download\"!=l&&\"rowSpan\"!=l&&\"colSpan\"!=l&&\"role\"!=l&&\"popover\"!=l&&l in n)try{n[l]=null==u?\"\":u;break n}catch(n){}\"function\"==typeof u||(null==u||!1===u&&\"-\"!=l[4]?n.removeAttribute(l):n.setAttribute(l,\"popover\"==l&&1==u?\"\":u))}}function V(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u[c])u[c]=h++;else if(u[c]<t[s])return;return t(l.event?l.event(u):u)}}}function q(n,u,t,i,r,o,e,f,c,s){var a,h,p,v,y,d,_,k,x,M,$,I,P,A,H,T=u.type;if(void 0!==u.constructor)return null;128&t.__u&&(c=!!(32&t.__u),o=[f=u.__e=t.__e]),(a=l.__b)&&a(u);n:if(\"function\"==typeof T)try{if(k=u.props,x=T.prototype&&T.prototype.render,M=(a=T.contextType)&&i[a.__c],$=a?M?M.props.value:a.__:i,t.__c?_=(h=u.__c=t.__c).__=h.__E:(x?u.__c=h=new T(k,$):(u.__c=h=new C(k,$),h.constructor=T,h.render=Q),M&&M.sub(h),h.state||(h.state={}),h.__n=i,p=h.__d=!0,h.__h=[],h._sb=[]),x&&null==h.__s&&(h.__s=h.state),x&&null!=T.getDerivedStateFromProps&&(h.__s==h.state&&(h.__s=m({},h.__s)),m(h.__s,T.getDerivedStateFromProps(k,h.__s))),v=h.props,y=h.state,h.__v=u,p)x&&null==T.getDerivedStateFromProps&&null!=h.componentWillMount&&h.componentWillMount(),x&&null!=h.componentDidMount&&h.__h.push(h.componentDidMount);else{if(x&&null==T.getDerivedStateFromProps&&k!==v&&null!=h.componentWillReceiveProps&&h.componentWillReceiveProps(k,$),u.__v==t.__v||!h.__e&&null!=h.shouldComponentUpdate&&!1===h.shouldComponentUpdate(k,h.__s,$)){u.__v!=t.__v&&(h.props=k,h.state=h.__s,h.__d=!1),u.__e=t.__e,u.__k=t.__k,u.__k.some(function(n){n&&(n.__=u)}),w.push.apply(h.__h,h._sb),h._sb=[],h.__h.length&&e.push(h);break n}null!=h.componentWillUpdate&&h.componentWillUpdate(k,h.__s,$),x&&null!=h.componentDidUpdate&&h.__h.push(function(){h.componentDidUpdate(v,y,d)})}if(h.context=$,h.props=k,h.__P=n,h.__e=!1,I=l.__r,P=0,x)h.state=h.__s,h.__d=!1,I&&I(u),a=h.render(h.props,h.state,h.context),w.push.apply(h.__h,h._sb),h._sb=[];else do{h.__d=!1,I&&I(u),a=h.render(h.props,h.state,h.context),h.state=h.__s}while(h.__d&&++P<25);h.state=h.__s,null!=h.getChildContext&&(i=m(m({},i),h.getChildContext())),x&&!p&&null!=h.getSnapshotBeforeUpdate&&(d=h.getSnapshotBeforeUpdate(v,y)),A=null!=a&&a.type===S&&null==a.key?E(a.props.children):a,f=L(n,g(A)?A:[A],u,t,i,r,o,e,f,c,s),h.base=u.__e,u.__u&=-161,h.__h.length&&e.push(h),_&&(h.__E=h.__=null)}catch(n){if(u.__v=null,c||null!=o)if(n.then){for(u.__u|=c?160:128;f&&8==f.nodeType&&f.nextSibling;)f=f.nextSibling;o[o.indexOf(f)]=null,u.__e=f}else{for(H=o.length;H--;)b(o[H]);B(u)}else u.__e=t.__e,u.__k=t.__k,n.then||B(u);l.__e(n,u,t)}else null==o&&u.__v==t.__v?(u.__k=t.__k,u.__e=t.__e):f=u.__e=G(t.__e,u,t,i,r,o,e,c,s);return(a=l.diffed)&&a(u),128&u.__u?void 0:f}function B(n){n&&(n.__c&&(n.__c.__e=!0),n.__k&&n.__k.some(B))}function D(n,u,t){for(var i=0;i<t.length;i++)J(t[i],t[++i],t[++i]);l.__c&&l.__c(u,n),n.some(function(u){try{n=u.__h,u.__h=[],n.some(function(n){n.call(u)})}catch(n){l.__e(n,u.__v)}})}function E(n){return\"object\"!=typeof n||null==n||n.__b>0?n:g(n)?n.map(E):m({},n)}function G(u,t,i,r,o,e,f,c,s){var a,h,p,v,y,w,_,m=i.props||d,k=t.props,x=t.type;if(\"svg\"==x?o=\"http://www.w3.org/2000/svg\":\"math\"==x?o=\"http://www.w3.org/1998/Math/MathML\":o||(o=\"http://www.w3.org/1999/xhtml\"),null!=e)for(a=0;a<e.length;a++)if((y=e[a])&&\"setAttribute\"in y==!!x&&(x?y.localName==x:3==y.nodeType)){u=y,e[a]=null;break}if(null==u){if(null==x)return document.createTextNode(k);u=document.createElementNS(o,x,k.is&&k),c&&(l.__m&&l.__m(t,e),c=!1),e=null}if(null==x)m===k||c&&u.data==k||(u.data=k);else{if(e=e&&n.call(u.childNodes),!c&&null!=e)for(m={},a=0;a<u.attributes.length;a++)m[(y=u.attributes[a]).name]=y.value;for(a in m)y=m[a],\"dangerouslySetInnerHTML\"==a?p=y:\"children\"==a||a in k||\"value\"==a&&\"defaultValue\"in k||\"checked\"==a&&\"defaultChecked\"in k||N(u,a,null,y,o);for(a in k)y=k[a],\"children\"==a?v=y:\"dangerouslySetInnerHTML\"==a?h=y:\"value\"==a?w=y:\"checked\"==a?_=y:c&&\"function\"!=typeof y||m[a]===y||N(u,a,y,m[a],o);if(h)c||p&&(h.__html==p.__html||h.__html==u.innerHTML)||(u.innerHTML=h.__html),t.__k=[];else if(p&&(u.innerHTML=\"\"),L(\"template\"==t.type?u.content:u,g(v)?v:[v],t,i,r,\"foreignObject\"==x?\"http://www.w3.org/1999/xhtml\":o,e,f,e?e[0]:i.__k&&$(i,0),c,s),null!=e)for(a=e.length;a--;)b(e[a]);c||(a=\"value\",\"progress\"==x&&null==w?u.removeAttribute(\"value\"):null!=w&&(w!==u[a]||\"progress\"==x&&!w||\"option\"==x&&w!=m[a])&&N(u,a,w,m[a],o),a=\"checked\",null!=_&&_!=u[a]&&N(u,a,_,m[a],o))}return u}function J(n,u,t){try{if(\"function\"==typeof n){var i=\"function\"==typeof n.__u;i&&n.__u(),i&&null==u||(n.__u=n(u))}else n.current=u}catch(n){l.__e(n,t)}}function K(n,u,t){var i,r;if(l.unmount&&l.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||J(i,null,u)),null!=(i=n.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(n){l.__e(n,u)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&K(i[r],u,t||\"function\"!=typeof n.type);t||b(n.__e),n.__c=n.__=n.__e=void 0}function Q(n,l,u){return this.constructor(n,u)}function R(u,t,i){var r,o,e,f;t==document&&(t=document.documentElement),l.__&&l.__(u,t),o=(r=\"function\"==typeof i)?null:i&&i.__k||t.__k,e=[],f=[],q(t,u=(!r&&i||t).__k=k(S,null,[u]),o||d,d,t.namespaceURI,!r&&i?[i]:o?null:t.firstChild?n.call(t.childNodes):null,e,!r&&i?i:o?o.__e:t.firstChild,r,f),D(e,u,f)}function U(n,l){R(n,l,U)}function W(l,u,t){var i,r,o,e,f=m({},l.props);for(o in l.type&&l.type.defaultProps&&(e=l.type.defaultProps),u)\"key\"==o?i=u[o]:\"ref\"==o?r=u[o]:f[o]=void 0===u[o]&&null!=e?e[o]:u[o];return arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),x(l.type,f,i||l.key,r||l.ref,null)}function X(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=!0,A(n)})},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n)}}),n.children}return l.__c=\"__cC\"+y++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}n=w.slice,l={__e:function(n,l,u,t){for(var i,r,o;l=l.__;)if((i=l.__c)&&!i.__)try{if((r=i.constructor)&&null!=r.getDerivedStateFromError&&(i.setState(r.getDerivedStateFromError(n)),o=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),o=i.__d),o)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},C.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=m({},this.state),\"function\"==typeof n&&(n=n(m({},u),this.props)),n&&m(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),A(this))},C.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),A(this))},C.prototype.render=S,i=[],o=\"function\"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n,l){return n.__v.__b-l.__v.__b},H.__r=0,f=Math.random().toString(8),c=\"__d\"+f,s=\"__a\"+f,a=/(PointerCapture)$|Capture$/i,h=0,p=V(!1),v=V(!0),y=0;export{C as Component,S as Fragment,W as cloneElement,X as createContext,k as createElement,M as createRef,k as h,U as hydrate,t as isValidElement,l as options,R as render,F as toChildArray};\n//# sourceMappingURL=preact.module.js.map\n","/*\n * Markup widget styles.\n *\n * All rules are scoped to the shadow root via the `markup-*` class prefix and\n * `:host`. We deliberately avoid Tailwind here — a hand-rolled stylesheet is\n * smaller, easier to ship in a single shadow-DOM <style>, and won't conflict\n * with whatever the host page uses.\n */\n\n:host {\n --markup-paper: #fdfcfa;\n --markup-ink: #1a1614;\n --markup-muted: #6b6661;\n --markup-border: rgba(26, 22, 20, 0.1);\n --markup-border-strong: rgba(26, 22, 20, 0.18);\n --markup-brand: #e35d2a;\n --markup-brand-hover: #c84d20;\n --markup-team: #2a4ac8;\n --markup-shadow: 0 1px 2px rgba(26, 22, 20, 0.06), 0 8px 28px rgba(26, 22, 20, 0.12);\n --markup-overlay-tint: rgba(26, 22, 20, 0.04);\n --markup-danger: #dc2626;\n --markup-radius: 6px;\n --markup-radius-sm: 4px;\n --markup-font:\n 'Geist Variable', 'Geist', ui-sans-serif, -apple-system, BlinkMacSystemFont, 'Segoe UI',\n system-ui, sans-serif;\n --markup-font-mono:\n 'Geist Mono Variable', 'Geist Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n\n all: initial;\n font-family: var(--markup-font);\n font-size: 14px;\n line-height: 1.5;\n color: var(--markup-ink);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Dark palette — applied when:\n * - data-theme=\"dark\" is set explicitly on the host (forces dark), OR\n * - no explicit theme is set AND the system prefers dark\n * data-theme=\"light\" wins over the media query so hosts can force light. */\n:host([data-theme='dark']) {\n --markup-paper: #1a1614;\n --markup-ink: #fdfcfa;\n --markup-muted: #a8a39e;\n --markup-border: rgba(253, 252, 250, 0.12);\n --markup-border-strong: rgba(253, 252, 250, 0.22);\n --markup-team: #7b99f0;\n --markup-shadow: 0 1px 2px rgba(0, 0, 0, 0.35), 0 12px 40px rgba(0, 0, 0, 0.45);\n --markup-overlay-tint: rgba(253, 252, 250, 0.05);\n --markup-danger: #f87171;\n}\n\n@media (prefers-color-scheme: dark) {\n :host(:not([data-theme='light'])) {\n --markup-paper: #1a1614;\n --markup-ink: #fdfcfa;\n --markup-muted: #a8a39e;\n --markup-border: rgba(253, 252, 250, 0.12);\n --markup-border-strong: rgba(253, 252, 250, 0.22);\n --markup-team: #7b99f0;\n --markup-shadow: 0 1px 2px rgba(0, 0, 0, 0.35), 0 12px 40px rgba(0, 0, 0, 0.45);\n --markup-overlay-tint: rgba(253, 252, 250, 0.05);\n --markup-danger: #f87171;\n }\n}\n\n.markup-shadow-root {\n font-family: var(--markup-font);\n}\n\n.markup-shadow-root *,\n.markup-shadow-root *::before,\n.markup-shadow-root *::after {\n box-sizing: border-box;\n}\n\n/* Resets wrapped in :where() so they have 0 specificity and never beat\n * component-level color/font overrides like .markup-fab or .markup-btn-primary. */\n:where(.markup-shadow-root button, .markup-shadow-root input, .markup-shadow-root textarea) {\n font: inherit;\n color: inherit;\n}\n\n.markup-eyebrow {\n font-family: var(--markup-font-mono);\n font-size: 10px;\n font-weight: 500;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n color: var(--markup-muted);\n}\n\n/* ────────── FAB ────────── */\n\n.markup-fab {\n position: fixed;\n bottom: 24px;\n /* Above the placement overlay (z:1) and any popovers so cancel always\n * receives its clicks, never the overlay underneath. */\n z-index: 10;\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 9px 14px;\n border: none;\n border-radius: 999px;\n background: var(--markup-ink);\n color: var(--markup-paper);\n cursor: pointer;\n /* Claim touch gestures so a finger drag moves the FAB instead of\n * scrolling the page; tap-to-toggle still works (clicks are\n * synthesized from pointer up/down regardless of touch-action). */\n touch-action: none;\n font-size: 13px;\n font-weight: 500;\n letter-spacing: -0.01em;\n pointer-events: auto;\n box-shadow:\n 0 0 0 1px color-mix(in srgb, var(--markup-brand) 35%, transparent),\n var(--markup-shadow);\n transition:\n background 150ms ease,\n box-shadow 150ms ease,\n transform 150ms ease;\n}\n.markup-fab:hover {\n background: var(--markup-brand);\n box-shadow:\n 0 0 0 1px color-mix(in srgb, var(--markup-brand) 0%, transparent),\n var(--markup-shadow);\n}\n.markup-fab:active {\n transform: translateY(1px);\n}\n.markup-fab.is-active {\n background: var(--markup-brand);\n box-shadow: var(--markup-shadow);\n}\n.markup-fab.is-active:hover {\n background: var(--markup-brand-hover);\n}\n.markup-fab .markup-fab-icon {\n color: var(--markup-brand);\n transition: color 150ms ease;\n}\n.markup-fab:hover .markup-fab-icon,\n.markup-fab.is-active .markup-fab-icon {\n color: var(--markup-paper);\n}\n.markup-fab-right {\n right: 24px;\n}\n.markup-fab-left {\n left: 24px;\n}\n/* Center variant — auto-margin between left:0 and right:0 centers the\n * FAB without a `transform`, leaving the `:active { translateY(1px) }`\n * press affordance intact. `width: max-content` lets the pill shrink\n * to its content so it doesn't span the viewport. */\n.markup-fab-center {\n left: 0;\n right: 0;\n margin-inline: auto;\n width: max-content;\n}\n/* While the user is dragging the FAB it ignores corner anchoring and\n * follows inline left/top coords. The touch-action: none claim ensures\n * a finger drag moves the FAB instead of scrolling the page. */\n.markup-fab.is-floating {\n bottom: auto;\n right: auto;\n left: 0;\n top: 0;\n}\n.markup-fab.is-dragging {\n cursor: grabbing;\n transition: none;\n}\n.markup-fab-icon {\n display: inline-flex;\n align-items: center;\n}\n.markup-fab-label {\n font-family: var(--markup-font);\n}\n/* Icon-only variant — square padding so the rounded corners resolve to\n * a circle. Height matches the default FAB (34px) so swapping variants\n * doesn't shift the baseline. */\n.markup-fab.is-icon-only {\n gap: 0;\n padding: 9px;\n}\n\n/* ────────── HUD-hidden toast ──────────\n * Brief instructional message shown once when the HUD is hidden via\n * shortcut or modifier-click. Mirrors the FAB corner so the user's\n * eye lands in the same spot the FAB just vacated; auto-dismisses. */\n\n.markup-hud-hidden-toast {\n position: fixed;\n bottom: 24px;\n z-index: 10;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 8px 14px;\n border-radius: 999px;\n background: var(--markup-ink);\n color: var(--markup-paper);\n font-size: 12px;\n font-weight: 500;\n letter-spacing: -0.01em;\n box-shadow: var(--markup-shadow);\n pointer-events: none;\n animation:\n markup-hud-hidden-in 220ms ease-out,\n markup-hud-hidden-out 320ms ease-in 4.6s forwards;\n}\n.markup-hud-hidden-toast-right {\n right: 24px;\n}\n.markup-hud-hidden-toast-left {\n left: 24px;\n}\n.markup-hud-hidden-toast-center {\n left: 0;\n right: 0;\n margin-inline: auto;\n width: max-content;\n}\n.markup-kbd {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 18px;\n height: 18px;\n padding: 0 5px;\n border-radius: 4px;\n background: color-mix(in srgb, var(--markup-paper) 14%, transparent);\n color: var(--markup-paper);\n font-family: var(--markup-font);\n font-size: 10px;\n font-weight: 600;\n line-height: 1;\n}\n\n@keyframes markup-hud-hidden-in {\n from {\n opacity: 0;\n transform: translateY(8px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n}\n@keyframes markup-hud-hidden-out {\n from {\n opacity: 1;\n transform: translateY(0);\n }\n to {\n opacity: 0;\n transform: translateY(4px);\n }\n}\n\n/* ────────── Pins layer ────────── */\n\n.markup-pins-layer {\n position: fixed;\n inset: 0;\n pointer-events: none;\n}\n\n.markup-pin {\n position: absolute;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n margin-top: -28px;\n padding: 0;\n border: none;\n background: var(--markup-ink);\n color: var(--markup-brand);\n border-radius: 50% 50% 50% 4px;\n cursor: pointer;\n pointer-events: auto;\n box-shadow:\n 0 0 0 2px var(--markup-paper),\n 0 0 0 3px color-mix(in srgb, var(--markup-brand) 35%, transparent),\n var(--markup-shadow);\n transition:\n transform 150ms ease,\n background 150ms ease,\n color 150ms ease,\n opacity 150ms ease,\n top 200ms ease,\n left 200ms ease;\n}\n.markup-pin:hover,\n.markup-pin.is-active {\n background: var(--markup-brand);\n color: var(--markup-paper);\n}\n.markup-pin.is-anchor {\n anchor-name: --markup-active-anchor;\n}\n/* Anchor selector didn't resolve — pin is at the fraction-based fallback\n position. Dim so the (likely wrong) location reads as tentative; once\n the anchor element appears, the position transition makes the pin\n snap smoothly to its real spot. */\n.markup-pin.is-unresolved {\n opacity: 0.5;\n}\n.markup-pin-ghost {\n background: var(--markup-brand);\n color: var(--markup-paper);\n cursor: default;\n pointer-events: none;\n animation: markup-ghost-pulse 1200ms ease-in-out infinite;\n}\n\n.markup-pin-dot {\n display: inline-block;\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: currentColor;\n}\n\n.markup-pin-count {\n position: absolute;\n top: -4px;\n left: 50%;\n transform: translate(-50%, -50%);\n min-width: 16px;\n height: 16px;\n padding: 0 4px;\n border-radius: 999px;\n background: var(--markup-brand);\n color: var(--markup-paper);\n font-family: var(--markup-font-mono);\n font-size: 9px;\n font-weight: 600;\n line-height: 16px;\n text-align: center;\n box-shadow: 0 0 0 2px var(--markup-paper);\n}\n\n@keyframes markup-ghost-pulse {\n 0%,\n 100% {\n box-shadow:\n 0 0 0 2px var(--markup-paper),\n 0 0 0 0 rgba(227, 93, 42, 0.4);\n }\n 50% {\n box-shadow:\n 0 0 0 2px var(--markup-paper),\n 0 0 0 10px rgba(227, 93, 42, 0);\n }\n}\n\n/* ────────── Placement overlay ────────── */\n\n.markup-placement-overlay {\n position: fixed;\n inset: 0;\n background: var(--markup-overlay-tint);\n cursor: crosshair;\n pointer-events: auto;\n z-index: 1;\n animation: markup-overlay-in 180ms ease-out;\n}\n.markup-placement-cursor-help {\n position: fixed;\n top: 24px;\n left: 50%;\n /* baseline transform; the keyframes animate from a higher offset */\n transform: translate(-50%, 0);\n padding: 10px 16px;\n background: var(--markup-ink);\n color: var(--markup-paper);\n border-radius: 999px;\n font-size: 12px;\n font-weight: 500;\n letter-spacing: -0.01em;\n box-shadow: var(--markup-shadow);\n pointer-events: none;\n animation: markup-help-in 220ms ease-out 60ms backwards;\n}\n\n@keyframes markup-overlay-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n@keyframes markup-help-in {\n from {\n opacity: 0;\n transform: translate(-50%, -8px);\n }\n to {\n opacity: 1;\n transform: translate(-50%, 0);\n }\n}\n\n/* ────────── Popover ────────── */\n\n/*\n * Uses the Popover API (`popover=\"auto\"`) — the browser promotes the element\n * into the top layer and gives us ESC + outside-click dismissal for free.\n * We override the UA's defaults (inset:0, margin:auto, fit-content sizing)\n * and pin position via CSS Anchor Positioning, falling back to JS-supplied\n * `--markup-pop-x` / `--markup-pop-y` custom properties when the API isn't\n * supported.\n */\n.markup-popover {\n position: fixed;\n inset: auto;\n margin: 0;\n padding: 0;\n width: 320px;\n max-width: calc(100vw - 24px);\n height: auto;\n /* never grow taller than the viewport — comments list scrolls inside */\n max-height: calc(100dvh - 24px);\n /* fallback positioning */\n left: var(--markup-pop-x, 0);\n top: var(--markup-pop-y, 0);\n display: flex;\n flex-direction: column;\n gap: 0;\n background: var(--markup-paper);\n color: var(--markup-ink);\n border: 1px solid var(--markup-border-strong);\n border-radius: var(--markup-radius);\n box-shadow: var(--markup-shadow);\n pointer-events: auto;\n overflow: hidden;\n animation: markup-popover-in 160ms ease-out;\n}\n\n@supports (anchor-name: --x) {\n .markup-popover {\n position-anchor: --markup-active-anchor;\n left: calc(anchor(right) + 8px);\n top: calc(anchor(top) - 9px);\n /* Flip across either axis when we'd overflow, then prefer whichever\n * placement leaves the most block-axis room — so a pin near the bottom\n * of the viewport flips above instead of clipping at the bottom edge. */\n position-try-fallbacks:\n flip-block,\n flip-inline,\n flip-block flip-inline;\n position-try-order: most-block-size;\n }\n /* Once the user has dragged the popover, it takes over its own\n * placement: anchor positioning and the flip-fallbacks would otherwise\n * fight the user-chosen coords. */\n .markup-popover.is-floating {\n left: var(--markup-pop-x, 0);\n top: var(--markup-pop-y, 0);\n position-try-fallbacks: none;\n }\n}\n\n/* HUD-hide keeps the popover mounted so drafts and drag position\n * survive a Cmd+. peek; suppress paint and pointer events until the\n * HUD is restored. */\n.markup-popover.is-hud-hidden {\n display: none;\n}\n\n@keyframes markup-popover-in {\n from {\n opacity: 0;\n transform: translateY(-4px) scale(0.98);\n }\n to {\n opacity: 1;\n transform: translateY(0) scale(1);\n }\n}\n\n.markup-popover-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 12px;\n border-bottom: 1px solid var(--markup-border);\n cursor: grab;\n user-select: none;\n /* Claim touch gestures so a finger drag on the header moves the popover\n * instead of scrolling the page underneath. */\n touch-action: none;\n}\n.markup-popover.is-dragging .markup-popover-header {\n cursor: grabbing;\n}\n.markup-popover-header-actions {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.markup-thread-menu {\n position: relative;\n display: flex;\n}\n.markup-thread-menu-list {\n position: absolute;\n top: calc(100% + 6px);\n right: 0;\n z-index: 10;\n min-width: 160px;\n padding: 4px;\n background: var(--markup-paper);\n border: 1px solid var(--markup-border-strong);\n border-radius: var(--markup-radius);\n box-shadow: var(--markup-shadow);\n animation: markup-menu-in 120ms ease-out;\n}\n.markup-thread-menu-item {\n display: block;\n width: 100%;\n padding: 7px 10px;\n border: none;\n border-radius: var(--markup-radius-sm);\n background: transparent;\n color: var(--markup-ink);\n font-size: 13px;\n text-align: left;\n cursor: pointer;\n transition:\n background 100ms ease,\n color 100ms ease;\n}\n.markup-thread-menu-item:hover {\n background: var(--markup-border);\n}\n.markup-thread-menu-item.is-danger {\n color: var(--markup-danger, #dc2626);\n}\n.markup-thread-menu-item.is-danger:hover {\n background: color-mix(in srgb, var(--markup-danger, #dc2626) 10%, transparent);\n}\n.markup-thread-menu-item:disabled {\n opacity: 0.5;\n cursor: default;\n}\n@keyframes markup-menu-in {\n from {\n opacity: 0;\n transform: translateY(-4px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n.markup-popover-body {\n padding: 12px;\n}\n\n.markup-popover-byline {\n display: flex;\n align-items: center;\n gap: 4px;\n margin: 0 0 8px;\n font-size: 12px;\n color: var(--markup-muted);\n}\n.markup-popover-name {\n color: var(--markup-ink);\n font-weight: 500;\n}\n\n.markup-icon-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 24px;\n height: 24px;\n padding: 0;\n border: none;\n border-radius: var(--markup-radius-sm);\n background: transparent;\n color: var(--markup-muted);\n cursor: pointer;\n transition:\n background 120ms ease,\n color 120ms ease;\n}\n.markup-icon-btn:hover,\n.markup-icon-btn.is-open {\n background: var(--markup-border);\n color: var(--markup-ink);\n}\n\n/* ────────── Comments ────────── */\n\n.markup-comments {\n list-style: none;\n margin: 0;\n padding: 8px 12px 4px;\n max-height: 280px;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 12px;\n border-bottom: 1px solid var(--markup-border);\n background:\n linear-gradient(var(--markup-paper), transparent) top / 100% 20px no-repeat local,\n linear-gradient(transparent, var(--markup-paper)) bottom / 100% 20px no-repeat local,\n radial-gradient(farthest-side at 50% 0%, rgba(26, 22, 20, 0.1), transparent) top / 100% 10px\n no-repeat scroll,\n radial-gradient(farthest-side at 50% 100%, rgba(26, 22, 20, 0.1), transparent) bottom / 100%\n 10px no-repeat scroll;\n}\n\n.markup-comment {\n display: flex;\n flex-direction: column;\n gap: 4px;\n}\n.markup-comment-meta {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 11px;\n}\n.markup-comment-author {\n font-weight: 600;\n color: var(--markup-ink);\n}\n.markup-comment.is-team .markup-comment-author {\n color: var(--markup-team);\n}\n.markup-comment-badge {\n display: inline-flex;\n align-items: center;\n height: 14px;\n padding: 0 5px;\n border-radius: 999px;\n background: color-mix(in srgb, var(--markup-team) 12%, transparent);\n color: var(--markup-team);\n font-family: var(--markup-font-mono);\n font-size: 9px;\n line-height: 1;\n font-weight: 500;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n}\n.markup-comment-time {\n color: var(--markup-muted);\n font-family: var(--markup-font-mono);\n font-size: 10px;\n letter-spacing: 0.04em;\n}\n.markup-comment-body {\n margin: 0;\n font-size: 13px;\n line-height: 1.5;\n white-space: pre-wrap;\n word-break: break-word;\n}\n\n.markup-comment-edited {\n color: var(--markup-muted);\n font-size: 11px;\n}\n\n.markup-thread-actions {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n/* Both right-side actions get `margin-left: auto`: the first one\n * rendered absorbs all available space; the second's auto resolves to\n * 0 so they sit flush. Covers both \"picker only\" (non-owner comment)\n * and \"picker + ellipsis\" (owner comment) without conditional CSS. */\n.markup-comment-meta .markup-reaction-picker-wrap,\n.markup-thread-actions {\n margin-left: auto;\n}\n.markup-comment-meta .markup-reaction-add {\n width: 22px;\n height: 22px;\n margin-top: -4px;\n margin-bottom: -4px;\n}\n.markup-reaction-picker-wrap > .markup-icon-btn,\n.markup-comment-menu > .markup-icon-btn {\n margin-top: -4px;\n margin-bottom: -4px;\n}\n/* Flip the dropdown above the trigger when it would otherwise spill\n * out the bottom of the .markup-comments scroll container — overflow-y:\n * auto on the list would clip it. Direction is decided on open in\n * thread-popover.tsx based on the trigger's measured position. */\n.markup-comment-menu.is-up .markup-thread-menu-list {\n top: auto;\n bottom: calc(100% + 6px);\n animation-name: markup-menu-in-up;\n}\n/* When the thread has a single comment the popover is too short for a\n * vertical dropdown to fit, so we anchor the menu to the left of the\n * trigger instead. */\n.markup-comment-menu.is-side .markup-thread-menu-list {\n top: -4px;\n right: calc(100% + 2px);\n animation-name: markup-menu-in-side;\n}\n@keyframes markup-menu-in-side {\n from {\n opacity: 0;\n transform: translate(4px, 0);\n }\n to {\n opacity: 1;\n transform: translate(0, 0);\n }\n}\n@keyframes markup-menu-in-up {\n from {\n opacity: 0;\n transform: translateY(4px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n/* Layout: meta row holds author + time + the reaction trigger + the\n * ellipsis menu (in that order, with the trigger and menu pinned to\n * the right via `margin-left: auto` on the trigger). Body sits below\n * as a plain paragraph; chips (when any) below that.\n * .markup-comment is `position: relative` so the picker popover\n * anchors to it without leaking out of the scroll container. */\n.markup-comment {\n position: relative;\n}\n.markup-reactions {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 4px;\n margin-top: 2px;\n}\n.markup-reaction-chip {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n height: 22px;\n padding: 0 7px 0 6px;\n border: 1px solid var(--markup-border);\n border-radius: 999px;\n background: transparent;\n color: var(--markup-ink);\n font: inherit;\n font-size: 11px;\n line-height: 1;\n cursor: pointer;\n transition:\n background 120ms ease,\n border-color 120ms ease;\n}\n.markup-reaction-chip:hover:not(:disabled) {\n background: color-mix(in srgb, var(--markup-ink) 5%, transparent);\n}\n.markup-reaction-chip.is-mine {\n border-color: color-mix(in srgb, var(--markup-brand) 45%, transparent);\n background: color-mix(in srgb, var(--markup-brand) 10%, transparent);\n}\n.markup-reaction-chip.is-mine:hover:not(:disabled) {\n background: color-mix(in srgb, var(--markup-brand) 16%, transparent);\n}\n.markup-reaction-chip:disabled {\n cursor: default;\n opacity: 0.6;\n}\n.markup-reaction-emoji {\n font-size: 13px;\n line-height: 1;\n}\n.markup-reaction-count {\n font-family: var(--markup-font-mono);\n font-size: 10px;\n letter-spacing: 0.04em;\n color: var(--markup-muted);\n}\n.markup-reaction-chip.is-mine .markup-reaction-count {\n color: var(--markup-brand);\n}\n\n.markup-reaction-picker-wrap {\n position: relative;\n display: inline-flex;\n flex: 0 0 auto;\n opacity: 0;\n transition: opacity 120ms ease;\n}\n/* Reveal the whole wrap (trigger + dropdown) when the comment row is\n * hovered, has focus inside, or the picker is already open. Keeping\n * the open state visible lets the user move the cursor off the row to\n * pick an emoji without the wrap fading out. */\n.markup-comment:hover .markup-reaction-picker-wrap,\n.markup-comment:focus-within .markup-reaction-picker-wrap,\n.markup-reaction-picker-wrap.is-open {\n opacity: 1;\n}\n.markup-reaction-add {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 22px;\n height: 22px;\n border: 1px dashed var(--markup-border-strong);\n border-radius: 999px;\n background: transparent;\n color: var(--markup-muted);\n font: inherit;\n font-size: 13px;\n line-height: 1;\n cursor: pointer;\n transition:\n background 120ms ease,\n color 120ms ease,\n border-color 120ms ease;\n}\n.markup-reaction-add:hover,\n.markup-reaction-add.is-open {\n background: color-mix(in srgb, var(--markup-ink) 5%, transparent);\n color: var(--markup-ink);\n border-style: solid;\n}\n\n.markup-reaction-picker {\n position: absolute;\n top: calc(100% + 6px);\n right: 0;\n z-index: 1;\n display: flex;\n gap: 2px;\n padding: 4px;\n border: 1px solid var(--markup-border-strong);\n border-radius: 8px;\n background: var(--markup-paper);\n box-shadow:\n 0 1px 2px rgba(26, 22, 20, 0.06),\n 0 8px 28px rgba(26, 22, 20, 0.1);\n animation: markup-menu-in 120ms ease;\n}\n.markup-reaction-picker-wrap.is-up .markup-reaction-picker {\n top: auto;\n bottom: calc(100% + 6px);\n animation-name: markup-menu-in-up;\n}\n/* Mirrors `.markup-comment-menu.is-side`: with a single comment the\n * popover is too short for a vertical picker, so we anchor it to the\n * left of the trigger instead. */\n.markup-reaction-picker-wrap.is-side .markup-reaction-picker {\n top: -4px;\n right: calc(100% + 2px);\n animation-name: markup-menu-in-side;\n}\n.markup-reaction-picker-item {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: 0;\n border-radius: 6px;\n background: transparent;\n font-size: 16px;\n line-height: 1;\n cursor: pointer;\n transition: background 120ms ease;\n}\n.markup-reaction-picker-item:hover {\n background: color-mix(in srgb, var(--markup-ink) 8%, transparent);\n}\n.markup-reaction-picker-item.is-mine {\n background: color-mix(in srgb, var(--markup-brand) 14%, transparent);\n}\n\n.markup-comment-edit-form {\n display: flex;\n flex-direction: column;\n gap: 6px;\n}\n.markup-comment-edit-form .markup-textarea {\n width: 100%;\n padding: 8px 10px;\n border: 1px solid var(--markup-border-strong);\n border-radius: var(--markup-radius-sm);\n background: var(--markup-paper);\n color: var(--markup-ink);\n resize: vertical;\n outline: none;\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n}\n.markup-comment-edit-form .markup-textarea:focus-visible {\n border-color: var(--markup-brand);\n box-shadow: 0 0 0 3px rgba(227, 93, 42, 0.18);\n}\n.markup-comment-edit-actions {\n display: flex;\n justify-content: flex-end;\n gap: 6px;\n}\n\n/* ────────── Composer ────────── */\n\n.markup-composer {\n position: relative;\n display: flex;\n flex-direction: column;\n}\n\n.markup-composer-input {\n width: 100%;\n min-height: 36px;\n max-height: 96px;\n padding: 8px 10px;\n border: 1px solid var(--markup-border-strong);\n border-radius: var(--markup-radius-sm);\n background: var(--markup-paper);\n color: var(--markup-ink);\n resize: none;\n outline: none;\n font-family: var(--markup-font);\n font-size: 13px;\n line-height: 1.5;\n transition:\n border-color 120ms ease,\n box-shadow 120ms ease,\n border-bottom-left-radius 150ms ease,\n border-bottom-right-radius 150ms ease;\n}\n.markup-composer-input:focus-visible {\n border-color: var(--markup-brand);\n box-shadow: 0 0 0 3px rgba(227, 93, 42, 0.18);\n}\n.markup-composer-input:disabled {\n opacity: 0.6;\n}\n.markup-composer-input::placeholder {\n color: var(--markup-muted);\n}\n\n.markup-composer.is-filled .markup-composer-input {\n border-bottom-left-radius: 0;\n border-bottom-right-radius: 0;\n}\n\n.markup-composer-footer-wrap {\n display: grid;\n grid-template-rows: 0fr;\n transition: grid-template-rows 150ms ease;\n}\n.markup-composer.is-filled .markup-composer-footer-wrap {\n grid-template-rows: 1fr;\n}\n\n.markup-composer-footer {\n overflow: hidden;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 2px 2px 2px 10px;\n border: 1px solid var(--markup-border-strong);\n border-radius: 0 0 var(--markup-radius-sm) var(--markup-radius-sm);\n border-top: none;\n opacity: 0;\n transition: opacity 100ms ease;\n}\n.markup-composer.is-filled .markup-composer-footer {\n opacity: 1;\n transition-delay: 60ms;\n}\n.markup-composer-hint {\n font-family: var(--markup-font-mono);\n font-size: 10px;\n letter-spacing: 0.06em;\n color: var(--markup-muted);\n}\n.markup-composer-error {\n color: var(--markup-brand);\n}\n.markup-composer-actions {\n display: flex;\n align-items: center;\n gap: 6px;\n}\n\n.markup-composer-actions-empty {\n position: absolute;\n top: 3px;\n right: 3px;\n transition: opacity 120ms ease;\n}\n.markup-composer.is-filled .markup-composer-actions-empty {\n opacity: 0;\n pointer-events: none;\n}\n\n/* ────────── Author prompt ────────── */\n\n.markup-author-prompt {\n display: flex;\n flex-direction: column;\n gap: 10px;\n padding: 12px;\n}\n.markup-author-status {\n margin: 0;\n color: var(--markup-muted);\n font-size: 12px;\n}\n.markup-input {\n width: 100%;\n height: 36px;\n padding: 0 10px;\n border: 1px solid var(--markup-border-strong);\n border-radius: var(--markup-radius-sm);\n background: var(--markup-paper);\n color: var(--markup-ink);\n outline: none;\n font-size: 14px;\n transition:\n border-color 120ms ease,\n box-shadow 120ms ease;\n}\n.markup-input:focus-visible {\n border-color: var(--markup-brand);\n box-shadow: 0 0 0 3px rgba(227, 93, 42, 0.18);\n}\n\n/* ────────── Buttons ────────── */\n\n.markup-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 6px;\n height: 30px;\n padding: 0 8px;\n border: 1px solid transparent;\n border-radius: var(--markup-radius-sm);\n background: transparent;\n color: var(--markup-ink);\n cursor: pointer;\n font-size: 12px;\n font-weight: 500;\n letter-spacing: -0.01em;\n white-space: nowrap;\n transition:\n background 120ms ease,\n border-color 120ms ease,\n color 120ms ease,\n opacity 120ms ease;\n}\n.markup-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n.markup-btn-primary {\n background: var(--markup-ink);\n color: var(--markup-paper);\n}\n.markup-btn-primary:hover:not(:disabled) {\n background: var(--markup-brand);\n}\n.markup-btn-ghost {\n color: var(--markup-muted);\n}\n.markup-btn-ghost:hover:not(:disabled) {\n background: var(--markup-border);\n color: var(--markup-ink);\n}\n\n/* ────────── Screenshot row ────────── */\n\n.markup-screenshot-row {\n margin-top: 8px;\n padding-top: 8px;\n border-top: 1px solid var(--markup-border);\n}\n\n.markup-screenshot-status {\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--markup-muted);\n font-family: var(--markup-font-mono);\n font-size: 10px;\n letter-spacing: 0.06em;\n}\n\n.markup-screenshot-toggle {\n display: flex;\n align-items: center;\n gap: 5px;\n cursor: pointer;\n color: var(--markup-muted);\n font-family: var(--markup-font-mono);\n font-size: 10px;\n letter-spacing: 0.06em;\n transition: color 120ms ease;\n}\n.markup-screenshot-toggle:hover {\n color: var(--markup-ink);\n}\n\n.markup-screenshot-checkbox {\n width: 12px;\n height: 12px;\n margin: 0;\n accent-color: var(--markup-brand);\n cursor: pointer;\n}\n\n.markup-screenshot-thumb {\n display: block;\n margin: -5px 0 -5px auto;\n width: auto;\n height: 25px;\n border-radius: 3px;\n border: 1px solid var(--markup-border-strong);\n object-fit: cover;\n flex-shrink: 0;\n}\n\n.markup-screenshot-redacted {\n margin-top: 4px;\n font-family: var(--markup-font-mono);\n font-size: 10px;\n color: var(--markup-muted);\n}\n\n.markup-screenshot-redacted-chip {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n border: none;\n background: transparent;\n padding: 0;\n cursor: pointer;\n color: var(--markup-muted);\n font: inherit;\n}\n.markup-screenshot-redacted-chip:hover {\n color: var(--markup-ink);\n}\n\n.markup-screenshot-redacted-arrow {\n font-style: normal;\n}\n\n.markup-screenshot-redacted-list {\n margin-top: 3px;\n padding-left: 10px;\n}\n\n.markup-screenshot-redacted-selector {\n display: block;\n font-family: var(--markup-font-mono);\n font-size: 9px;\n color: var(--markup-muted);\n}\n\n.markup-screenshot-help {\n margin: 5px 0 0;\n font-family: var(--markup-font-mono);\n font-size: 10px;\n color: var(--markup-muted);\n line-height: 1.5;\n}\n\n.markup-screenshot-help-code {\n font-family: var(--markup-font-mono);\n color: var(--markup-ink);\n}\n\n/* ────────── Screenshot thumbnail inside first comment ────────── */\n\n.markup-comment-screenshot {\n display: block;\n margin-top: 8px;\n padding: 0;\n border: 1px solid var(--markup-border-strong);\n border-radius: var(--markup-radius-sm);\n background: transparent;\n cursor: pointer;\n overflow: hidden;\n transition:\n border-color 120ms ease,\n opacity 120ms ease;\n}\n.markup-comment-screenshot:hover {\n border-color: var(--markup-brand);\n opacity: 0.9;\n}\n.markup-comment-screenshot img {\n display: block;\n width: 100%;\n height: auto;\n max-height: 120px;\n object-fit: cover;\n object-position: top;\n}\n\n/* ────────── Screenshot lightbox ────────── */\n\n.markup-lightbox {\n position: fixed;\n inset: 0;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n margin: 0;\n padding: 24px;\n border: none;\n background: rgba(26, 22, 20, 0.88);\n}\n\n.markup-lightbox[open] {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.markup-lightbox::backdrop {\n display: none;\n}\n\n.markup-lightbox-img {\n max-width: 100%;\n max-height: 100%;\n border-radius: var(--markup-radius);\n object-fit: contain;\n box-shadow: var(--markup-shadow);\n animation: markup-lightbox-in 160ms ease-out;\n}\n\n.markup-lightbox-close {\n position: absolute;\n top: 16px;\n right: 16px;\n background: rgba(26, 22, 20, 0.6);\n color: #fdfcfa;\n}\n.markup-lightbox-close:hover {\n background: rgba(26, 22, 20, 0.85);\n color: #fdfcfa;\n}\n\n@keyframes markup-lightbox-in {\n from {\n opacity: 0;\n transform: scale(0.96);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* ────────── Reduced motion ────────── */\n\n@media (prefers-reduced-motion: reduce) {\n .markup-fab,\n .markup-pin,\n .markup-icon-btn,\n .markup-btn,\n .markup-popover,\n .markup-pin-ghost,\n .markup-placement-overlay,\n .markup-placement-cursor-help,\n .markup-lightbox-img {\n transition: none;\n animation: none;\n }\n}\n","import{options as n}from\"preact\";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function p(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,h(D,n)}function h(n,u,i){var o=p(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.__f)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(n){return n.__c});if(u.every(function(n){return!n.__N}))return!c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.some(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c&&c.call(this,n,t,r)||i};r.__f=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},r.shouldComponentUpdate=f}return o.__N||o.__}function y(n,u){var i=p(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i))}function _(n,u){var i=p(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){if(\"function\"==typeof n){var r=n(t());return function(){n(null),r&&\"function\"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function T(n,r){var u=p(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=p(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=p(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function g(){var n=p(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__=\"P\"+i[0]+\"-\"+i[1]++}return n.__}function j(){for(var n;n=f.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(z),t.__h.some(B),t.__h=[]}catch(r){t.__h=[],c.__e(r,n.__v)}}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(i.__h.some(z),i.__h.some(B),i.__h=[],t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.some(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.some(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k=\"function\"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;\"function\"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return\"function\"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,y as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,h as useReducer,A as useRef,d as useState};\n//# sourceMappingURL=hooks.module.js.map\n","\"use strict\";\nexport const version = \"1.38.0\";\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar lookup = [];\nvar revLookup = [];\nvar Arr = Uint8Array;\nvar code = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\nrevLookup[\"-\".charCodeAt(0)] = 62;\nrevLookup[\"_\".charCodeAt(0)] = 63;\nfunction getLens(b64) {\n var len = b64.length;\n if (len % 4 > 0) {\n throw new Error(\"Invalid string. Length must be a multiple of 4\");\n }\n var validLen = b64.indexOf(\"=\");\n if (validLen === -1) validLen = len;\n var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;\n return [validLen, placeHoldersLen];\n}\nexport function byteLength(b64) {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;\n}\nfunction _byteLength(_b64, validLen, placeHoldersLen) {\n return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;\n}\nexport function toByteArray(b64) {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n var curByte = 0;\n var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n var i;\n for (i = 0; i < len; i += 4) {\n tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = tmp >> 16 & 255;\n arr[curByte++] = tmp >> 8 & 255;\n arr[curByte++] = tmp & 255;\n }\n if (placeHoldersLen === 2) {\n tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;\n arr[curByte++] = tmp & 255;\n }\n if (placeHoldersLen === 1) {\n tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;\n arr[curByte++] = tmp >> 8 & 255;\n arr[curByte++] = tmp & 255;\n }\n return arr;\n}\nfunction tripletToBase64(num) {\n return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];\n}\nfunction encodeChunk(uint8, start, end) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);\n output.push(tripletToBase64(tmp));\n }\n return output.join(\"\");\n}\nexport function fromByteArray(uint8) {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3;\n var parts = [];\n var maxChunkLength = 16383;\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(\n encodeChunk(\n uint8,\n i,\n i + maxChunkLength > len2 ? len2 : i + maxChunkLength\n )\n );\n }\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + \"==\");\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + \"=\"\n );\n }\n return parts.join(\"\");\n}\nexport function fromByteArrayUrlSafeNoPadding(uint8) {\n return fromByteArray(uint8).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n//# sourceMappingURL=base64.js.map\n","\"use strict\";\nexport function parseArgs(args) {\n if (args === void 0) {\n return {};\n }\n if (!isSimpleObject(args)) {\n throw new Error(\n `The arguments to a Convex function must be an object. Received: ${args}`\n );\n }\n return args;\n}\nexport function validateDeploymentUrl(deploymentUrl) {\n if (typeof deploymentUrl === \"undefined\") {\n throw new Error(\n `Client created with undefined deployment address. If you used an environment variable, check that it's set.`\n );\n }\n if (typeof deploymentUrl !== \"string\") {\n throw new Error(\n `Invalid deployment address: found ${deploymentUrl}\".`\n );\n }\n if (!(deploymentUrl.startsWith(\"http:\") || deploymentUrl.startsWith(\"https:\"))) {\n throw new Error(\n `Invalid deployment address: Must start with \"https://\" or \"http://\". Found \"${deploymentUrl}\".`\n );\n }\n try {\n new URL(deploymentUrl);\n } catch {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" is not a valid URL. If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`\n );\n }\n if (deploymentUrl.endsWith(\".convex.site\")) {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`\n );\n }\n}\nexport function isSimpleObject(value) {\n const isObject = typeof value === \"object\";\n const prototype = Object.getPrototypeOf(value);\n const isSimple = prototype === null || prototype === Object.prototype || // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n // conditions but are still simple objects.\n prototype?.constructor?.name === \"Object\";\n return isObject && isSimple;\n}\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\nconst LITTLE_ENDIAN = true;\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nconst MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\nfunction isSpecial(n) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\nexport function slowBigIntToBase64(value) {\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g).reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\nexport function slowBase64ToBigInt(encoded) {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\nexport function modernBigIntToBase64(value) {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\nexport function modernBase64ToBigInt(encoded) {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\nexport const bigIntToBase64 = DataView.prototype.setBigInt64 ? modernBigIntToBase64 : slowBigIntToBase64;\nexport const base64ToBigInt = DataView.prototype.getBigInt64 ? modernBase64ToBigInt : slowBase64ToBigInt;\nconst MAX_IDENTIFIER_LEN = 1024;\nfunction validateObjectField(k) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`\n );\n }\n }\n}\nexport function jsonToConvex(value) {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value2) => jsonToConvex(value2));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`\n );\n }\n }\n const out = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\nconst MAX_VALUE_FOR_ERROR_LEN = 16384;\nexport function stringifyValueForError(value) {\n const str = JSON.stringify(value, (_key, value2) => {\n if (value2 === void 0) {\n return \"undefined\";\n }\n if (typeof value2 === \"bigint\") {\n return `${value2.toString()}n`;\n }\n return value2;\n });\n if (str.length > MAX_VALUE_FOR_ERROR_LEN) {\n const rest = \"[...truncated]\";\n let truncateAt = MAX_VALUE_FOR_ERROR_LEN - rest.length;\n const codePoint = str.codePointAt(truncateAt - 1);\n if (codePoint !== void 0 && codePoint > 65535) {\n truncateAt -= 1;\n }\n return str.substring(0, truncateAt) + rest;\n }\n return str;\n}\nfunction convexToJsonInternal(value, originalValue, context, includeTopLevelUndefined) {\n if (value === void 0) {\n const contextText = context && ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (Array.isArray(value)) {\n return value.map(\n (value2, i) => convexToJsonInternal(value2, originalValue, context + `[${i}]`, false)\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue)\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue)\n );\n }\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue)\n );\n }\n const out = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => k1 === k2 ? 0 : k1 < k2 ? -1 : 1);\n for (const [k, v] of entries) {\n if (v !== void 0) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`\n );\n }\n }\n return out;\n}\nfunction errorMessageForUnsupportedType(context, typeName, value, originalValue) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value\n )} is not a supported Convex type.`;\n }\n}\nfunction convexOrUndefinedToJsonInternal(value, originalValue, context) {\n if (value === void 0) {\n return { $undefined: null };\n } else {\n if (originalValue === void 0) {\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value\n )} but original value is undefined`\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\nexport function convexToJson(value) {\n return convexToJsonInternal(value, value, \"\", false);\n}\nexport function convexOrUndefinedToJson(value) {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\nexport function patchValueToJson(value) {\n return convexToJsonInternal(value, value, \"\", true);\n}\n//# sourceMappingURL=value.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar _a, _b;\nimport { stringifyValueForError } from \"./value.js\";\nconst IDENTIFYING_FIELD = Symbol.for(\"ConvexError\");\nexport class ConvexError extends (_b = Error, _a = IDENTIFYING_FIELD, _b) {\n constructor(data) {\n super(typeof data === \"string\" ? data : stringifyValueForError(data));\n __publicField(this, \"name\", \"ConvexError\");\n __publicField(this, \"data\");\n __publicField(this, _a, true);\n this.data = data;\n }\n}\n//# sourceMappingURL=errors.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nconst INFO_COLOR = \"color:rgb(0, 145, 255)\";\nfunction prefix_for_source(source) {\n switch (source) {\n case \"query\":\n return \"Q\";\n case \"mutation\":\n return \"M\";\n case \"action\":\n return \"A\";\n case \"any\":\n return \"?\";\n }\n}\nexport class DefaultLogger {\n constructor(options) {\n __publicField(this, \"_onLogLineFuncs\");\n __publicField(this, \"_verbose\");\n this._onLogLineFuncs = {};\n this._verbose = options.verbose;\n }\n addLogLineListener(func) {\n let id = Math.random().toString(36).substring(2, 15);\n for (let i = 0; i < 10; i++) {\n if (this._onLogLineFuncs[id] === void 0) {\n break;\n }\n id = Math.random().toString(36).substring(2, 15);\n }\n this._onLogLineFuncs[id] = func;\n return () => {\n delete this._onLogLineFuncs[id];\n };\n }\n logVerbose(...args) {\n if (this._verbose) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"debug\", `${(/* @__PURE__ */ new Date()).toISOString()}`, ...args);\n }\n }\n }\n log(...args) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"info\", ...args);\n }\n }\n warn(...args) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"warn\", ...args);\n }\n }\n error(...args) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"error\", ...args);\n }\n }\n}\nexport function instantiateDefaultLogger(options) {\n const logger = new DefaultLogger(options);\n logger.addLogLineListener((level, ...args) => {\n switch (level) {\n case \"debug\":\n console.debug(...args);\n break;\n case \"info\":\n console.log(...args);\n break;\n case \"warn\":\n console.warn(...args);\n break;\n case \"error\":\n console.error(...args);\n break;\n default: {\n level;\n console.log(...args);\n }\n }\n });\n return logger;\n}\nexport function instantiateNoopLogger(options) {\n return new DefaultLogger(options);\n}\nexport function logForFunction(logger, type, source, udfPath, message) {\n const prefix = prefix_for_source(source);\n if (typeof message === \"object\") {\n message = `ConvexError ${JSON.stringify(message.errorData, null, 2)}`;\n }\n if (type === \"info\") {\n const match = message.match(/^\\[.*?\\] /);\n if (match === null) {\n logger.error(\n `[CONVEX ${prefix}(${udfPath})] Could not parse console.log`\n );\n return;\n }\n const level = message.slice(1, match[0].length - 2);\n const args = message.slice(match[0].length);\n logger.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`, INFO_COLOR, args);\n } else {\n logger.error(`[CONVEX ${prefix}(${udfPath})] ${message}`);\n }\n}\nexport function logFatalError(logger, message) {\n const errorMessage = `[CONVEX FATAL ERROR] ${message}`;\n logger.error(errorMessage);\n return new Error(errorMessage);\n}\nexport function createHybridErrorStacktrace(source, udfPath, result) {\n const prefix = prefix_for_source(source);\n return `[CONVEX ${prefix}(${udfPath})] ${result.errorMessage}\n Called by client`;\n}\nexport function forwardData(result, error) {\n error.data = result.errorData;\n return error;\n}\n//# sourceMappingURL=logging.js.map\n","\"use strict\";\nimport { convexToJson } from \"../../values/index.js\";\nexport function canonicalizeUdfPath(udfPath) {\n const pieces = udfPath.split(\":\");\n let moduleName;\n let functionName;\n if (pieces.length === 1) {\n moduleName = pieces[0];\n functionName = \"default\";\n } else {\n moduleName = pieces.slice(0, pieces.length - 1).join(\":\");\n functionName = pieces[pieces.length - 1];\n }\n if (moduleName.endsWith(\".js\")) {\n moduleName = moduleName.slice(0, -3);\n }\n return `${moduleName}:${functionName}`;\n}\nexport function serializePathAndArgs(udfPath, args) {\n return JSON.stringify({\n udfPath: canonicalizeUdfPath(udfPath),\n args: convexToJson(args)\n });\n}\nexport function serializePaginatedPathAndArgs(udfPath, args, options) {\n const { initialNumItems, id } = options;\n const result = JSON.stringify({\n type: \"paginated\",\n udfPath: canonicalizeUdfPath(udfPath),\n args: convexToJson(args),\n options: convexToJson({ initialNumItems, id })\n });\n return result;\n}\nexport function serializedQueryTokenIsPaginated(token) {\n return JSON.parse(token).type === \"paginated\";\n}\n//# sourceMappingURL=udf_path_utils.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexToJson } from \"../../values/index.js\";\nimport {\n canonicalizeUdfPath,\n serializePathAndArgs\n} from \"./udf_path_utils.js\";\nexport class LocalSyncState {\n constructor() {\n __publicField(this, \"nextQueryId\");\n __publicField(this, \"querySetVersion\");\n __publicField(this, \"querySet\");\n __publicField(this, \"queryIdToToken\");\n __publicField(this, \"identityVersion\");\n __publicField(this, \"auth\");\n __publicField(this, \"outstandingQueriesOlderThanRestart\");\n __publicField(this, \"outstandingAuthOlderThanRestart\");\n __publicField(this, \"paused\");\n __publicField(this, \"pendingQuerySetModifications\");\n this.nextQueryId = 0;\n this.querySetVersion = 0;\n this.identityVersion = 0;\n this.querySet = /* @__PURE__ */ new Map();\n this.queryIdToToken = /* @__PURE__ */ new Map();\n this.outstandingQueriesOlderThanRestart = /* @__PURE__ */ new Set();\n this.outstandingAuthOlderThanRestart = false;\n this.paused = false;\n this.pendingQuerySetModifications = /* @__PURE__ */ new Map();\n }\n hasSyncedPastLastReconnect() {\n return this.outstandingQueriesOlderThanRestart.size === 0 && !this.outstandingAuthOlderThanRestart;\n }\n markAuthCompletion() {\n this.outstandingAuthOlderThanRestart = false;\n }\n subscribe(udfPath, args, journal, componentPath) {\n const canonicalizedUdfPath = canonicalizeUdfPath(udfPath);\n const queryToken = serializePathAndArgs(canonicalizedUdfPath, args);\n const existingEntry = this.querySet.get(queryToken);\n if (existingEntry !== void 0) {\n existingEntry.numSubscribers += 1;\n return {\n queryToken,\n modification: null,\n unsubscribe: () => this.removeSubscriber(queryToken)\n };\n } else {\n const queryId = this.nextQueryId++;\n const query = {\n id: queryId,\n canonicalizedUdfPath,\n args,\n numSubscribers: 1,\n journal,\n componentPath\n };\n this.querySet.set(queryToken, query);\n this.queryIdToToken.set(queryId, queryToken);\n const baseVersion = this.querySetVersion;\n const newVersion = this.querySetVersion + 1;\n const add = {\n type: \"Add\",\n queryId,\n udfPath: canonicalizedUdfPath,\n args: [convexToJson(args)],\n journal,\n componentPath\n };\n if (this.paused) {\n this.pendingQuerySetModifications.set(queryId, add);\n } else {\n this.querySetVersion = newVersion;\n }\n const modification = {\n type: \"ModifyQuerySet\",\n baseVersion,\n newVersion,\n modifications: [add]\n };\n return {\n queryToken,\n modification,\n unsubscribe: () => this.removeSubscriber(queryToken)\n };\n }\n }\n transition(transition) {\n for (const modification of transition.modifications) {\n switch (modification.type) {\n case \"QueryUpdated\":\n case \"QueryFailed\": {\n this.outstandingQueriesOlderThanRestart.delete(modification.queryId);\n const journal = modification.journal;\n if (journal !== void 0) {\n const queryToken = this.queryIdToToken.get(modification.queryId);\n if (queryToken !== void 0) {\n this.querySet.get(queryToken).journal = journal;\n }\n }\n break;\n }\n case \"QueryRemoved\": {\n this.outstandingQueriesOlderThanRestart.delete(modification.queryId);\n break;\n }\n default: {\n modification;\n throw new Error(`Invalid modification ${modification.type}`);\n }\n }\n }\n }\n queryId(udfPath, args) {\n const canonicalizedUdfPath = canonicalizeUdfPath(udfPath);\n const queryToken = serializePathAndArgs(canonicalizedUdfPath, args);\n const existingEntry = this.querySet.get(queryToken);\n if (existingEntry !== void 0) {\n return existingEntry.id;\n }\n return null;\n }\n isCurrentOrNewerAuthVersion(version) {\n return version >= this.identityVersion;\n }\n getAuth() {\n return this.auth;\n }\n setAuth(value) {\n this.auth = {\n tokenType: \"User\",\n value\n };\n const baseVersion = this.identityVersion;\n if (!this.paused) {\n this.identityVersion = baseVersion + 1;\n }\n return {\n type: \"Authenticate\",\n baseVersion,\n ...this.auth\n };\n }\n setAdminAuth(value, actingAs) {\n const auth = {\n tokenType: \"Admin\",\n value,\n impersonating: actingAs\n };\n this.auth = auth;\n const baseVersion = this.identityVersion;\n if (!this.paused) {\n this.identityVersion = baseVersion + 1;\n }\n return {\n type: \"Authenticate\",\n baseVersion,\n ...auth\n };\n }\n clearAuth() {\n this.auth = void 0;\n this.markAuthCompletion();\n const baseVersion = this.identityVersion;\n if (!this.paused) {\n this.identityVersion = baseVersion + 1;\n }\n return {\n type: \"Authenticate\",\n tokenType: \"None\",\n baseVersion\n };\n }\n hasAuth() {\n return !!this.auth;\n }\n isNewAuth(value) {\n return this.auth?.value !== value;\n }\n queryPath(queryId) {\n const pathAndArgs = this.queryIdToToken.get(queryId);\n if (pathAndArgs) {\n return this.querySet.get(pathAndArgs).canonicalizedUdfPath;\n }\n return null;\n }\n queryArgs(queryId) {\n const pathAndArgs = this.queryIdToToken.get(queryId);\n if (pathAndArgs) {\n return this.querySet.get(pathAndArgs).args;\n }\n return null;\n }\n queryToken(queryId) {\n return this.queryIdToToken.get(queryId) ?? null;\n }\n queryJournal(queryToken) {\n return this.querySet.get(queryToken)?.journal;\n }\n restart() {\n this.unpause();\n this.outstandingQueriesOlderThanRestart.clear();\n const modifications = [];\n for (const localQuery of this.querySet.values()) {\n const add = {\n type: \"Add\",\n queryId: localQuery.id,\n udfPath: localQuery.canonicalizedUdfPath,\n args: [convexToJson(localQuery.args)],\n journal: localQuery.journal,\n componentPath: localQuery.componentPath\n };\n modifications.push(add);\n this.outstandingQueriesOlderThanRestart.add(localQuery.id);\n }\n this.querySetVersion = 1;\n const querySet = {\n type: \"ModifyQuerySet\",\n baseVersion: 0,\n newVersion: 1,\n modifications\n };\n if (!this.auth) {\n this.identityVersion = 0;\n return [querySet, void 0];\n }\n this.outstandingAuthOlderThanRestart = true;\n const authenticate = {\n type: \"Authenticate\",\n baseVersion: 0,\n ...this.auth\n };\n this.identityVersion = 1;\n return [querySet, authenticate];\n }\n pause() {\n this.paused = true;\n }\n resume() {\n const querySet = this.pendingQuerySetModifications.size > 0 ? {\n type: \"ModifyQuerySet\",\n baseVersion: this.querySetVersion,\n newVersion: ++this.querySetVersion,\n modifications: Array.from(\n this.pendingQuerySetModifications.values()\n )\n } : void 0;\n const authenticate = this.auth !== void 0 ? {\n type: \"Authenticate\",\n baseVersion: this.identityVersion++,\n ...this.auth\n } : void 0;\n this.unpause();\n return [querySet, authenticate];\n }\n unpause() {\n this.paused = false;\n this.pendingQuerySetModifications.clear();\n }\n removeSubscriber(queryToken) {\n const localQuery = this.querySet.get(queryToken);\n if (localQuery.numSubscribers > 1) {\n localQuery.numSubscribers -= 1;\n return null;\n } else {\n this.querySet.delete(queryToken);\n this.queryIdToToken.delete(localQuery.id);\n this.outstandingQueriesOlderThanRestart.delete(localQuery.id);\n const baseVersion = this.querySetVersion;\n const newVersion = this.querySetVersion + 1;\n const remove = {\n type: \"Remove\",\n queryId: localQuery.id\n };\n if (this.paused) {\n if (this.pendingQuerySetModifications.has(localQuery.id)) {\n this.pendingQuerySetModifications.delete(localQuery.id);\n } else {\n this.pendingQuerySetModifications.set(localQuery.id, remove);\n }\n } else {\n this.querySetVersion = newVersion;\n }\n return {\n type: \"ModifyQuerySet\",\n baseVersion,\n newVersion,\n modifications: [remove]\n };\n }\n }\n}\n//# sourceMappingURL=local_state.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jsonToConvex } from \"../../values/index.js\";\nimport { logForFunction } from \"../logging.js\";\nexport class RequestManager {\n constructor(logger, markConnectionStateDirty) {\n this.logger = logger;\n this.markConnectionStateDirty = markConnectionStateDirty;\n __publicField(this, \"inflightRequests\");\n __publicField(this, \"requestsOlderThanRestart\");\n __publicField(this, \"inflightMutationsCount\", 0);\n __publicField(this, \"inflightActionsCount\", 0);\n this.inflightRequests = /* @__PURE__ */ new Map();\n this.requestsOlderThanRestart = /* @__PURE__ */ new Set();\n }\n request(message, sent) {\n const result = new Promise((resolve) => {\n const status = sent ? \"Requested\" : \"NotSent\";\n this.inflightRequests.set(message.requestId, {\n message,\n status: { status, requestedAt: /* @__PURE__ */ new Date(), onResult: resolve }\n });\n if (message.type === \"Mutation\") {\n this.inflightMutationsCount++;\n } else if (message.type === \"Action\") {\n this.inflightActionsCount++;\n }\n });\n this.markConnectionStateDirty();\n return result;\n }\n /**\n * Update the state after receiving a response.\n *\n * @returns A RequestId if the request is complete and its optimistic update\n * can be dropped, null otherwise.\n */\n onResponse(response) {\n const requestInfo = this.inflightRequests.get(response.requestId);\n if (requestInfo === void 0) {\n return null;\n }\n if (requestInfo.status.status === \"Completed\") {\n return null;\n }\n const udfType = requestInfo.message.type === \"Mutation\" ? \"mutation\" : \"action\";\n const udfPath = requestInfo.message.udfPath;\n for (const line of response.logLines) {\n logForFunction(this.logger, \"info\", udfType, udfPath, line);\n }\n const status = requestInfo.status;\n let result;\n let onResolve;\n if (response.success) {\n result = {\n success: true,\n logLines: response.logLines,\n value: jsonToConvex(response.result)\n };\n onResolve = () => status.onResult(result);\n } else {\n const errorMessage = response.result;\n const { errorData } = response;\n logForFunction(this.logger, \"error\", udfType, udfPath, errorMessage);\n result = {\n success: false,\n errorMessage,\n errorData: errorData !== void 0 ? jsonToConvex(errorData) : void 0,\n logLines: response.logLines\n };\n onResolve = () => status.onResult(result);\n }\n if (response.type === \"ActionResponse\" || !response.success) {\n onResolve();\n this.inflightRequests.delete(response.requestId);\n this.requestsOlderThanRestart.delete(response.requestId);\n if (requestInfo.message.type === \"Action\") {\n this.inflightActionsCount--;\n } else if (requestInfo.message.type === \"Mutation\") {\n this.inflightMutationsCount--;\n }\n this.markConnectionStateDirty();\n return { requestId: response.requestId, result };\n }\n requestInfo.status = {\n status: \"Completed\",\n result,\n ts: response.ts,\n onResolve\n };\n return null;\n }\n // Remove and returns completed requests.\n removeCompleted(ts) {\n const completeRequests = /* @__PURE__ */ new Map();\n for (const [requestId, requestInfo] of this.inflightRequests.entries()) {\n const status = requestInfo.status;\n if (status.status === \"Completed\" && status.ts.lessThanOrEqual(ts)) {\n status.onResolve();\n completeRequests.set(requestId, status.result);\n if (requestInfo.message.type === \"Mutation\") {\n this.inflightMutationsCount--;\n } else if (requestInfo.message.type === \"Action\") {\n this.inflightActionsCount--;\n }\n this.inflightRequests.delete(requestId);\n this.requestsOlderThanRestart.delete(requestId);\n }\n }\n if (completeRequests.size > 0) {\n this.markConnectionStateDirty();\n }\n return completeRequests;\n }\n restart() {\n this.requestsOlderThanRestart = new Set(this.inflightRequests.keys());\n const allMessages = [];\n for (const [requestId, value] of this.inflightRequests) {\n if (value.status.status === \"NotSent\") {\n value.status.status = \"Requested\";\n allMessages.push(value.message);\n continue;\n }\n if (value.message.type === \"Mutation\") {\n allMessages.push(value.message);\n } else if (value.message.type === \"Action\") {\n this.inflightRequests.delete(requestId);\n this.requestsOlderThanRestart.delete(requestId);\n this.inflightActionsCount--;\n if (value.status.status === \"Completed\") {\n throw new Error(\"Action should never be in 'Completed' state\");\n }\n value.status.onResult({\n success: false,\n errorMessage: \"Connection lost while action was in flight\",\n logLines: []\n });\n }\n }\n this.markConnectionStateDirty();\n return allMessages;\n }\n resume() {\n const allMessages = [];\n for (const [, value] of this.inflightRequests) {\n if (value.status.status === \"NotSent\") {\n value.status.status = \"Requested\";\n allMessages.push(value.message);\n continue;\n }\n }\n return allMessages;\n }\n /**\n * @returns true if there are any requests that have been requested but have\n * not be completed yet.\n */\n hasIncompleteRequests() {\n for (const requestInfo of this.inflightRequests.values()) {\n if (requestInfo.status.status === \"Requested\") {\n return true;\n }\n }\n return false;\n }\n /**\n * @returns true if there are any inflight requests, including ones that have\n * completed on the server, but have not been applied.\n */\n hasInflightRequests() {\n return this.inflightRequests.size > 0;\n }\n /**\n * @returns true if there are any inflight requests, that have been hanging around\n * since prior to the most recent restart.\n */\n hasSyncedPastLastReconnect() {\n return this.requestsOlderThanRestart.size === 0;\n }\n timeOfOldestInflightRequest() {\n if (this.inflightRequests.size === 0) {\n return null;\n }\n let oldestInflightRequest = Date.now();\n for (const request of this.inflightRequests.values()) {\n if (request.status.status !== \"Completed\") {\n if (request.status.requestedAt.getTime() < oldestInflightRequest) {\n oldestInflightRequest = request.status.requestedAt.getTime();\n }\n }\n }\n return new Date(oldestInflightRequest);\n }\n /**\n * @returns The number of mutations currently in flight.\n */\n inflightMutations() {\n return this.inflightMutationsCount;\n }\n /**\n * @returns The number of actions currently in flight.\n */\n inflightActions() {\n return this.inflightActionsCount;\n }\n}\n//# sourceMappingURL=request_manager.js.map\n","\"use strict\";\nexport const functionName = Symbol.for(\"functionName\");\n//# sourceMappingURL=functionName.js.map\n","\"use strict\";\nimport { functionName } from \"../functionName.js\";\nexport const toReferencePath = Symbol.for(\"toReferencePath\");\nexport function setReferencePath(obj, value) {\n obj[toReferencePath] = value;\n}\nexport function extractReferencePath(reference) {\n return reference[toReferencePath] ?? null;\n}\nexport function isFunctionHandle(s) {\n return s.startsWith(\"function://\");\n}\nexport function getFunctionAddress(functionReference) {\n let functionAddress;\n if (typeof functionReference === \"string\") {\n if (isFunctionHandle(functionReference)) {\n functionAddress = { functionHandle: functionReference };\n } else {\n functionAddress = { name: functionReference };\n }\n } else if (functionReference[functionName]) {\n functionAddress = { name: functionReference[functionName] };\n } else {\n const referencePath = extractReferencePath(functionReference);\n if (!referencePath) {\n throw new Error(`${functionReference} is not a functionReference`);\n }\n functionAddress = { reference: referencePath };\n }\n return functionAddress;\n}\n//# sourceMappingURL=paths.js.map\n","\"use strict\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\nexport function getFunctionName(functionReference) {\n const address = getFunctionAddress(functionReference);\n if (address.name === void 0) {\n if (address.functionHandle !== void 0) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`\n );\n } else if (address.reference !== void 0) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`\n );\n }\n if (typeof functionReference === \"string\") return functionReference;\n const name = functionReference[functionName];\n if (!name) {\n throw new Error(`${functionReference} is not a functionReference`);\n }\n return name;\n}\nexport function makeFunctionReference(name) {\n return { [functionName]: name };\n}\nfunction createApi(pathParts = []) {\n const handler = {\n get(_, prop) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return void 0;\n }\n }\n };\n return new Proxy({}, handler);\n}\nexport function filterApi(api) {\n return api;\n}\nexport function justInternal(api) {\n return api;\n}\nexport function justPublic(api) {\n return api;\n}\nexport function justQueries(api) {\n return api;\n}\nexport function justMutations(api) {\n return api;\n}\nexport function justActions(api) {\n return api;\n}\nexport function justPaginatedQueries(api) {\n return api;\n}\nexport function justSchedulable(api) {\n return api;\n}\nexport const anyApi = createApi();\n//# sourceMappingURL=api.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n getFunctionName\n} from \"../../server/api.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { createHybridErrorStacktrace, forwardData } from \"../logging.js\";\nimport {\n canonicalizeUdfPath,\n serializePathAndArgs\n} from \"./udf_path_utils.js\";\nimport { ConvexError } from \"../../values/errors.js\";\nclass OptimisticLocalStoreImpl {\n constructor(queryResults) {\n // A references of the query results in OptimisticQueryResults\n __publicField(this, \"queryResults\");\n // All of the queries modified by this class\n __publicField(this, \"modifiedQueries\");\n this.queryResults = queryResults;\n this.modifiedQueries = [];\n }\n getQuery(query, ...args) {\n const queryArgs = parseArgs(args[0]);\n const name = getFunctionName(query);\n const queryResult = this.queryResults.get(\n serializePathAndArgs(name, queryArgs)\n );\n if (queryResult === void 0) {\n return void 0;\n }\n return OptimisticLocalStoreImpl.queryValue(queryResult.result);\n }\n getAllQueries(query) {\n const queriesWithName = [];\n const name = getFunctionName(query);\n for (const queryResult of this.queryResults.values()) {\n if (queryResult.udfPath === canonicalizeUdfPath(name)) {\n queriesWithName.push({\n args: queryResult.args,\n value: OptimisticLocalStoreImpl.queryValue(queryResult.result)\n });\n }\n }\n return queriesWithName;\n }\n setQuery(queryReference, args, value) {\n const queryArgs = parseArgs(args);\n const name = getFunctionName(queryReference);\n const queryToken = serializePathAndArgs(name, queryArgs);\n let result;\n if (value === void 0) {\n result = void 0;\n } else {\n result = {\n success: true,\n value,\n // It's an optimistic update, so there are no function logs to show.\n logLines: []\n };\n }\n const query = {\n udfPath: name,\n args: queryArgs,\n result\n };\n this.queryResults.set(queryToken, query);\n this.modifiedQueries.push(queryToken);\n }\n static queryValue(result) {\n if (result === void 0) {\n return void 0;\n } else if (result.success) {\n return result.value;\n } else {\n return void 0;\n }\n }\n}\nexport class OptimisticQueryResults {\n constructor() {\n __publicField(this, \"queryResults\");\n __publicField(this, \"optimisticUpdates\");\n this.queryResults = /* @__PURE__ */ new Map();\n this.optimisticUpdates = [];\n }\n /**\n * Apply all optimistic updates on top of server query results\n */\n ingestQueryResultsFromServer(serverQueryResults, optimisticUpdatesToDrop) {\n this.optimisticUpdates = this.optimisticUpdates.filter((updateAndId) => {\n return !optimisticUpdatesToDrop.has(updateAndId.mutationId);\n });\n const oldQueryResults = this.queryResults;\n this.queryResults = new Map(serverQueryResults);\n const localStore = new OptimisticLocalStoreImpl(this.queryResults);\n for (const updateAndId of this.optimisticUpdates) {\n updateAndId.update(localStore);\n }\n const changedQueries = [];\n for (const [queryToken, query] of this.queryResults) {\n const oldQuery = oldQueryResults.get(queryToken);\n if (oldQuery === void 0 || oldQuery.result !== query.result) {\n changedQueries.push(queryToken);\n }\n }\n return changedQueries;\n }\n applyOptimisticUpdate(update, mutationId) {\n this.optimisticUpdates.push({\n update,\n mutationId\n });\n const localStore = new OptimisticLocalStoreImpl(this.queryResults);\n update(localStore);\n return localStore.modifiedQueries;\n }\n /**\n * \"Raw\" with respect to errors vs values, but query results still have\n * optimistic updates applied.\n *\n * @internal\n */\n rawQueryResult(queryToken) {\n const query = this.queryResults.get(queryToken);\n if (query === void 0) {\n return void 0;\n }\n return query.result;\n }\n queryResult(queryToken) {\n const query = this.queryResults.get(queryToken);\n if (query === void 0) {\n return void 0;\n }\n const result = query.result;\n if (result === void 0) {\n return void 0;\n } else if (result.success) {\n return result.value;\n } else {\n if (result.errorData !== void 0) {\n throw forwardData(\n result,\n new ConvexError(\n createHybridErrorStacktrace(\"query\", query.udfPath, result)\n )\n );\n }\n throw new Error(\n createHybridErrorStacktrace(\"query\", query.udfPath, result)\n );\n }\n }\n hasQueryResult(queryToken) {\n return this.queryResults.get(queryToken) !== void 0;\n }\n /**\n * @internal\n */\n queryLogs(queryToken) {\n const query = this.queryResults.get(queryToken);\n return query?.result?.logLines;\n }\n}\n//# sourceMappingURL=optimistic_updates_impl.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nexport class Long {\n constructor(low, high) {\n __publicField(this, \"low\");\n __publicField(this, \"high\");\n __publicField(this, \"__isUnsignedLong__\");\n this.low = low | 0;\n this.high = high | 0;\n this.__isUnsignedLong__ = true;\n }\n static isLong(obj) {\n return (obj && obj.__isUnsignedLong__) === true;\n }\n // prettier-ignore\n static fromBytesLE(bytes) {\n return new Long(\n bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24,\n bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24\n );\n }\n // prettier-ignore\n toBytesLE() {\n const hi = this.high;\n const lo = this.low;\n return [\n lo & 255,\n lo >>> 8 & 255,\n lo >>> 16 & 255,\n lo >>> 24,\n hi & 255,\n hi >>> 8 & 255,\n hi >>> 16 & 255,\n hi >>> 24\n ];\n }\n static fromNumber(value) {\n if (isNaN(value)) return UZERO;\n if (value < 0) return UZERO;\n if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;\n return new Long(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0);\n }\n toString() {\n return (BigInt(this.high) * BigInt(TWO_PWR_32_DBL) + BigInt(this.low)).toString();\n }\n equals(other) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;\n return this.high === other.high && this.low === other.low;\n }\n notEquals(other) {\n return !this.equals(other);\n }\n comp(other) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.equals(other)) return 0;\n return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;\n }\n lessThanOrEqual(other) {\n return this.comp(\n /* validates */\n other\n ) <= 0;\n }\n static fromValue(val) {\n if (typeof val === \"number\") return Long.fromNumber(val);\n return new Long(val.low, val.high);\n }\n}\nconst UZERO = new Long(0, 0);\nconst TWO_PWR_16_DBL = 1 << 16;\nconst TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\nconst TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\nconst MAX_UNSIGNED_VALUE = new Long(4294967295 | 0, 4294967295 | 0);\n//# sourceMappingURL=long.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jsonToConvex } from \"../../values/index.js\";\nimport { Long } from \"../../vendor/long.js\";\nimport { logForFunction } from \"../logging.js\";\nexport class RemoteQuerySet {\n constructor(queryPath, logger) {\n __publicField(this, \"version\");\n __publicField(this, \"remoteQuerySet\");\n __publicField(this, \"queryPath\");\n __publicField(this, \"logger\");\n this.version = { querySet: 0, ts: Long.fromNumber(0), identity: 0 };\n this.remoteQuerySet = /* @__PURE__ */ new Map();\n this.queryPath = queryPath;\n this.logger = logger;\n }\n transition(transition) {\n const start = transition.startVersion;\n if (this.version.querySet !== start.querySet || this.version.ts.notEquals(start.ts) || this.version.identity !== start.identity) {\n throw new Error(\n `Invalid start version: ${start.ts.toString()}:${start.querySet}:${start.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`\n );\n }\n for (const modification of transition.modifications) {\n switch (modification.type) {\n case \"QueryUpdated\": {\n const queryPath = this.queryPath(modification.queryId);\n if (queryPath) {\n for (const line of modification.logLines) {\n logForFunction(this.logger, \"info\", \"query\", queryPath, line);\n }\n }\n const value = jsonToConvex(modification.value ?? null);\n this.remoteQuerySet.set(modification.queryId, {\n success: true,\n value,\n logLines: modification.logLines\n });\n break;\n }\n case \"QueryFailed\": {\n const queryPath = this.queryPath(modification.queryId);\n if (queryPath) {\n for (const line of modification.logLines) {\n logForFunction(this.logger, \"info\", \"query\", queryPath, line);\n }\n }\n const { errorData } = modification;\n this.remoteQuerySet.set(modification.queryId, {\n success: false,\n errorMessage: modification.errorMessage,\n errorData: errorData !== void 0 ? jsonToConvex(errorData) : void 0,\n logLines: modification.logLines\n });\n break;\n }\n case \"QueryRemoved\": {\n this.remoteQuerySet.delete(modification.queryId);\n break;\n }\n default: {\n modification;\n throw new Error(`Invalid modification ${modification.type}`);\n }\n }\n }\n this.version = transition.endVersion;\n }\n remoteQueryResults() {\n return this.remoteQuerySet;\n }\n timestamp() {\n return this.version.ts;\n }\n}\n//# sourceMappingURL=remote_query_set.js.map\n","\"use strict\";\nimport { Base64 } from \"../../values/index.js\";\nimport { Long } from \"../../vendor/long.js\";\nexport function u64ToLong(encoded) {\n const integerBytes = Base64.toByteArray(encoded);\n return Long.fromBytesLE(Array.from(integerBytes));\n}\nexport function longToU64(raw) {\n const integerBytes = new Uint8Array(raw.toBytesLE());\n return Base64.fromByteArray(integerBytes);\n}\nexport function parseServerMessage(encoded) {\n switch (encoded.type) {\n case \"FatalError\":\n case \"AuthError\":\n case \"ActionResponse\":\n case \"TransitionChunk\":\n case \"Ping\": {\n return { ...encoded };\n }\n case \"MutationResponse\": {\n if (encoded.success) {\n return { ...encoded, ts: u64ToLong(encoded.ts) };\n } else {\n return { ...encoded };\n }\n }\n case \"Transition\": {\n return {\n ...encoded,\n startVersion: {\n ...encoded.startVersion,\n ts: u64ToLong(encoded.startVersion.ts)\n },\n endVersion: {\n ...encoded.endVersion,\n ts: u64ToLong(encoded.endVersion.ts)\n }\n };\n }\n default: {\n encoded;\n }\n }\n return void 0;\n}\nexport function encodeClientMessage(message) {\n switch (message.type) {\n case \"Authenticate\":\n case \"ModifyQuerySet\":\n case \"Mutation\":\n case \"Action\":\n case \"Event\": {\n return { ...message };\n }\n case \"Connect\": {\n if (message.maxObservedTimestamp !== void 0) {\n return {\n ...message,\n maxObservedTimestamp: longToU64(message.maxObservedTimestamp)\n };\n } else {\n return { ...message, maxObservedTimestamp: void 0 };\n }\n }\n default: {\n message;\n }\n }\n return void 0;\n}\n//# sourceMappingURL=protocol.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n encodeClientMessage,\n parseServerMessage\n} from \"./protocol.js\";\nconst CLOSE_NORMAL = 1e3;\nconst CLOSE_GOING_AWAY = 1001;\nconst CLOSE_NO_STATUS = 1005;\nconst CLOSE_NOT_FOUND = 4040;\nlet firstTime;\nfunction monotonicMillis() {\n if (firstTime === void 0) {\n firstTime = Date.now();\n }\n if (typeof performance === \"undefined\" || !performance.now) {\n return Date.now();\n }\n return Math.round(firstTime + performance.now());\n}\nfunction prettyNow() {\n return `t=${Math.round((monotonicMillis() - firstTime) / 100) / 10}s`;\n}\nconst serverDisconnectErrors = {\n // A known error, e.g. during a restart or push\n InternalServerError: { timeout: 1e3 },\n // ErrorMetadata::overloaded() messages that we realy should back off\n SubscriptionsWorkerFullError: { timeout: 3e3 },\n TooManyConcurrentRequests: { timeout: 3e3 },\n CommitterFullError: { timeout: 3e3 },\n AwsTooManyRequestsException: { timeout: 3e3 },\n ExecuteFullError: { timeout: 3e3 },\n SystemTimeoutError: { timeout: 3e3 },\n ExpiredInQueue: { timeout: 3e3 },\n // ErrorMetadata::feature_temporarily_unavailable() that typically indicate a deploy just happened\n VectorIndexesUnavailable: { timeout: 1e3 },\n SearchIndexesUnavailable: { timeout: 1e3 },\n TableSummariesUnavailable: { timeout: 1e3 },\n // More ErrorMetadata::overloaded()\n VectorIndexTooLarge: { timeout: 3e3 },\n SearchIndexTooLarge: { timeout: 3e3 },\n TooManyWritesInTimePeriod: { timeout: 3e3 }\n};\nfunction classifyDisconnectError(s) {\n if (s === void 0) return \"Unknown\";\n for (const prefix of Object.keys(\n serverDisconnectErrors\n )) {\n if (s.startsWith(prefix)) {\n return prefix;\n }\n }\n return \"Unknown\";\n}\nexport class WebSocketManager {\n constructor(uri, callbacks, webSocketConstructor, logger, markConnectionStateDirty, debug) {\n this.markConnectionStateDirty = markConnectionStateDirty;\n this.debug = debug;\n __publicField(this, \"socket\");\n __publicField(this, \"connectionCount\");\n __publicField(this, \"_hasEverConnected\", false);\n __publicField(this, \"lastCloseReason\");\n // State for assembling the split-up Transition currently being received.\n __publicField(this, \"transitionChunkBuffer\", null);\n /** Upon HTTPS/WSS failure, the first jittered backoff duration, in ms. */\n __publicField(this, \"defaultInitialBackoff\");\n /** We backoff exponentially, but we need to cap that--this is the jittered max. */\n __publicField(this, \"maxBackoff\");\n /** How many times have we failed consecutively? */\n __publicField(this, \"retries\");\n /** How long before lack of server response causes us to initiate a reconnect,\n * in ms */\n __publicField(this, \"serverInactivityThreshold\");\n __publicField(this, \"reconnectDueToServerInactivityTimeout\");\n /** Scheduled reconnect state: timeout handle and timing info */\n __publicField(this, \"scheduledReconnect\", null);\n __publicField(this, \"networkOnlineHandler\", null);\n /** Pending event to send after reconnecting due to network recovery */\n __publicField(this, \"pendingNetworkRecoveryInfo\", null);\n __publicField(this, \"uri\");\n __publicField(this, \"onOpen\");\n __publicField(this, \"onResume\");\n __publicField(this, \"onMessage\");\n __publicField(this, \"webSocketConstructor\");\n __publicField(this, \"logger\");\n __publicField(this, \"onServerDisconnectError\");\n this.webSocketConstructor = webSocketConstructor;\n this.socket = { state: \"disconnected\" };\n this.connectionCount = 0;\n this.lastCloseReason = \"InitialConnect\";\n this.defaultInitialBackoff = 1e3;\n this.maxBackoff = 16e3;\n this.retries = 0;\n this.serverInactivityThreshold = 6e4;\n this.reconnectDueToServerInactivityTimeout = null;\n this.uri = uri;\n this.onOpen = callbacks.onOpen;\n this.onResume = callbacks.onResume;\n this.onMessage = callbacks.onMessage;\n this.onServerDisconnectError = callbacks.onServerDisconnectError;\n this.logger = logger;\n this.setupNetworkListener();\n this.connect();\n }\n setSocketState(state) {\n this.socket = state;\n this._logVerbose(\n `socket state changed: ${this.socket.state}, paused: ${\"paused\" in this.socket ? this.socket.paused : void 0}`\n );\n this.markConnectionStateDirty();\n }\n setupNetworkListener() {\n if (typeof window === \"undefined\" || typeof window.addEventListener !== \"function\") {\n return;\n }\n if (this.networkOnlineHandler !== null) {\n return;\n }\n this.networkOnlineHandler = () => {\n this._logVerbose(\"network online event detected\");\n this.tryReconnectImmediately();\n };\n window.addEventListener(\"online\", this.networkOnlineHandler);\n this._logVerbose(\"network online event listener registered\");\n }\n cleanupNetworkListener() {\n if (this.networkOnlineHandler && typeof window !== \"undefined\" && typeof window.removeEventListener === \"function\") {\n window.removeEventListener(\"online\", this.networkOnlineHandler);\n this.networkOnlineHandler = null;\n this._logVerbose(\"network online event listener removed\");\n }\n }\n assembleTransition(chunk) {\n if (chunk.partNumber < 0 || chunk.partNumber >= chunk.totalParts || chunk.totalParts === 0 || this.transitionChunkBuffer && (this.transitionChunkBuffer.totalParts !== chunk.totalParts || this.transitionChunkBuffer.transitionId !== chunk.transitionId)) {\n this.transitionChunkBuffer = null;\n throw new Error(\"Invalid TransitionChunk\");\n }\n if (this.transitionChunkBuffer === null) {\n this.transitionChunkBuffer = {\n chunks: [],\n totalParts: chunk.totalParts,\n transitionId: chunk.transitionId\n };\n }\n if (chunk.partNumber !== this.transitionChunkBuffer.chunks.length) {\n const expectedLength = this.transitionChunkBuffer.chunks.length;\n this.transitionChunkBuffer = null;\n throw new Error(\n `TransitionChunk received out of order: expected part ${expectedLength}, got ${chunk.partNumber}`\n );\n }\n this.transitionChunkBuffer.chunks.push(chunk.chunk);\n if (this.transitionChunkBuffer.chunks.length === chunk.totalParts) {\n const fullJson = this.transitionChunkBuffer.chunks.join(\"\");\n this.transitionChunkBuffer = null;\n const transition = parseServerMessage(JSON.parse(fullJson));\n if (transition.type !== \"Transition\") {\n throw new Error(\n `Expected Transition, got ${transition.type} after assembling chunks`\n );\n }\n return transition;\n }\n return null;\n }\n connect() {\n if (this.socket.state === \"terminated\") {\n return;\n }\n if (this.socket.state !== \"disconnected\" && this.socket.state !== \"stopped\") {\n throw new Error(\n \"Didn't start connection from disconnected state: \" + this.socket.state\n );\n }\n const ws = new this.webSocketConstructor(this.uri);\n this._logVerbose(\"constructed WebSocket\");\n this.setSocketState({\n state: \"connecting\",\n ws,\n paused: \"no\"\n });\n this.resetServerInactivityTimeout();\n ws.onopen = () => {\n this.logger.logVerbose(\"begin ws.onopen\");\n if (this.socket.state !== \"connecting\") {\n throw new Error(\"onopen called with socket not in connecting state\");\n }\n this.setSocketState({\n state: \"ready\",\n ws,\n paused: this.socket.paused === \"yes\" ? \"uninitialized\" : \"no\"\n });\n this.resetServerInactivityTimeout();\n if (this.socket.paused === \"no\") {\n this._hasEverConnected = true;\n this.onOpen({\n connectionCount: this.connectionCount,\n lastCloseReason: this.lastCloseReason,\n clientTs: monotonicMillis()\n });\n }\n if (this.lastCloseReason !== \"InitialConnect\") {\n if (this.lastCloseReason) {\n this.logger.log(\n \"WebSocket reconnected at\",\n prettyNow(),\n \"after disconnect due to\",\n this.lastCloseReason\n );\n } else {\n this.logger.log(\"WebSocket reconnected at\", prettyNow());\n }\n }\n this.connectionCount += 1;\n this.lastCloseReason = null;\n if (this.pendingNetworkRecoveryInfo !== null) {\n const { timeSavedMs } = this.pendingNetworkRecoveryInfo;\n this.pendingNetworkRecoveryInfo = null;\n this.sendMessage({\n type: \"Event\",\n eventType: \"NetworkRecoveryReconnect\",\n event: { timeSavedMs }\n });\n this.logger.log(\n `Network recovery reconnect saved ~${Math.round(timeSavedMs / 1e3)}s of waiting`\n );\n }\n };\n ws.onerror = (error) => {\n this.transitionChunkBuffer = null;\n const message = error.message;\n if (message) {\n this.logger.log(`WebSocket error message: ${message}`);\n }\n };\n ws.onmessage = (message) => {\n this.resetServerInactivityTimeout();\n const messageLength = message.data.length;\n let serverMessage = parseServerMessage(JSON.parse(message.data));\n this._logVerbose(`received ws message with type ${serverMessage.type}`);\n if (serverMessage.type === \"Ping\") {\n return;\n }\n if (serverMessage.type === \"TransitionChunk\") {\n const transition = this.assembleTransition(serverMessage);\n if (!transition) {\n return;\n }\n serverMessage = transition;\n this._logVerbose(\n `assembled full ws message of type ${serverMessage.type}`\n );\n }\n if (this.transitionChunkBuffer !== null) {\n this.transitionChunkBuffer = null;\n this.logger.log(\n `Received unexpected ${serverMessage.type} while buffering TransitionChunks`\n );\n }\n if (serverMessage.type === \"Transition\") {\n this.reportLargeTransition({\n messageLength,\n transition: serverMessage\n });\n }\n const response = this.onMessage(serverMessage);\n if (response.hasSyncedPastLastReconnect) {\n this.retries = 0;\n this.markConnectionStateDirty();\n }\n };\n ws.onclose = (event) => {\n this._logVerbose(\"begin ws.onclose\");\n this.transitionChunkBuffer = null;\n if (this.lastCloseReason === null) {\n this.lastCloseReason = event.reason || `closed with code ${event.code}`;\n }\n if (event.code !== CLOSE_NORMAL && event.code !== CLOSE_GOING_AWAY && // This commonly gets fired on mobile apps when the app is backgrounded\n event.code !== CLOSE_NO_STATUS && event.code !== CLOSE_NOT_FOUND) {\n let msg = `WebSocket closed with code ${event.code}`;\n if (event.reason) {\n msg += `: ${event.reason}`;\n }\n this.logger.log(msg);\n if (this.onServerDisconnectError && event.reason) {\n this.onServerDisconnectError(msg);\n }\n }\n const reason = classifyDisconnectError(event.reason);\n this.scheduleReconnect(reason);\n return;\n };\n }\n /**\n * @returns The state of the {@link Socket}.\n */\n socketState() {\n return this.socket.state;\n }\n /**\n * @param message - A ClientMessage to send.\n * @returns Whether the message (might have been) sent.\n */\n sendMessage(message) {\n const messageForLog = {\n type: message.type,\n ...message.type === \"Authenticate\" && message.tokenType === \"User\" ? {\n value: `...${message.value.slice(-7)}`\n } : {}\n };\n if (this.socket.state === \"ready\" && this.socket.paused === \"no\") {\n const encodedMessage = encodeClientMessage(message);\n const request = JSON.stringify(encodedMessage);\n let sent = false;\n try {\n this.socket.ws.send(request);\n sent = true;\n } catch (error) {\n this.logger.log(\n `Failed to send message on WebSocket, reconnecting: ${error}`\n );\n this.closeAndReconnect(\"FailedToSendMessage\");\n }\n this._logVerbose(\n `${sent ? \"sent\" : \"failed to send\"} message with type ${message.type}: ${JSON.stringify(\n messageForLog\n )}`\n );\n return true;\n }\n this._logVerbose(\n `message not sent (socket state: ${this.socket.state}, paused: ${\"paused\" in this.socket ? this.socket.paused : void 0}): ${JSON.stringify(\n messageForLog\n )}`\n );\n return false;\n }\n resetServerInactivityTimeout() {\n if (this.socket.state === \"terminated\") {\n return;\n }\n if (this.reconnectDueToServerInactivityTimeout !== null) {\n clearTimeout(this.reconnectDueToServerInactivityTimeout);\n this.reconnectDueToServerInactivityTimeout = null;\n }\n this.reconnectDueToServerInactivityTimeout = setTimeout(() => {\n this.closeAndReconnect(\"InactiveServer\");\n }, this.serverInactivityThreshold);\n }\n scheduleReconnect(reason) {\n if (this.scheduledReconnect) {\n clearTimeout(this.scheduledReconnect.timeout);\n this.scheduledReconnect = null;\n }\n this.socket = { state: \"disconnected\" };\n const backoff = this.nextBackoff(reason);\n this.markConnectionStateDirty();\n this.logger.log(`Attempting reconnect in ${Math.round(backoff)}ms`);\n const scheduledAt = monotonicMillis();\n const timeoutId = setTimeout(() => {\n if (this.scheduledReconnect?.timeout === timeoutId) {\n this.scheduledReconnect = null;\n this.connect();\n }\n }, backoff);\n this.scheduledReconnect = {\n timeout: timeoutId,\n scheduledAt,\n backoffMs: backoff\n };\n }\n /**\n * Close the WebSocket and schedule a reconnect.\n *\n * This should be used when we hit an error and would like to restart the session.\n */\n closeAndReconnect(closeReason) {\n this._logVerbose(`begin closeAndReconnect with reason ${closeReason}`);\n switch (this.socket.state) {\n case \"disconnected\":\n case \"terminated\":\n case \"stopped\":\n return;\n case \"connecting\":\n case \"ready\": {\n this.lastCloseReason = closeReason;\n void this.close();\n this.scheduleReconnect(\"client\");\n return;\n }\n default: {\n this.socket;\n }\n }\n }\n /**\n * Close the WebSocket, being careful to clear the onclose handler to avoid re-entrant\n * calls. Use this instead of directly calling `ws.close()`\n *\n * It is the callers responsibility to update the state after this method is called so that the\n * closed socket is not accessible or used again after this method is called\n */\n close() {\n this.transitionChunkBuffer = null;\n switch (this.socket.state) {\n case \"disconnected\":\n case \"terminated\":\n case \"stopped\":\n return Promise.resolve();\n case \"connecting\": {\n const ws = this.socket.ws;\n ws.onmessage = (_message) => {\n this._logVerbose(\"Ignoring message received after close\");\n };\n return new Promise((r) => {\n ws.onclose = () => {\n this._logVerbose(\"Closed after connecting\");\n r();\n };\n ws.onopen = () => {\n this._logVerbose(\"Opened after connecting\");\n ws.close();\n };\n });\n }\n case \"ready\": {\n this._logVerbose(\"ws.close called\");\n const ws = this.socket.ws;\n ws.onmessage = (_message) => {\n this._logVerbose(\"Ignoring message received after close\");\n };\n const result = new Promise((r) => {\n ws.onclose = () => {\n r();\n };\n });\n ws.close();\n return result;\n }\n default: {\n this.socket;\n return Promise.resolve();\n }\n }\n }\n /**\n * Close the WebSocket and do not reconnect.\n * @returns A Promise that resolves when the WebSocket `onClose` callback is called.\n */\n terminate() {\n if (this.reconnectDueToServerInactivityTimeout) {\n clearTimeout(this.reconnectDueToServerInactivityTimeout);\n }\n if (this.scheduledReconnect) {\n clearTimeout(this.scheduledReconnect.timeout);\n this.scheduledReconnect = null;\n }\n this.cleanupNetworkListener();\n switch (this.socket.state) {\n case \"terminated\":\n case \"stopped\":\n case \"disconnected\":\n case \"connecting\":\n case \"ready\": {\n const result = this.close();\n this.setSocketState({ state: \"terminated\" });\n return result;\n }\n default: {\n this.socket;\n throw new Error(\n `Invalid websocket state: ${this.socket.state}`\n );\n }\n }\n }\n stop() {\n switch (this.socket.state) {\n case \"terminated\":\n return Promise.resolve();\n case \"connecting\":\n case \"stopped\":\n case \"disconnected\":\n case \"ready\": {\n this.cleanupNetworkListener();\n const result = this.close();\n this.socket = { state: \"stopped\" };\n return result;\n }\n default: {\n this.socket;\n return Promise.resolve();\n }\n }\n }\n /**\n * Create a new WebSocket after a previous `stop()`, unless `terminate()` was\n * called before.\n */\n tryRestart() {\n switch (this.socket.state) {\n case \"stopped\":\n break;\n case \"terminated\":\n case \"connecting\":\n case \"ready\":\n case \"disconnected\":\n this.logger.logVerbose(\"Restart called without stopping first\");\n return;\n default: {\n this.socket;\n }\n }\n this.setupNetworkListener();\n this.connect();\n }\n pause() {\n switch (this.socket.state) {\n case \"disconnected\":\n case \"stopped\":\n case \"terminated\":\n return;\n case \"connecting\":\n case \"ready\": {\n this.socket = { ...this.socket, paused: \"yes\" };\n return;\n }\n default: {\n this.socket;\n return;\n }\n }\n }\n /**\n * Try to reconnect immediately, canceling any scheduled reconnect.\n * This is useful when detecting network recovery.\n * Only takes action if we're in disconnected state (waiting to reconnect).\n */\n tryReconnectImmediately() {\n this._logVerbose(\"tryReconnectImmediately called\");\n if (this.socket.state !== \"disconnected\") {\n this._logVerbose(\n `tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`\n );\n return;\n }\n let timeSavedMs = null;\n if (this.scheduledReconnect) {\n const elapsed = monotonicMillis() - this.scheduledReconnect.scheduledAt;\n timeSavedMs = Math.max(0, this.scheduledReconnect.backoffMs - elapsed);\n this._logVerbose(\n `would have waited ${Math.round(timeSavedMs)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(elapsed)}ms)`\n );\n clearTimeout(this.scheduledReconnect.timeout);\n this.scheduledReconnect = null;\n this._logVerbose(\"canceled scheduled reconnect\");\n }\n this.logger.log(\"Network recovery detected, reconnecting immediately\");\n this.pendingNetworkRecoveryInfo = timeSavedMs !== null ? { timeSavedMs } : null;\n this.connect();\n }\n /**\n * Resume the state machine if previously paused.\n */\n resume() {\n switch (this.socket.state) {\n case \"connecting\":\n this.socket = { ...this.socket, paused: \"no\" };\n return;\n case \"ready\":\n if (this.socket.paused === \"uninitialized\") {\n this.socket = { ...this.socket, paused: \"no\" };\n this._hasEverConnected = true;\n this.onOpen({\n connectionCount: this.connectionCount,\n lastCloseReason: this.lastCloseReason,\n clientTs: monotonicMillis()\n });\n } else if (this.socket.paused === \"yes\") {\n this.socket = { ...this.socket, paused: \"no\" };\n this.onResume();\n }\n return;\n case \"terminated\":\n case \"stopped\":\n case \"disconnected\":\n return;\n default: {\n this.socket;\n }\n }\n this.connect();\n }\n connectionState() {\n return {\n isConnected: this.socket.state === \"ready\",\n hasEverConnected: this._hasEverConnected,\n connectionCount: this.connectionCount,\n connectionRetries: this.retries\n };\n }\n _logVerbose(message) {\n this.logger.logVerbose(message);\n }\n nextBackoff(reason) {\n const initialBackoff = reason === \"client\" ? 100 : reason === \"Unknown\" ? this.defaultInitialBackoff : serverDisconnectErrors[reason].timeout;\n const baseBackoff = initialBackoff * Math.pow(2, this.retries);\n this.retries += 1;\n const actualBackoff = Math.min(baseBackoff, this.maxBackoff);\n const jitter = actualBackoff * (Math.random() - 0.5);\n return actualBackoff + jitter;\n }\n reportLargeTransition({\n transition,\n messageLength\n }) {\n if (transition.clientClockSkew === void 0 || transition.serverTs === void 0) {\n return;\n }\n const transitionTransitTime = monotonicMillis() - // client time now\n // clientClockSkew = (server time + upstream latency) - client time\n // clientClockSkew is \"how many milliseconds behind (slow) is the client clock\"\n // but the latency of the Connect message inflates this, making it appear further behind\n transition.clientClockSkew - transition.serverTs / 1e6;\n const prettyTransitionTime = `${Math.round(transitionTransitTime)}ms`;\n const prettyMessageMB = `${Math.round(messageLength / 1e4) / 100}MB`;\n const bytesPerSecond = messageLength / (transitionTransitTime / 1e3);\n const prettyBytesPerSecond = `${Math.round(bytesPerSecond / 1e4) / 100}MB per second`;\n this._logVerbose(\n `received ${prettyMessageMB} transition in ${prettyTransitionTime} at ${prettyBytesPerSecond}`\n );\n if (messageLength > 2e7) {\n this.logger.log(\n `received query results totaling more that 20MB (${prettyMessageMB}) which will take a long time to download on slower connections`\n );\n } else if (transitionTransitTime > 2e4) {\n this.logger.log(\n `received query results totaling ${prettyMessageMB} which took more than 20s to arrive (${prettyTransitionTime})`\n );\n }\n if (this.debug) {\n this.sendMessage({\n type: \"Event\",\n eventType: \"ClientReceivedTransition\",\n event: { transitionTransitTime, messageLength }\n });\n }\n }\n}\n//# sourceMappingURL=web_socket_manager.js.map\n","\"use strict\";\nexport function newSessionId() {\n return uuidv4();\n}\nfunction uuidv4() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = Math.random() * 16 | 0, v = c === \"x\" ? r : r & 3 | 8;\n return v.toString(16);\n });\n}\n//# sourceMappingURL=session.js.map\n","\"use strict\";\nexport class InvalidTokenError extends Error {\n}\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\nfunction b64DecodeUnicode(str) {\n return decodeURIComponent(\n atob(str).replace(/(.)/g, (_m, p) => {\n let code = p.charCodeAt(0).toString(16).toUpperCase();\n if (code.length < 2) {\n code = \"0\" + code;\n }\n return \"%\" + code;\n })\n );\n}\nfunction base64UrlDecode(str) {\n let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n switch (output.length % 4) {\n case 0:\n break;\n case 2:\n output += \"==\";\n break;\n case 3:\n output += \"=\";\n break;\n default:\n throw new Error(\"base64 string is not of the correct length\");\n }\n try {\n return b64DecodeUnicode(output);\n } catch {\n return atob(output);\n }\n}\nexport function jwtDecode(token, options) {\n if (typeof token !== \"string\") {\n throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n }\n options || (options = {});\n const pos = options.header === true ? 0 : 1;\n const part = token.split(\".\")[pos];\n if (typeof part !== \"string\") {\n throw new InvalidTokenError(\n `Invalid token specified: missing part #${pos + 1}`\n );\n }\n let decoded;\n try {\n decoded = base64UrlDecode(part);\n } catch (e) {\n throw new InvalidTokenError(\n `Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`\n );\n }\n try {\n return JSON.parse(decoded);\n } catch (e) {\n throw new InvalidTokenError(\n `Invalid token specified: invalid json for part #${pos + 1} (${e.message})`\n );\n }\n}\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jwtDecode } from \"../../vendor/jwt-decode/index.js\";\nconst MAXIMUM_REFRESH_DELAY = 20 * 24 * 60 * 60 * 1e3;\nconst MAX_TOKEN_CONFIRMATION_ATTEMPTS = 2;\nexport class AuthenticationManager {\n constructor(syncState, callbacks, config) {\n __publicField(this, \"authState\", { state: \"noAuth\" });\n // Used to detect races involving `setConfig` calls\n // while a token is being fetched.\n __publicField(this, \"configVersion\", 0);\n // Shared by the BaseClient so that the auth manager can easily inspect it\n __publicField(this, \"syncState\");\n // Passed down by BaseClient, sends a message to the server\n __publicField(this, \"authenticate\");\n __publicField(this, \"stopSocket\");\n __publicField(this, \"tryRestartSocket\");\n __publicField(this, \"pauseSocket\");\n __publicField(this, \"resumeSocket\");\n // Passed down by BaseClient, sends a message to the server\n __publicField(this, \"clearAuth\");\n __publicField(this, \"logger\");\n __publicField(this, \"refreshTokenLeewaySeconds\");\n // Number of times we have attempted to confirm the latest token. We retry up\n // to `MAX_TOKEN_CONFIRMATION_ATTEMPTS` times.\n __publicField(this, \"tokenConfirmationAttempts\", 0);\n this.syncState = syncState;\n this.authenticate = callbacks.authenticate;\n this.stopSocket = callbacks.stopSocket;\n this.tryRestartSocket = callbacks.tryRestartSocket;\n this.pauseSocket = callbacks.pauseSocket;\n this.resumeSocket = callbacks.resumeSocket;\n this.clearAuth = callbacks.clearAuth;\n this.logger = config.logger;\n this.refreshTokenLeewaySeconds = config.refreshTokenLeewaySeconds;\n }\n async setConfig(fetchToken, onChange) {\n this.resetAuthState();\n this._logVerbose(\"pausing WS for auth token fetch\");\n this.pauseSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(fetchToken, {\n forceRefreshToken: false\n });\n if (token.isFromOutdatedConfig) {\n return;\n }\n if (token.value) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfCachedToken\",\n config: { fetchToken, onAuthChange: onChange },\n hasRetried: false\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"initialRefetch\",\n config: { fetchToken, onAuthChange: onChange }\n });\n await this.refetchToken();\n }\n this._logVerbose(\"resuming WS after auth token fetch\");\n this.resumeSocket();\n }\n onTransition(serverMessage) {\n if (!this.syncState.isCurrentOrNewerAuthVersion(\n serverMessage.endVersion.identity\n )) {\n return;\n }\n if (serverMessage.endVersion.identity <= serverMessage.startVersion.identity) {\n return;\n }\n this._logVerbose(\n `auth state is ${this.authState.state} when handling transition`\n );\n this.syncState.markAuthCompletion();\n if (this.authState.state === \"waitingForServerConfirmationOfCachedToken\") {\n this._logVerbose(\"server confirmed auth token is valid\");\n void this.refetchToken();\n this.authState.config.onAuthChange(true);\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this._logVerbose(\"server confirmed new auth token is valid\");\n this.scheduleTokenRefetch(this.authState.token);\n this.tokenConfirmationAttempts = 0;\n if (!this.authState.hadAuth) {\n this.authState.config.onAuthChange(true);\n }\n }\n }\n onAuthError(serverMessage) {\n if (serverMessage.authUpdateAttempted === false && (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" || this.authState.state === \"waitingForServerConfirmationOfCachedToken\")) {\n this._logVerbose(\"ignoring non-auth token expired error\");\n return;\n }\n const { baseVersion } = serverMessage;\n if (!this.syncState.isCurrentOrNewerAuthVersion(baseVersion + 1)) {\n this._logVerbose(\"ignoring auth error for previous auth attempt\");\n return;\n }\n void this.tryToReauthenticate(serverMessage);\n return;\n }\n // This is similar to `refetchToken` defined below, in fact we\n // don't represent them as different states, but it is different\n // in that we pause the WebSocket so that mutations\n // don't retry with bad auth.\n async tryToReauthenticate(serverMessage) {\n this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`);\n if (\n // No way to fetch another token, kaboom\n this.authState.state === \"noAuth\" || // We failed on a fresh token. After a small number of retries, we give up\n // and clear the auth state to avoid infinite retries.\n this.authState.state === \"waitingForServerConfirmationOfFreshToken\" && this.tokenConfirmationAttempts >= MAX_TOKEN_CONFIRMATION_ATTEMPTS\n ) {\n this.logger.error(\n `Failed to authenticate: \"${serverMessage.error}\", check your server auth config`\n );\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n if (this.authState.state !== \"noAuth\") {\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this.tokenConfirmationAttempts++;\n this._logVerbose(\n `retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS - this.tokenConfirmationAttempts} attempts remaining`\n );\n }\n await this.stopSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true\n }\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n if (token.value && this.syncState.isNewAuth(token.value)) {\n this.authenticate(token.value);\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n config: this.authState.config,\n token: token.value,\n hadAuth: this.authState.state === \"notRefetching\" || this.authState.state === \"waitingForScheduledRefetch\"\n });\n } else {\n this._logVerbose(\"reauthentication failed, could not fetch a new token\");\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n this.tryRestartSocket();\n }\n // Force refetch the token and schedule another refetch\n // before the token expires - an active client should never\n // need to reauthenticate.\n async refetchToken() {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n this._logVerbose(\"refetching auth token\");\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true\n }\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n if (token.value) {\n if (this.syncState.isNewAuth(token.value)) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n hadAuth: this.syncState.hasAuth(),\n token: token.value,\n config: this.authState.config\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"notRefetching\",\n config: this.authState.config\n });\n }\n } else {\n this._logVerbose(\"refetching token failed\");\n if (this.syncState.hasAuth()) {\n this.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n this._logVerbose(\n \"restarting WS after auth token fetch (if currently stopped)\"\n );\n this.tryRestartSocket();\n }\n scheduleTokenRefetch(token) {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n const decodedToken = this.decodeToken(token);\n if (!decodedToken) {\n this.logger.error(\n \"Auth token is not a valid JWT, cannot refetch the token\"\n );\n return;\n }\n const { iat, exp } = decodedToken;\n if (!iat || !exp) {\n this.logger.error(\n \"Auth token does not have required fields, cannot refetch the token\"\n );\n return;\n }\n const tokenValiditySeconds = exp - iat;\n if (tokenValiditySeconds <= 2) {\n this.logger.error(\n \"Auth token does not live long enough, cannot refetch the token\"\n );\n return;\n }\n let delay = Math.min(\n MAXIMUM_REFRESH_DELAY,\n (tokenValiditySeconds - this.refreshTokenLeewaySeconds) * 1e3\n );\n if (delay <= 0) {\n this.logger.warn(\n `Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`\n );\n delay = 0;\n }\n const refetchTokenTimeoutId = setTimeout(() => {\n this._logVerbose(\"running scheduled token refetch\");\n void this.refetchToken();\n }, delay);\n this.setAuthState({\n state: \"waitingForScheduledRefetch\",\n refetchTokenTimeoutId,\n config: this.authState.config\n });\n this._logVerbose(\n `scheduled preemptive auth token refetching in ${delay}ms`\n );\n }\n // Protects against simultaneous calls to `setConfig`\n // while we're fetching a token\n async fetchTokenAndGuardAgainstRace(fetchToken, fetchArgs) {\n const originalConfigVersion = ++this.configVersion;\n this._logVerbose(\n `fetching token with config version ${originalConfigVersion}`\n );\n const token = await fetchToken(fetchArgs);\n if (this.configVersion !== originalConfigVersion) {\n this._logVerbose(\n `stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`\n );\n return { isFromOutdatedConfig: true };\n }\n return { isFromOutdatedConfig: false, value: token };\n }\n stop() {\n this.resetAuthState();\n this.configVersion++;\n this._logVerbose(`config version bumped to ${this.configVersion}`);\n }\n setAndReportAuthFailed(onAuthChange) {\n onAuthChange(false);\n this.resetAuthState();\n }\n resetAuthState() {\n this.setAuthState({ state: \"noAuth\" });\n }\n setAuthState(newAuth) {\n const authStateForLog = newAuth.state === \"waitingForServerConfirmationOfFreshToken\" ? {\n hadAuth: newAuth.hadAuth,\n state: newAuth.state,\n token: `...${newAuth.token.slice(-7)}`\n } : { state: newAuth.state };\n this._logVerbose(\n `setting auth state to ${JSON.stringify(authStateForLog)}`\n );\n switch (newAuth.state) {\n case \"waitingForScheduledRefetch\":\n case \"notRefetching\":\n case \"noAuth\":\n this.tokenConfirmationAttempts = 0;\n break;\n case \"waitingForServerConfirmationOfFreshToken\":\n case \"waitingForServerConfirmationOfCachedToken\":\n case \"initialRefetch\":\n break;\n default: {\n newAuth;\n }\n }\n if (this.authState.state === \"waitingForScheduledRefetch\") {\n clearTimeout(this.authState.refetchTokenTimeoutId);\n }\n this.authState = newAuth;\n }\n decodeToken(token) {\n try {\n return jwtDecode(token);\n } catch (e) {\n this._logVerbose(\n `Error decoding token: ${e instanceof Error ? e.message : \"Unknown error\"}`\n );\n return null;\n }\n }\n _logVerbose(message) {\n this.logger.logVerbose(`${message} [v${this.configVersion}]`);\n }\n}\n//# sourceMappingURL=authentication_manager.js.map\n","\"use strict\";\nconst markNames = [\n \"convexClientConstructed\",\n \"convexWebSocketOpen\",\n \"convexFirstMessageReceived\"\n];\nexport function mark(name, sessionId) {\n const detail = { sessionId };\n if (typeof performance === \"undefined\" || !performance.mark) return;\n performance.mark(name, { detail });\n}\nfunction performanceMarkToJson(mark2) {\n let name = mark2.name.slice(\"convex\".length);\n name = name.charAt(0).toLowerCase() + name.slice(1);\n return {\n name,\n startTime: mark2.startTime\n };\n}\nexport function getMarksReport(sessionId) {\n if (typeof performance === \"undefined\" || !performance.getEntriesByName) {\n return [];\n }\n const allMarks = [];\n for (const name of markNames) {\n const marks = performance.getEntriesByName(name).filter((entry) => entry.entryType === \"mark\").filter((mark2) => mark2.detail.sessionId === sessionId);\n allMarks.push(...marks);\n }\n return allMarks.map(performanceMarkToJson);\n}\n//# sourceMappingURL=metrics.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { version } from \"../../index.js\";\nimport { convexToJson } from \"../../values/index.js\";\nimport {\n createHybridErrorStacktrace,\n forwardData,\n instantiateDefaultLogger,\n instantiateNoopLogger,\n logFatalError\n} from \"../logging.js\";\nimport { LocalSyncState } from \"./local_state.js\";\nimport { RequestManager } from \"./request_manager.js\";\nimport {\n OptimisticQueryResults\n} from \"./optimistic_updates_impl.js\";\nimport { RemoteQuerySet } from \"./remote_query_set.js\";\nimport { serializePathAndArgs } from \"./udf_path_utils.js\";\nimport { WebSocketManager } from \"./web_socket_manager.js\";\nimport { newSessionId } from \"./session.js\";\nimport {\n AuthenticationManager\n} from \"./authentication_manager.js\";\nimport { getMarksReport, mark } from \"./metrics.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../../common/index.js\";\nimport { ConvexError } from \"../../values/errors.js\";\nimport { jwtDecode } from \"../../vendor/jwt-decode/index.js\";\nexport class BaseConvexClient {\n /**\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param onTransition - A callback receiving an array of query tokens\n * corresponding to query results that have changed -- additional handlers\n * can be added via `addOnTransitionHandler`.\n * @param options - See {@link BaseConvexClientOptions} for a full description.\n */\n constructor(address, onTransition, options) {\n __publicField(this, \"address\");\n __publicField(this, \"state\");\n __publicField(this, \"requestManager\");\n __publicField(this, \"webSocketManager\");\n __publicField(this, \"authenticationManager\");\n __publicField(this, \"remoteQuerySet\");\n __publicField(this, \"optimisticQueryResults\");\n __publicField(this, \"_transitionHandlerCounter\", 0);\n __publicField(this, \"_nextRequestId\");\n __publicField(this, \"_onTransitionFns\", /* @__PURE__ */ new Map());\n __publicField(this, \"_sessionId\");\n __publicField(this, \"firstMessageReceived\", false);\n __publicField(this, \"debug\");\n __publicField(this, \"logger\");\n __publicField(this, \"maxObservedTimestamp\");\n __publicField(this, \"connectionStateSubscribers\", /* @__PURE__ */ new Map());\n __publicField(this, \"nextConnectionStateSubscriberId\", 0);\n __publicField(this, \"_lastPublishedConnectionState\");\n /**\n * Call this whenever the connection state may have changed in a way that could\n * require publishing it. Schedules a possibly update.\n */\n __publicField(this, \"markConnectionStateDirty\", () => {\n void Promise.resolve().then(() => {\n const curConnectionState = this.connectionState();\n if (JSON.stringify(curConnectionState) !== JSON.stringify(this._lastPublishedConnectionState)) {\n this._lastPublishedConnectionState = curConnectionState;\n for (const cb of this.connectionStateSubscribers.values()) {\n cb(curConnectionState);\n }\n }\n });\n });\n // Instance property so that `mark()` doesn't need to be called as a method.\n __publicField(this, \"mark\", (name) => {\n if (this.debug) {\n mark(name, this.sessionId);\n }\n });\n if (typeof address === \"object\") {\n throw new Error(\n \"Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.\"\n );\n }\n if (options?.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n options = { ...options };\n const authRefreshTokenLeewaySeconds = options.authRefreshTokenLeewaySeconds ?? 10;\n let webSocketConstructor = options.webSocketConstructor;\n if (!webSocketConstructor && typeof WebSocket === \"undefined\") {\n throw new Error(\n \"No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient\"\n );\n }\n webSocketConstructor = webSocketConstructor || WebSocket;\n this.debug = options.reportDebugInfoToConvex ?? false;\n this.address = address;\n this.logger = options.logger === false ? instantiateNoopLogger({ verbose: options.verbose ?? false }) : options.logger !== true && options.logger ? options.logger : instantiateDefaultLogger({ verbose: options.verbose ?? false });\n const i = address.search(\"://\");\n if (i === -1) {\n throw new Error(\"Provided address was not an absolute URL.\");\n }\n const origin = address.substring(i + 3);\n const protocol = address.substring(0, i);\n let wsProtocol;\n if (protocol === \"http\") {\n wsProtocol = \"ws\";\n } else if (protocol === \"https\") {\n wsProtocol = \"wss\";\n } else {\n throw new Error(`Unknown parent protocol ${protocol}`);\n }\n const wsUri = `${wsProtocol}://${origin}/api/${version}/sync`;\n this.state = new LocalSyncState();\n this.remoteQuerySet = new RemoteQuerySet(\n (queryId) => this.state.queryPath(queryId),\n this.logger\n );\n this.requestManager = new RequestManager(\n this.logger,\n this.markConnectionStateDirty\n );\n const pauseSocket = () => {\n this.webSocketManager.pause();\n this.state.pause();\n };\n this.authenticationManager = new AuthenticationManager(\n this.state,\n {\n authenticate: (token) => {\n const message = this.state.setAuth(token);\n this.webSocketManager.sendMessage(message);\n return message.baseVersion;\n },\n stopSocket: () => this.webSocketManager.stop(),\n tryRestartSocket: () => this.webSocketManager.tryRestart(),\n pauseSocket,\n resumeSocket: () => this.webSocketManager.resume(),\n clearAuth: () => {\n this.clearAuth();\n }\n },\n {\n logger: this.logger,\n refreshTokenLeewaySeconds: authRefreshTokenLeewaySeconds\n }\n );\n this.optimisticQueryResults = new OptimisticQueryResults();\n this.addOnTransitionHandler((transition) => {\n onTransition(transition.queries.map((q) => q.token));\n });\n this._nextRequestId = 0;\n this._sessionId = newSessionId();\n const { unsavedChangesWarning } = options;\n if (typeof window === \"undefined\" || typeof window.addEventListener === \"undefined\") {\n if (unsavedChangesWarning === true) {\n throw new Error(\n \"unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.\"\n );\n }\n } else if (unsavedChangesWarning !== false) {\n window.addEventListener(\"beforeunload\", (e) => {\n if (this.requestManager.hasIncompleteRequests()) {\n e.preventDefault();\n const confirmationMessage = \"Are you sure you want to leave? Your changes may not be saved.\";\n (e || window.event).returnValue = confirmationMessage;\n return confirmationMessage;\n }\n });\n }\n this.webSocketManager = new WebSocketManager(\n wsUri,\n {\n onOpen: (reconnectMetadata) => {\n this.mark(\"convexWebSocketOpen\");\n this.webSocketManager.sendMessage({\n ...reconnectMetadata,\n type: \"Connect\",\n sessionId: this._sessionId,\n maxObservedTimestamp: this.maxObservedTimestamp\n });\n this.remoteQuerySet = new RemoteQuerySet(\n (queryId) => this.state.queryPath(queryId),\n this.logger\n );\n const [querySetModification, authModification] = this.state.restart();\n if (authModification) {\n this.webSocketManager.sendMessage(authModification);\n }\n this.webSocketManager.sendMessage(querySetModification);\n for (const message of this.requestManager.restart()) {\n this.webSocketManager.sendMessage(message);\n }\n },\n onResume: () => {\n const [querySetModification, authModification] = this.state.resume();\n if (authModification) {\n this.webSocketManager.sendMessage(authModification);\n }\n if (querySetModification) {\n this.webSocketManager.sendMessage(querySetModification);\n }\n for (const message of this.requestManager.resume()) {\n this.webSocketManager.sendMessage(message);\n }\n },\n onMessage: (serverMessage) => {\n if (!this.firstMessageReceived) {\n this.firstMessageReceived = true;\n this.mark(\"convexFirstMessageReceived\");\n this.reportMarks();\n }\n switch (serverMessage.type) {\n case \"Transition\": {\n this.observedTimestamp(serverMessage.endVersion.ts);\n this.authenticationManager.onTransition(serverMessage);\n this.remoteQuerySet.transition(serverMessage);\n this.state.transition(serverMessage);\n const completedRequests = this.requestManager.removeCompleted(\n this.remoteQuerySet.timestamp()\n );\n this.notifyOnQueryResultChanges(completedRequests);\n break;\n }\n case \"MutationResponse\": {\n if (serverMessage.success) {\n this.observedTimestamp(serverMessage.ts);\n }\n const completedMutationInfo = this.requestManager.onResponse(serverMessage);\n if (completedMutationInfo !== null) {\n this.notifyOnQueryResultChanges(\n /* @__PURE__ */ new Map([\n [\n completedMutationInfo.requestId,\n completedMutationInfo.result\n ]\n ])\n );\n }\n break;\n }\n case \"ActionResponse\": {\n this.requestManager.onResponse(serverMessage);\n break;\n }\n case \"AuthError\": {\n this.authenticationManager.onAuthError(serverMessage);\n break;\n }\n case \"FatalError\": {\n const error = logFatalError(this.logger, serverMessage.error);\n void this.webSocketManager.terminate();\n throw error;\n }\n default: {\n serverMessage;\n }\n }\n return {\n hasSyncedPastLastReconnect: this.hasSyncedPastLastReconnect()\n };\n },\n onServerDisconnectError: options.onServerDisconnectError\n },\n webSocketConstructor,\n this.logger,\n this.markConnectionStateDirty,\n this.debug\n );\n this.mark(\"convexClientConstructed\");\n if (options.expectAuth) {\n pauseSocket();\n }\n }\n /**\n * Return true if there is outstanding work from prior to the time of the most recent restart.\n * This indicates that the client has not proven itself to have gotten past the issue that\n * potentially led to the restart. Use this to influence when to reset backoff after a failure.\n */\n hasSyncedPastLastReconnect() {\n const hasSyncedPastLastReconnect = this.requestManager.hasSyncedPastLastReconnect() && this.state.hasSyncedPastLastReconnect();\n return hasSyncedPastLastReconnect;\n }\n observedTimestamp(observedTs) {\n if (this.maxObservedTimestamp === void 0 || this.maxObservedTimestamp.lessThanOrEqual(observedTs)) {\n this.maxObservedTimestamp = observedTs;\n }\n }\n getMaxObservedTimestamp() {\n return this.maxObservedTimestamp;\n }\n /**\n * Compute the current query results based on the remoteQuerySet and the\n * current optimistic updates and call `onTransition` for all the changed\n * queries.\n *\n * @param completedMutations - A set of mutation IDs whose optimistic updates\n * are no longer needed.\n */\n notifyOnQueryResultChanges(completedRequests) {\n const remoteQueryResults = this.remoteQuerySet.remoteQueryResults();\n const queryTokenToValue = /* @__PURE__ */ new Map();\n for (const [queryId, result] of remoteQueryResults) {\n const queryToken = this.state.queryToken(queryId);\n if (queryToken !== null) {\n const query = {\n result,\n udfPath: this.state.queryPath(queryId),\n args: this.state.queryArgs(queryId)\n };\n queryTokenToValue.set(queryToken, query);\n }\n }\n const changedQueryTokens = this.optimisticQueryResults.ingestQueryResultsFromServer(\n queryTokenToValue,\n new Set(completedRequests.keys())\n );\n this.handleTransition({\n queries: changedQueryTokens.map((token) => {\n const optimisticResult = this.optimisticQueryResults.rawQueryResult(token);\n return {\n token,\n modification: {\n kind: \"Updated\",\n result: optimisticResult\n }\n };\n }),\n reflectedMutations: Array.from(completedRequests).map(\n ([requestId, result]) => ({\n requestId,\n result\n })\n ),\n timestamp: this.remoteQuerySet.timestamp()\n });\n }\n handleTransition(transition) {\n for (const fn of this._onTransitionFns.values()) {\n fn(transition);\n }\n }\n /**\n * Add a handler that will be called on a transition.\n *\n * Any external side effects (e.g. setting React state) should be handled here.\n *\n * @param fn\n *\n * @returns\n */\n addOnTransitionHandler(fn) {\n const id = this._transitionHandlerCounter++;\n this._onTransitionFns.set(id, fn);\n return () => this._onTransitionFns.delete(id);\n }\n /**\n * Get the current JWT auth token and decoded claims.\n */\n getCurrentAuthClaims() {\n const authToken = this.state.getAuth();\n let decoded = {};\n if (authToken && authToken.tokenType === \"User\") {\n try {\n decoded = authToken ? jwtDecode(authToken.value) : {};\n } catch {\n decoded = {};\n }\n } else {\n return void 0;\n }\n return { token: authToken.value, decoded };\n }\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(fetchToken, onChange) {\n void this.authenticationManager.setConfig(fetchToken, onChange);\n }\n hasAuth() {\n return this.state.hasAuth();\n }\n /** @internal */\n setAdminAuth(value, fakeUserIdentity) {\n const message = this.state.setAdminAuth(value, fakeUserIdentity);\n this.webSocketManager.sendMessage(message);\n }\n clearAuth() {\n const message = this.state.clearAuth();\n this.webSocketManager.sendMessage(message);\n }\n /**\n * Subscribe to a query function.\n *\n * Whenever this query's result changes, the `onTransition` callback\n * passed into the constructor will be called.\n *\n * @param name - The name of the query.\n * @param args - An arguments object for the query. If this is omitted, the\n * arguments will be `{}`.\n * @param options - A {@link SubscribeOptions} options object for this query.\n \n * @returns An object containing a {@link QueryToken} corresponding to this\n * query and an `unsubscribe` callback.\n */\n subscribe(name, args, options) {\n const argsObject = parseArgs(args);\n const { modification, queryToken, unsubscribe } = this.state.subscribe(\n name,\n argsObject,\n options?.journal,\n options?.componentPath\n );\n if (modification !== null) {\n this.webSocketManager.sendMessage(modification);\n }\n return {\n queryToken,\n unsubscribe: () => {\n const modification2 = unsubscribe();\n if (modification2) {\n this.webSocketManager.sendMessage(modification2);\n }\n }\n };\n }\n /**\n * A query result based only on the current, local state.\n *\n * The only way this will return a value is if we're already subscribed to the\n * query or its value has been set optimistically.\n */\n localQueryResult(udfPath, args) {\n const argsObject = parseArgs(args);\n const queryToken = serializePathAndArgs(udfPath, argsObject);\n return this.optimisticQueryResults.queryResult(queryToken);\n }\n /**\n * Get query result by query token based on current, local state\n *\n * The only way this will return a value is if we're already subscribed to the\n * query or its value has been set optimistically.\n *\n * @internal\n */\n localQueryResultByToken(queryToken) {\n return this.optimisticQueryResults.queryResult(queryToken);\n }\n /**\n * Whether local query result is available for a token.\n *\n * This method does not throw if the result is an error.\n *\n * @internal\n */\n hasLocalQueryResultByToken(queryToken) {\n return this.optimisticQueryResults.hasQueryResult(queryToken);\n }\n /**\n * @internal\n */\n localQueryLogs(udfPath, args) {\n const argsObject = parseArgs(args);\n const queryToken = serializePathAndArgs(udfPath, argsObject);\n return this.optimisticQueryResults.queryLogs(queryToken);\n }\n /**\n * Retrieve the current {@link QueryJournal} for this query function.\n *\n * If we have not yet received a result for this query, this will be `undefined`.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for this query.\n * @returns The query's {@link QueryJournal} or `undefined`.\n */\n queryJournal(name, args) {\n const argsObject = parseArgs(args);\n const queryToken = serializePathAndArgs(name, argsObject);\n return this.state.queryJournal(queryToken);\n }\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState() {\n const wsConnectionState = this.webSocketManager.connectionState();\n return {\n hasInflightRequests: this.requestManager.hasInflightRequests(),\n isWebSocketConnected: wsConnectionState.isConnected,\n hasEverConnected: wsConnectionState.hasEverConnected,\n connectionCount: wsConnectionState.connectionCount,\n connectionRetries: wsConnectionState.connectionRetries,\n timeOfOldestInflightRequest: this.requestManager.timeOfOldestInflightRequest(),\n inflightMutations: this.requestManager.inflightMutations(),\n inflightActions: this.requestManager.inflightActions()\n };\n }\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(cb) {\n const id = this.nextConnectionStateSubscriberId++;\n this.connectionStateSubscribers.set(id, cb);\n return () => {\n this.connectionStateSubscribers.delete(id);\n };\n }\n /**\n * Execute a mutation function.\n *\n * @param name - The name of the mutation.\n * @param args - An arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link MutationOptions} options object for this mutation.\n \n * @returns - A promise of the mutation's result.\n */\n async mutation(name, args, options) {\n const result = await this.mutationInternal(name, args, options);\n if (!result.success) {\n if (result.errorData !== void 0) {\n throw forwardData(\n result,\n new ConvexError(\n createHybridErrorStacktrace(\"mutation\", name, result)\n )\n );\n }\n throw new Error(createHybridErrorStacktrace(\"mutation\", name, result));\n }\n return result.value;\n }\n /**\n * @internal\n */\n async mutationInternal(udfPath, args, options, componentPath) {\n const { mutationPromise } = this.enqueueMutation(\n udfPath,\n args,\n options,\n componentPath\n );\n return mutationPromise;\n }\n /**\n * @internal\n */\n enqueueMutation(udfPath, args, options, componentPath) {\n const mutationArgs = parseArgs(args);\n this.tryReportLongDisconnect();\n const requestId = this.nextRequestId;\n this._nextRequestId++;\n if (options !== void 0) {\n const optimisticUpdate = options.optimisticUpdate;\n if (optimisticUpdate !== void 0) {\n const wrappedUpdate = (localQueryStore) => {\n const result = optimisticUpdate(\n localQueryStore,\n mutationArgs\n );\n if (result instanceof Promise) {\n this.logger.warn(\n \"Optimistic update handler returned a Promise. Optimistic updates should be synchronous.\"\n );\n }\n };\n const changedQueryTokens = this.optimisticQueryResults.applyOptimisticUpdate(\n wrappedUpdate,\n requestId\n );\n const changedQueries = changedQueryTokens.map((token) => {\n const localResult = this.localQueryResultByToken(token);\n return {\n token,\n modification: {\n kind: \"Updated\",\n result: localResult === void 0 ? void 0 : {\n success: true,\n value: localResult,\n logLines: []\n }\n }\n };\n });\n this.handleTransition({\n queries: changedQueries,\n reflectedMutations: [],\n timestamp: this.remoteQuerySet.timestamp()\n });\n }\n }\n const message = {\n type: \"Mutation\",\n requestId,\n udfPath,\n componentPath,\n args: [convexToJson(mutationArgs)]\n };\n const mightBeSent = this.webSocketManager.sendMessage(message);\n const mutationPromise = this.requestManager.request(message, mightBeSent);\n return {\n requestId,\n mutationPromise\n };\n }\n /**\n * Execute an action function.\n *\n * @param name - The name of the action.\n * @param args - An arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n async action(name, args) {\n const result = await this.actionInternal(name, args);\n if (!result.success) {\n if (result.errorData !== void 0) {\n throw forwardData(\n result,\n new ConvexError(createHybridErrorStacktrace(\"action\", name, result))\n );\n }\n throw new Error(createHybridErrorStacktrace(\"action\", name, result));\n }\n return result.value;\n }\n /**\n * @internal\n */\n async actionInternal(udfPath, args, componentPath) {\n const actionArgs = parseArgs(args);\n const requestId = this.nextRequestId;\n this._nextRequestId++;\n this.tryReportLongDisconnect();\n const message = {\n type: \"Action\",\n requestId,\n udfPath,\n componentPath,\n args: [convexToJson(actionArgs)]\n };\n const mightBeSent = this.webSocketManager.sendMessage(message);\n return this.requestManager.request(message, mightBeSent);\n }\n /**\n * Close any network handles associated with this client and stop all subscriptions.\n *\n * Call this method when you're done with an {@link BaseConvexClient} to\n * dispose of its sockets and resources.\n *\n * @returns A `Promise` fulfilled when the connection has been completely closed.\n */\n async close() {\n this.authenticationManager.stop();\n return this.webSocketManager.terminate();\n }\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n /**\n * @internal\n */\n get nextRequestId() {\n return this._nextRequestId;\n }\n /**\n * @internal\n */\n get sessionId() {\n return this._sessionId;\n }\n /**\n * Reports performance marks to the server. This should only be called when\n * we have a functional websocket.\n */\n reportMarks() {\n if (this.debug) {\n const report = getMarksReport(this.sessionId);\n this.webSocketManager.sendMessage({\n type: \"Event\",\n eventType: \"ClientConnect\",\n event: report\n });\n }\n }\n tryReportLongDisconnect() {\n if (!this.debug) {\n return;\n }\n const timeOfOldestRequest = this.connectionState().timeOfOldestInflightRequest;\n if (timeOfOldestRequest === null || Date.now() - timeOfOldestRequest.getTime() <= 60 * 1e3) {\n return;\n }\n const endpoint = `${this.address}/api/debug_event`;\n fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`\n },\n body: JSON.stringify({ event: \"LongWebsocketDisconnect\" })\n }).then((response) => {\n if (!response.ok) {\n this.logger.warn(\n \"Analytics request failed with response:\",\n response.body\n );\n }\n }).catch((error) => {\n this.logger.warn(\"Analytics response failed with error:\", error);\n });\n }\n}\n//# sourceMappingURL=client.js.map\n","\"use strict\";\nexport function asPaginationArgs(value) {\n if (typeof value.paginationOpts.numItems !== \"number\") {\n throw new Error(`Not valid paginated query args: ${JSON.stringify(value)}`);\n }\n return value;\n}\nexport function asPaginationResult(value) {\n if (typeof value !== \"object\" || value === null || !Array.isArray(value.page) || typeof value.isDone !== \"boolean\" || typeof value.continueCursor !== \"string\") {\n throw new Error(`Not a valid paginated query result: ${value?.toString()}`);\n }\n return value;\n}\n//# sourceMappingURL=pagination.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n serializePaginatedPathAndArgs,\n canonicalizeUdfPath\n} from \"./udf_path_utils.js\";\nimport {\n asPaginationResult\n} from \"./pagination.js\";\nimport { Long } from \"../../vendor/long.js\";\nexport class PaginatedQueryClient {\n constructor(client, onTransition) {\n this.client = client;\n this.onTransition = onTransition;\n __publicField(this, \"paginatedQuerySet\", /* @__PURE__ */ new Map());\n // hold onto a real Transition so we can construct synthetic ones with that timestamp\n __publicField(this, \"lastTransitionTs\");\n this.lastTransitionTs = Long.fromNumber(0);\n this.client.addOnTransitionHandler(\n (transition) => this.onBaseTransition(transition)\n );\n }\n /**\n * Subscribe to a paginated query.\n *\n * @param name - The name of the paginated query function\n * @param args - Arguments for the query (excluding paginationOpts)\n * @param options - Pagination options including initialNumItems\n * @returns Object with paginatedQueryToken and unsubscribe function\n */\n subscribe(name, args, options) {\n const canonicalizedUdfPath = canonicalizeUdfPath(name);\n const token = serializePaginatedPathAndArgs(\n canonicalizedUdfPath,\n args,\n options\n );\n const unsubscribe = () => this.removePaginatedQuerySubscriber(token);\n const existingEntry = this.paginatedQuerySet.get(token);\n if (existingEntry) {\n existingEntry.numSubscribers += 1;\n return {\n paginatedQueryToken: token,\n unsubscribe\n };\n }\n this.paginatedQuerySet.set(token, {\n token,\n canonicalizedUdfPath,\n args,\n numSubscribers: 1,\n options: { initialNumItems: options.initialNumItems },\n nextPageKey: 0,\n pageKeys: [],\n pageKeyToQuery: /* @__PURE__ */ new Map(),\n ongoingSplits: /* @__PURE__ */ new Map(),\n skip: false,\n id: options.id\n });\n this.addPageToPaginatedQuery(token, null, options.initialNumItems);\n return {\n paginatedQueryToken: token,\n unsubscribe\n };\n }\n /**\n * Get current results for a paginated query based on local state.\n *\n * Throws an error when one of the pages has errored.\n */\n localQueryResult(name, args, options) {\n const canonicalizedUdfPath = canonicalizeUdfPath(name);\n const token = serializePaginatedPathAndArgs(\n canonicalizedUdfPath,\n args,\n options\n );\n return this.localQueryResultByToken(token);\n }\n /**\n * @internal\n */\n localQueryResultByToken(token) {\n const paginatedQuery = this.paginatedQuerySet.get(token);\n if (!paginatedQuery) {\n return void 0;\n }\n const activePages = this.activePageQueryTokens(paginatedQuery);\n if (activePages.length === 0) {\n return {\n results: [],\n status: \"LoadingFirstPage\",\n loadMore: (numItems) => {\n return this.loadMoreOfPaginatedQuery(token, numItems);\n }\n };\n }\n let allResults = [];\n let hasUndefined = false;\n let isDone = false;\n for (const pageToken of activePages) {\n const result = this.client.localQueryResultByToken(pageToken);\n if (result === void 0) {\n hasUndefined = true;\n isDone = false;\n continue;\n }\n const paginationResult = asPaginationResult(result);\n allResults = allResults.concat(paginationResult.page);\n isDone = !!paginationResult.isDone;\n }\n let status;\n if (hasUndefined) {\n status = allResults.length === 0 ? \"LoadingFirstPage\" : \"LoadingMore\";\n } else if (isDone) {\n status = \"Exhausted\";\n } else {\n status = \"CanLoadMore\";\n }\n return {\n results: allResults,\n status,\n loadMore: (numItems) => {\n return this.loadMoreOfPaginatedQuery(token, numItems);\n }\n };\n }\n onBaseTransition(transition) {\n const changedBaseTokens = transition.queries.map((q) => q.token);\n const changed = this.queriesContainingTokens(changedBaseTokens);\n let paginatedQueries = [];\n if (changed.length > 0) {\n this.processPaginatedQuerySplits(\n changed,\n (token) => this.client.localQueryResultByToken(token)\n );\n paginatedQueries = changed.map((token) => ({\n token,\n modification: {\n kind: \"Updated\",\n result: this.localQueryResultByToken(token)\n }\n }));\n }\n const extendedTransition = {\n ...transition,\n paginatedQueries\n };\n this.onTransition(extendedTransition);\n }\n /**\n * Load more items for a paginated query.\n *\n * This *always* causes a transition, the status of the query\n * has probably changed from \"CanLoadMore\" to \"LoadingMore\".\n * Data might have changed too: maybe a subscription to this page\n * query already exists (unlikely but possible) or this page query\n * has an optimistic update providing some initial data.\n *\n * @internal\n */\n loadMoreOfPaginatedQuery(token, numItems) {\n this.mustGetPaginatedQuery(token);\n const lastPageToken = this.queryTokenForLastPageOfPaginatedQuery(token);\n const lastPageResult = this.client.localQueryResultByToken(lastPageToken);\n if (!lastPageResult) {\n return false;\n }\n const paginationResult = asPaginationResult(lastPageResult);\n if (paginationResult.isDone) {\n return false;\n }\n this.addPageToPaginatedQuery(\n token,\n paginationResult.continueCursor,\n numItems\n );\n const loadMoreTransition = {\n timestamp: this.lastTransitionTs,\n reflectedMutations: [],\n queries: [],\n paginatedQueries: [\n {\n token,\n modification: {\n kind: \"Updated\",\n result: this.localQueryResultByToken(token)\n }\n }\n ]\n };\n this.onTransition(loadMoreTransition);\n return true;\n }\n /**\n * @internal\n */\n queriesContainingTokens(queryTokens) {\n if (queryTokens.length === 0) {\n return [];\n }\n const changed = [];\n const queryTokenSet = new Set(queryTokens);\n for (const [paginatedToken, paginatedQuery] of this.paginatedQuerySet) {\n for (const pageToken of this.allQueryTokens(paginatedQuery)) {\n if (queryTokenSet.has(pageToken)) {\n changed.push(paginatedToken);\n break;\n }\n }\n }\n return changed;\n }\n /**\n * @internal\n */\n processPaginatedQuerySplits(changed, getResult) {\n for (const paginatedQueryToken of changed) {\n const paginatedQuery = this.mustGetPaginatedQuery(paginatedQueryToken);\n const { ongoingSplits, pageKeyToQuery, pageKeys } = paginatedQuery;\n for (const [pageKey, [splitKey1, splitKey2]] of ongoingSplits) {\n const bothNewPagesLoaded = getResult(pageKeyToQuery.get(splitKey1).queryToken) !== void 0 && getResult(pageKeyToQuery.get(splitKey2).queryToken) !== void 0;\n if (bothNewPagesLoaded) {\n this.completePaginatedQuerySplit(\n paginatedQuery,\n pageKey,\n splitKey1,\n splitKey2\n );\n }\n }\n for (const pageKey of pageKeys) {\n if (ongoingSplits.has(pageKey)) {\n continue;\n }\n const pageToken = pageKeyToQuery.get(pageKey).queryToken;\n const pageResult = getResult(pageToken);\n if (!pageResult) {\n continue;\n }\n const result = asPaginationResult(pageResult);\n const shouldSplit = result.splitCursor && (result.pageStatus === \"SplitRecommended\" || result.pageStatus === \"SplitRequired\" || // This client-driven page splitting condition will change in the future.\n result.page.length > paginatedQuery.options.initialNumItems * 2);\n if (shouldSplit) {\n this.splitPaginatedQueryPage(\n paginatedQuery,\n pageKey,\n result.splitCursor,\n // we just checked\n result.continueCursor\n );\n }\n }\n }\n }\n splitPaginatedQueryPage(paginatedQuery, pageKey, splitCursor, continueCursor) {\n const splitKey1 = paginatedQuery.nextPageKey++;\n const splitKey2 = paginatedQuery.nextPageKey++;\n const paginationOpts = {\n cursor: continueCursor,\n numItems: paginatedQuery.options.initialNumItems,\n id: paginatedQuery.id\n };\n const firstSubscription = this.client.subscribe(\n paginatedQuery.canonicalizedUdfPath,\n {\n ...paginatedQuery.args,\n paginationOpts: {\n ...paginationOpts,\n cursor: null,\n // Start from beginning for first split\n endCursor: splitCursor\n }\n }\n );\n paginatedQuery.pageKeyToQuery.set(splitKey1, firstSubscription);\n const secondSubscription = this.client.subscribe(\n paginatedQuery.canonicalizedUdfPath,\n {\n ...paginatedQuery.args,\n paginationOpts: {\n ...paginationOpts,\n cursor: splitCursor,\n endCursor: continueCursor\n }\n }\n );\n paginatedQuery.pageKeyToQuery.set(splitKey2, secondSubscription);\n paginatedQuery.ongoingSplits.set(pageKey, [splitKey1, splitKey2]);\n }\n /**\n * @internal\n */\n addPageToPaginatedQuery(token, continueCursor, numItems) {\n const paginatedQuery = this.mustGetPaginatedQuery(token);\n const pageKey = paginatedQuery.nextPageKey++;\n const paginationOpts = {\n cursor: continueCursor,\n numItems,\n id: paginatedQuery.id\n };\n const pageArgs = {\n ...paginatedQuery.args,\n paginationOpts\n };\n const subscription = this.client.subscribe(\n paginatedQuery.canonicalizedUdfPath,\n pageArgs\n );\n paginatedQuery.pageKeys.push(pageKey);\n paginatedQuery.pageKeyToQuery.set(pageKey, subscription);\n return subscription;\n }\n removePaginatedQuerySubscriber(token) {\n const paginatedQuery = this.paginatedQuerySet.get(token);\n if (!paginatedQuery) {\n return;\n }\n paginatedQuery.numSubscribers -= 1;\n if (paginatedQuery.numSubscribers > 0) {\n return;\n }\n for (const subscription of paginatedQuery.pageKeyToQuery.values()) {\n subscription.unsubscribe();\n }\n this.paginatedQuerySet.delete(token);\n }\n completePaginatedQuerySplit(paginatedQuery, pageKey, splitKey1, splitKey2) {\n const originalQuery = paginatedQuery.pageKeyToQuery.get(pageKey);\n paginatedQuery.pageKeyToQuery.delete(pageKey);\n const pageIndex = paginatedQuery.pageKeys.indexOf(pageKey);\n paginatedQuery.pageKeys.splice(pageIndex, 1, splitKey1, splitKey2);\n paginatedQuery.ongoingSplits.delete(pageKey);\n originalQuery.unsubscribe();\n }\n /** The query tokens for all active pages, in result order */\n activePageQueryTokens(paginatedQuery) {\n return paginatedQuery.pageKeys.map(\n (pageKey) => paginatedQuery.pageKeyToQuery.get(pageKey).queryToken\n );\n }\n allQueryTokens(paginatedQuery) {\n return Array.from(paginatedQuery.pageKeyToQuery.values()).map(\n (sub) => sub.queryToken\n );\n }\n queryTokenForLastPageOfPaginatedQuery(token) {\n const paginatedQuery = this.mustGetPaginatedQuery(token);\n const lastPageKey = paginatedQuery.pageKeys[paginatedQuery.pageKeys.length - 1];\n if (lastPageKey === void 0) {\n throw new Error(`No pages for paginated query ${token}`);\n }\n return paginatedQuery.pageKeyToQuery.get(lastPageKey).queryToken;\n }\n mustGetPaginatedQuery(token) {\n const paginatedQuery = this.paginatedQuerySet.get(token);\n if (!paginatedQuery) {\n throw new Error(\"paginated query no longer exists for token \" + token);\n }\n return paginatedQuery;\n }\n}\n//# sourceMappingURL=paginated_query_client.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n BaseConvexClient\n} from \"./index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport {\n PaginatedQueryClient\n} from \"./sync/paginated_query_client.js\";\nimport { serializedQueryTokenIsPaginated } from \"./sync/udf_path_utils.js\";\nlet defaultWebSocketConstructor;\nexport function setDefaultWebSocketConstructor(ws) {\n defaultWebSocketConstructor = ws;\n}\nexport class ConvexClient {\n /**\n * Construct a client and immediately initiate a WebSocket connection to the passed address.\n *\n * @public\n */\n constructor(address, options = {}) {\n __publicField(this, \"listeners\");\n __publicField(this, \"_client\");\n __publicField(this, \"_paginatedClient\");\n // A synthetic server event to run callbacks the first time\n __publicField(this, \"callNewListenersWithCurrentValuesTimer\");\n __publicField(this, \"_closed\");\n __publicField(this, \"_disabled\");\n if (options.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n const { disabled, ...baseOptions } = options;\n this._closed = false;\n this._disabled = !!disabled;\n if (defaultWebSocketConstructor && !(\"webSocketConstructor\" in baseOptions) && typeof WebSocket === \"undefined\") {\n baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n }\n if (typeof window === \"undefined\" && !(\"unsavedChangesWarning\" in baseOptions)) {\n baseOptions.unsavedChangesWarning = false;\n }\n if (!this.disabled) {\n this._client = new BaseConvexClient(\n address,\n () => {\n },\n // NOP, let the paginated query client do it all\n baseOptions\n );\n this._paginatedClient = new PaginatedQueryClient(\n this._client,\n (transition) => this._transition(transition)\n );\n }\n this.listeners = /* @__PURE__ */ new Set();\n }\n /**\n * Once closed no registered callbacks will fire again.\n */\n get closed() {\n return this._closed;\n }\n get client() {\n if (this._client) return this._client;\n throw new Error(\"ConvexClient is disabled\");\n }\n /**\n * @internal\n */\n get paginatedClient() {\n if (this._paginatedClient) return this._paginatedClient;\n throw new Error(\"ConvexClient is disabled\");\n }\n get disabled() {\n return this._disabled;\n }\n /**\n * Call a callback whenever a new result for a query is received. The callback\n * will run soon after being registered if a result for the query is already\n * in memory.\n *\n * The return value is an {@link Unsubscribe} object which is both a function\n * an an object with properties. Both of the patterns below work with this object:\n *\n *```ts\n * // call the return value as a function\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n * unsubscribe();\n *\n * // unpack the return value into its properties\n * const {\n * getCurrentValue,\n * unsubscribe,\n * } = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n *```\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n * If not provided, errors will be thrown instead of calling the callback.\n *\n * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n */\n onUpdate(query, args, callback, onError) {\n if (this.disabled) {\n return this.createDisabledUnsubscribe();\n }\n const { queryToken, unsubscribe } = this.client.subscribe(\n getFunctionName(query),\n args\n );\n const queryInfo = {\n queryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions: void 0\n };\n this.listeners.add(queryInfo);\n if (this.queryResultReady(queryToken) && this.callNewListenersWithCurrentValuesTimer === void 0) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0\n );\n }\n const unsubscribeProps = {\n unsubscribe: () => {\n if (this.closed) {\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n getQueryLogs: () => this.client.localQueryLogs(queryToken)\n };\n const ret = unsubscribeProps.unsubscribe;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n /**\n * Call a callback whenever a new result for a paginated query is received.\n *\n * This is an experimental preview: the final API may change.\n * In particular, caching behavior, page splitting, and required paginated query options\n * may change.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param options - Options for the paginated query including initialNumItems and id.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n *\n * @return an {@link Unsubscribe} function to stop calling the callback.\n */\n onPaginatedUpdate_experimental(query, args, options, callback, onError) {\n if (this.disabled) {\n return this.createDisabledUnsubscribe();\n }\n const paginationOptions = {\n initialNumItems: options.initialNumItems,\n id: -1\n };\n const { paginatedQueryToken, unsubscribe } = this.paginatedClient.subscribe(\n getFunctionName(query),\n args,\n // Simple client doesn't use IDs, there's no expectation that these queries remain separate.\n paginationOptions\n );\n const queryInfo = {\n queryToken: paginatedQueryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions\n };\n this.listeners.add(queryInfo);\n if (!!this.paginatedClient.localQueryResultByToken(paginatedQueryToken) && this.callNewListenersWithCurrentValuesTimer === void 0) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0\n );\n }\n const unsubscribeProps = {\n unsubscribe: () => {\n if (this.closed) {\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => {\n const result = this.paginatedClient.localQueryResult(\n getFunctionName(query),\n args,\n paginationOptions\n );\n return result;\n },\n getQueryLogs: () => []\n // Paginated queries don't aggregate their logs\n };\n const ret = unsubscribeProps.unsubscribe;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n // Run all callbacks that have never been run before if they have a query\n // result available now.\n callNewListenersWithCurrentValues() {\n this.callNewListenersWithCurrentValuesTimer = void 0;\n this._transition({ queries: [], paginatedQueries: [] }, true);\n }\n queryResultReady(queryToken) {\n return this.client.hasLocalQueryResultByToken(queryToken);\n }\n createDisabledUnsubscribe() {\n const disabledUnsubscribe = (() => {\n });\n const unsubscribeProps = {\n unsubscribe: disabledUnsubscribe,\n getCurrentValue: () => void 0,\n getQueryLogs: () => void 0\n };\n Object.assign(disabledUnsubscribe, unsubscribeProps);\n return disabledUnsubscribe;\n }\n async close() {\n if (this.disabled) return;\n this.listeners.clear();\n this._closed = true;\n if (this._paginatedClient) {\n this._paginatedClient = void 0;\n }\n return this.client.close();\n }\n /**\n * Get the current JWT auth token and decoded claims.\n */\n getAuth() {\n if (this.disabled) return;\n return this.client.getCurrentAuthClaims();\n }\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(fetchToken, onChange) {\n if (this.disabled) return;\n this.client.setAuth(\n fetchToken,\n onChange ?? (() => {\n })\n );\n }\n /**\n * @internal\n */\n setAdminAuth(token, identity) {\n if (this.closed) {\n throw new Error(\"ConvexClient has already been closed.\");\n }\n if (this.disabled) return;\n this.client.setAdminAuth(token, identity);\n }\n /**\n * @internal\n */\n _transition({\n queries,\n paginatedQueries\n }, callNewListeners = false) {\n const updatedQueries = [\n ...queries.map((q) => q.token),\n ...paginatedQueries.map((q) => q.token)\n ];\n for (const queryInfo of this.listeners) {\n const { callback, queryToken, onError, hasEverRun } = queryInfo;\n const isPaginatedQuery = serializedQueryTokenIsPaginated(queryToken);\n const hasResultReady = isPaginatedQuery ? !!this.paginatedClient.localQueryResultByToken(queryToken) : this.client.hasLocalQueryResultByToken(queryToken);\n if (updatedQueries.includes(queryToken) || callNewListeners && !hasEverRun && hasResultReady) {\n queryInfo.hasEverRun = true;\n let newValue;\n try {\n if (isPaginatedQuery) {\n newValue = this.paginatedClient.localQueryResultByToken(queryToken);\n } else {\n newValue = this.client.localQueryResultByToken(queryToken);\n }\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n if (onError) {\n onError(\n error,\n \"Second argument to onUpdate onError is reserved for later use\"\n );\n } else {\n void Promise.reject(error);\n }\n continue;\n }\n callback(\n newValue,\n \"Second argument to onUpdate callback is reserved for later use\"\n );\n }\n }\n }\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n async mutation(mutation, args, options) {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.mutation(getFunctionName(mutation), args, options);\n }\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action.\n * @returns A promise of the action's result.\n */\n async action(action, args) {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.action(getFunctionName(action), args);\n }\n /**\n * Fetch a query result once.\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query.\n * @returns A promise of the query's result.\n */\n async query(query, args) {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n const value = this.client.localQueryResult(getFunctionName(query), args);\n if (value !== void 0) return Promise.resolve(value);\n return new Promise((resolve, reject) => {\n const { unsubscribe } = this.onUpdate(\n query,\n args,\n (value2) => {\n unsubscribe();\n resolve(value2);\n },\n (e) => {\n unsubscribe();\n reject(e);\n }\n );\n });\n }\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState() {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return this.client.connectionState();\n }\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(cb) {\n if (this.disabled) return () => {\n };\n return this.client.subscribeToConnectionState(cb);\n }\n}\n//# sourceMappingURL=simple_client.js.map\n","/**\n * Tiny in-house state machine. Replaces clusters of `useState` booleans /\n * strings where the values are correlated — invalid combinations become\n * unrepresentable, and side-effects become consequences of `state.kind`\n * changes (one effect per transition) instead of orchestration logic\n * scattered across many effects.\n *\n * The model intentionally mirrors Kent C. Dodds' \"Implementing a simple\n * state machine library in JavaScript\": states keyed by string, events\n * keyed by string, transitions are pure functions. Invalid transitions\n * are silent no-ops rather than throws — same forgiving semantics.\n */\n\nimport { useCallback, useRef, useState } from 'preact/hooks'\n\n/**\n * State-kind → event-type → transition fn.\n *\n * Typed so the transition receives the narrowed state + event variant —\n * inside a handler keyed by `'idle'`/`'start'` the parameter types are\n * `Extract<S, { kind: 'idle' }>` and `Extract<E, { type: 'start' }>`,\n * not the full unions. The `Partial<>` lets a state omit handlers for\n * irrelevant events without listing them all as `undefined`.\n */\nexport type TransitionMap<S extends { kind: string }, E extends { type: string }> = {\n [K in S['kind']]?: Partial<{\n [T in E['type']]: (state: Extract<S, { kind: K }>, event: Extract<E, { type: T }>) => S\n }>\n}\n\nexport type Send<E extends { type: string }> = (event: E) => void\n\n/**\n * Identity helper that gives a `TransitionMap` literal full type inference\n * for state and event unions. Equivalent to writing\n * `const m: TransitionMap<S, E> = { ... }` at the call site, but reads\n * better and keeps the generic params co-located with the table.\n */\nexport function defineMachine<S extends { kind: string }, E extends { type: string }>(\n transitions: TransitionMap<S, E>,\n): TransitionMap<S, E> {\n return transitions\n}\n\n/**\n * Drive a state machine inside a component. Returns the current state\n * and a `send` dispatcher whose identity is stable across renders, so\n * it can sit on dependency arrays without re-triggering effects.\n *\n * The transition table is captured in a ref so each call sees the\n * freshest closure values without invalidating `send`. Callers can\n * inline `defineMachine(...)` in the render body and reference render-\n * scope values from handlers without explicit memoization.\n */\nexport function useMachine<S extends { kind: string }, E extends { type: string }>(\n transitions: TransitionMap<S, E>,\n // `NoInfer` so a narrow initial literal (e.g. `{ kind: 'visible' }`) does\n // not pin `S` to a single variant — `S` is inferred from the transition\n // table, which carries the full union, and `initial` must merely be\n // assignable to it.\n initial: NoInfer<S> | (() => NoInfer<S>),\n): [S, Send<E>] {\n const transitionsRef = useRef(transitions)\n transitionsRef.current = transitions\n\n const [state, setState] = useState<S>(() =>\n typeof initial === 'function' ? (initial as () => S)() : initial,\n )\n\n const send = useCallback<Send<E>>((event) => {\n setState((current) => {\n const forKind = transitionsRef.current[current.kind as S['kind']]\n const handler = forKind?.[event.type as E['type']] as ((s: S, e: E) => S) | undefined\n return handler ? handler(current, event) : current\n })\n }, [])\n\n return [state, send]\n}\n","/**\n * `useAsyncAction` — drives a single user-initiated async operation\n * through a 4-state machine. Modeled on TanStack Query's `useMutation`:\n * exposes `isIdle` / `isPending` / `isSuccess` / `isError` flags,\n * persists the most recent `data` on success, and supports per-call\n * `onSuccess` / `onError` / `onSettled` callbacks.\n *\n * Replaces the\n *\n * setPending(true); setError(null)\n * try { ... } catch (err) { setError(err.message) } finally { setPending(false) }\n *\n * boilerplate that gets repeated across every async handler in the\n * widget. Each handler shrinks to one `run(async () => { ... })` call\n * and inherits correct loading + error state, with invalid combinations\n * (pending + error simultaneously, error + success crossover) eliminated\n * at the type level.\n *\n * Re-entrant calls while `pending` are silently dropped — `run`'s own\n * guard subsumes the per-handler `if (signingIn) return` patterns.\n *\n * **Diff from `useMutation`:** the function being driven is passed per-\n * call to `run`, not bound at hook setup (`mutationFn`). This is\n * deliberate — the widget reuses a single machine instance across\n * several handlers (one popover surfaces a single `pending` + `error`\n * at a time), so binding a single mutation function at the hook would\n * force per-handler instances and a `pending`/`error` aggregator in the\n * popover. Per-call binding preserves the shared-instance pattern while\n * still giving each invocation its own lifecycle callbacks.\n *\n * **Skipped from `useMutation`:** built-in `retry` (the widget's two\n * retry loops own bespoke timing), separate `mutate` vs `mutateAsync`\n * (`run` already returns a Promise; not awaiting it is fire-and-forget),\n * `variables` / `submittedAt` persistence (handlers know their own\n * args), `onMutate` rollback context (Convex subscriptions are the\n * authoritative cache, so we don't optimistic-update).\n */\n\nimport { useCallback, useRef } from 'preact/hooks'\n\nimport { defineMachine, useMachine } from './machine'\n\nexport type AsyncActionState<T> =\n | { kind: 'idle' }\n | { kind: 'pending' }\n | { kind: 'success'; data: T }\n | { kind: 'error'; message: string }\n\ntype AsyncActionEvent =\n | { type: 'start' }\n | { type: 'success'; data: unknown }\n | { type: 'failure'; message: string }\n | { type: 'reset' }\n\n// Internally typed against `unknown` data so a single machine instance\n// can back any per-hook `T`. The transitions themselves never read\n// `data` as a typed value — they just shuttle it through to the\n// `success` variant — so the cast at the hook boundary is sound.\nconst machine = defineMachine<AsyncActionState<unknown>, AsyncActionEvent>({\n idle: {\n start: () => ({ kind: 'pending' }),\n },\n pending: {\n success: (_, e) => ({ kind: 'success', data: e.data }),\n failure: (_, e) => ({ kind: 'error', message: e.message }),\n },\n success: {\n // A fresh `run()` from `success` flows through `pending` again —\n // the previous data is dropped at that point, matching `useMutation`.\n start: () => ({ kind: 'pending' }),\n reset: () => ({ kind: 'idle' }),\n },\n error: {\n start: () => ({ kind: 'pending' }),\n reset: () => ({ kind: 'idle' }),\n },\n})\n\nexport interface RunOptions<T> {\n /**\n * Re-throw the original error after the failure transition. Used by\n * handlers whose parent UI needs to react to the failure (e.g.,\n * keeping an edit form open on save error).\n */\n rethrow?: boolean\n /** Fires after the success transition, with the resolved value. */\n onSuccess?: (data: T) => void\n /** Fires after the failure transition, with the surfaced message. */\n onError?: (message: string) => void\n /** Fires after either branch — equivalent to a `finally`. */\n onSettled?: () => void\n}\n\nexport interface UseAsyncActionResult<T> {\n state: AsyncActionState<T>\n isIdle: boolean\n isPending: boolean\n isSuccess: boolean\n isError: boolean\n /** Resolved value of the most recent successful run, else `undefined`. */\n data: T | undefined\n /** Message from the most recent failure, else `undefined`. */\n error: string | undefined\n /**\n * Execute an async function under the machine. Transitions: idle /\n * success / error → pending; on resolve → success { data }; on reject\n * → error { message }. Returns the resolved value, or `undefined` if\n * `fn` threw (and `rethrow` was not set) or the call was a re-entrant\n * no-op while already pending.\n */\n run: (fn: () => Promise<T>, options?: RunOptions<T>) => Promise<T | undefined>\n /** Force back to `idle`, dropping any data or error message. */\n reset: () => void\n}\n\nexport function useAsyncAction<T = unknown>(): UseAsyncActionResult<T> {\n const [stateAny, send] = useMachine(machine, { kind: 'idle' })\n const state = stateAny as AsyncActionState<T>\n\n // The pending guard reads through a ref so a re-entrant call within\n // the same render cycle (before the machine state propagates back to\n // the closure) is still caught.\n const stateRef = useRef(state)\n stateRef.current = state\n\n const run = useCallback(\n async (fn: () => Promise<T>, options?: RunOptions<T>) => {\n if (stateRef.current.kind === 'pending') return undefined\n send({ type: 'start' })\n try {\n const result = await fn()\n send({ type: 'success', data: result })\n options?.onSuccess?.(result)\n options?.onSettled?.()\n return result\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Action failed'\n send({ type: 'failure', message })\n options?.onError?.(message)\n options?.onSettled?.()\n if (options?.rethrow) throw err\n return undefined\n }\n },\n [send],\n )\n\n const reset = useCallback(() => send({ type: 'reset' }), [send])\n\n return {\n state,\n isIdle: state.kind === 'idle',\n isPending: state.kind === 'pending',\n isSuccess: state.kind === 'success',\n isError: state.kind === 'error',\n data: state.kind === 'success' ? state.data : undefined,\n error: state.kind === 'error' ? state.message : undefined,\n run,\n reset,\n }\n}\n","// License: MIT\n// Author: Anton Medvedev <anton@medv.io>\n// Source: https://github.com/antonmedv/finder\nconst acceptedAttrNames = new Set(['role', 'name', 'aria-label', 'rel', 'href']);\n/** Check if attribute name and value are word-like. */\nexport function attr(name, value) {\n let nameIsOk = acceptedAttrNames.has(name);\n nameIsOk ||= name.startsWith('data-') && wordLike(name);\n let valueIsOk = wordLike(value) && value.length < 100;\n valueIsOk ||= value.startsWith('#') && wordLike(value.slice(1));\n return nameIsOk && valueIsOk;\n}\n/** Check if id name is word-like. */\nexport function idName(name) {\n return wordLike(name);\n}\n/** Check if class name is word-like. */\nexport function className(name) {\n return wordLike(name);\n}\n/** Check if tag name is word-like. */\nexport function tagName(name) {\n return true;\n}\n/** Finds unique CSS selectors for the given element. */\nexport function finder(input, options) {\n if (input.nodeType !== Node.ELEMENT_NODE) {\n throw new Error(`Can't generate CSS selector for non-element node type.`);\n }\n if (input.tagName.toLowerCase() === 'html') {\n return 'html';\n }\n const defaults = {\n root: document.body,\n idName: idName,\n className: className,\n tagName: tagName,\n attr: attr,\n timeoutMs: 1000,\n seedMinLength: 3,\n optimizedMinLength: 2,\n maxNumberOfPathChecks: Infinity,\n };\n const startTime = new Date();\n const config = { ...defaults, ...options };\n const rootDocument = findRootDocument(config.root, defaults);\n let foundPath;\n let count = 0;\n for (const candidate of search(input, config, rootDocument)) {\n const elapsedTimeMs = new Date().getTime() - startTime.getTime();\n if (elapsedTimeMs > config.timeoutMs ||\n count >= config.maxNumberOfPathChecks) {\n const fPath = fallback(input, rootDocument);\n if (!fPath) {\n throw new Error(`Timeout: Can't find a unique selector after ${config.timeoutMs}ms`);\n }\n return selector(fPath);\n }\n count++;\n if (unique(candidate, rootDocument)) {\n foundPath = candidate;\n break;\n }\n }\n if (!foundPath) {\n throw new Error(`Selector was not found.`);\n }\n const optimized = [\n ...optimize(foundPath, input, config, rootDocument, startTime),\n ];\n optimized.sort(byPenalty);\n if (optimized.length > 0) {\n return selector(optimized[0]);\n }\n return selector(foundPath);\n}\nfunction* search(input, config, rootDocument) {\n const stack = [];\n let paths = [];\n let current = input;\n let i = 0;\n while (current && current !== rootDocument) {\n const level = tie(current, config);\n for (const node of level) {\n node.level = i;\n }\n stack.push(level);\n current = current.parentElement;\n i++;\n paths.push(...combinations(stack));\n if (i >= config.seedMinLength) {\n paths.sort(byPenalty);\n for (const candidate of paths) {\n yield candidate;\n }\n paths = [];\n }\n }\n paths.sort(byPenalty);\n for (const candidate of paths) {\n yield candidate;\n }\n}\nfunction wordLike(name) {\n if (/^[a-z\\-]{3,}$/i.test(name)) {\n const words = name.split(/-|[A-Z]/);\n for (const word of words) {\n if (word.length <= 2) {\n return false;\n }\n if (/[^aeiou]{4,}/i.test(word)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\nfunction tie(element, config) {\n const level = [];\n const elementId = element.getAttribute('id');\n if (elementId && config.idName(elementId)) {\n level.push({\n name: '#' + CSS.escape(elementId),\n penalty: 0,\n });\n }\n for (let i = 0; i < element.classList.length; i++) {\n const name = element.classList[i];\n if (config.className(name)) {\n level.push({\n name: '.' + CSS.escape(name),\n penalty: 1,\n });\n }\n }\n for (let i = 0; i < element.attributes.length; i++) {\n const attr = element.attributes[i];\n if (config.attr(attr.name, attr.value)) {\n level.push({\n name: `[${CSS.escape(attr.name)}=\"${CSS.escape(attr.value)}\"]`,\n penalty: 2,\n });\n }\n }\n const tagName = element.tagName.toLowerCase();\n if (config.tagName(tagName)) {\n level.push({\n name: tagName,\n penalty: 5,\n });\n const index = indexOf(element, tagName);\n if (index !== undefined) {\n level.push({\n name: nthOfType(tagName, index),\n penalty: 10,\n });\n }\n }\n const nth = indexOf(element);\n if (nth !== undefined) {\n level.push({\n name: nthChild(tagName, nth),\n penalty: 50,\n });\n }\n return level;\n}\nfunction selector(path) {\n let node = path[0];\n let query = node.name;\n for (let i = 1; i < path.length; i++) {\n const level = path[i].level || 0;\n if (node.level === level - 1) {\n query = `${path[i].name} > ${query}`;\n }\n else {\n query = `${path[i].name} ${query}`;\n }\n node = path[i];\n }\n return query;\n}\nfunction penalty(path) {\n return path.map((node) => node.penalty).reduce((acc, i) => acc + i, 0);\n}\nfunction byPenalty(a, b) {\n return penalty(a) - penalty(b);\n}\nfunction indexOf(input, tagName) {\n const parent = input.parentNode;\n if (!parent) {\n return undefined;\n }\n let child = parent.firstChild;\n if (!child) {\n return undefined;\n }\n let i = 0;\n while (child) {\n if (child.nodeType === Node.ELEMENT_NODE &&\n (tagName === undefined ||\n child.tagName.toLowerCase() === tagName)) {\n i++;\n }\n if (child === input) {\n break;\n }\n child = child.nextSibling;\n }\n return i;\n}\nfunction fallback(input, rootDocument) {\n let i = 0;\n let current = input;\n const path = [];\n while (current && current !== rootDocument) {\n const tagName = current.tagName.toLowerCase();\n const index = indexOf(current, tagName);\n if (index === undefined) {\n return;\n }\n path.push({\n name: nthOfType(tagName, index),\n penalty: NaN,\n level: i,\n });\n current = current.parentElement;\n i++;\n }\n if (unique(path, rootDocument)) {\n return path;\n }\n}\nfunction nthChild(tagName, index) {\n if (tagName === 'html') {\n return 'html';\n }\n return `${tagName}:nth-child(${index})`;\n}\nfunction nthOfType(tagName, index) {\n if (tagName === 'html') {\n return 'html';\n }\n return `${tagName}:nth-of-type(${index})`;\n}\nfunction* combinations(stack, path = []) {\n if (stack.length > 0) {\n for (let node of stack[0]) {\n yield* combinations(stack.slice(1, stack.length), path.concat(node));\n }\n }\n else {\n yield path;\n }\n}\nfunction findRootDocument(rootNode, defaults) {\n if (rootNode.nodeType === Node.DOCUMENT_NODE) {\n return rootNode;\n }\n if (rootNode === defaults.root) {\n return rootNode.ownerDocument;\n }\n return rootNode;\n}\nfunction unique(path, rootDocument) {\n const css = selector(path);\n switch (rootDocument.querySelectorAll(css).length) {\n case 0:\n throw new Error(`Can't select any node with this selector: ${css}`);\n case 1:\n return true;\n default:\n return false;\n }\n}\nfunction* optimize(path, input, config, rootDocument, startTime) {\n if (path.length > 2 && path.length > config.optimizedMinLength) {\n for (let i = 1; i < path.length - 1; i++) {\n const elapsedTimeMs = new Date().getTime() - startTime.getTime();\n if (elapsedTimeMs > config.timeoutMs) {\n return;\n }\n const newPath = [...path];\n newPath.splice(i, 1);\n if (unique(newPath, rootDocument) &&\n rootDocument.querySelector(selector(newPath)) === input) {\n yield newPath;\n yield* optimize(newPath, input, config, rootDocument, startTime);\n }\n }\n }\n}\n","/**\n * Anchor coordinate helpers.\n *\n * Pins are stored as 0..1 fractions of the page's content size (doc width\n * and height) plus a viewport-width snapshot. That lets us re-render them\n * roughly in place across responsive layouts. We also capture a CSS selector\n * for the element under the click so we can re-anchor exactly if the layout\n * reflowed.\n */\n\nimport { finder } from '@medv/finder'\n\nexport type PageCoords = {\n /** Fraction 0..1 of document.documentElement.scrollWidth */\n anchorX: number\n /** Fraction 0..1 of document.documentElement.scrollHeight */\n anchorY: number\n viewportW: number\n viewportY: number\n anchorSelector?: string\n /** Fraction 0..1 of the anchored element's width at click point */\n anchorOffsetX?: number\n /** Fraction 0..1 of the anchored element's height at click point */\n anchorOffsetY?: number\n}\n\nexport type ScreenPoint = {\n /** Pixel position relative to the document (page coords, includes scroll) */\n pageX: number\n pageY: number\n /**\n * `true` when the stored selector matched a live element and the\n * returned coordinates reflect that element's current rect. `false`\n * when we fell through to the fraction-based fallback — used by\n * callers to render a tentative-state cue and to know that retrying\n * later (e.g. after DOM mutations) may yield a better position.\n */\n resolved: boolean\n}\n\n/**\n * Convert a click event into normalised page coordinates.\n * Pass `target` explicitly when `event.target` is not the real page element\n * (e.g. when an overlay is intercepting the click).\n */\nexport function toPageCoords(event: MouseEvent, target?: Element | null): PageCoords {\n const docEl = document.documentElement\n const docW = Math.max(docEl.scrollWidth, docEl.clientWidth)\n const docH = Math.max(docEl.scrollHeight, docEl.clientHeight)\n\n const pageX = event.clientX + window.scrollX\n const pageY = event.clientY + window.scrollY\n\n const resolvedTarget =\n target !== undefined ? target : event.target instanceof Element ? event.target : null\n const selector = resolvedTarget ? elementSelector(resolvedTarget) : undefined\n\n let anchorOffsetX: number | undefined\n let anchorOffsetY: number | undefined\n if (resolvedTarget) {\n const rect = resolvedTarget.getBoundingClientRect()\n if (rect.width > 0 && rect.height > 0) {\n anchorOffsetX = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width))\n anchorOffsetY = Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height))\n }\n }\n\n return {\n anchorX: docW > 0 ? pageX / docW : 0,\n anchorY: docH > 0 ? pageY / docH : 0,\n viewportW: window.innerWidth,\n viewportY: window.innerHeight,\n anchorSelector: selector,\n anchorOffsetX,\n anchorOffsetY,\n }\n}\n\n/**\n * Resolve stored anchor coordinates into current page-space pixel positions.\n * If a selector is stored and still resolves, we use its center; otherwise\n * we fall back to the fraction × current document size.\n */\nexport function resolveCoords(c: {\n anchorX: number\n anchorY: number\n anchorSelector?: string\n anchorOffsetX?: number\n anchorOffsetY?: number\n}): ScreenPoint {\n if (c.anchorSelector) {\n try {\n const el = document.querySelector(c.anchorSelector)\n if (el) {\n const rect = el.getBoundingClientRect()\n return {\n pageX: rect.left + window.scrollX + (c.anchorOffsetX ?? 0.5) * rect.width,\n pageY: rect.top + window.scrollY + (c.anchorOffsetY ?? 0.5) * rect.height,\n resolved: true,\n }\n }\n } catch {\n // bad selector — fall through to fraction math\n }\n }\n\n const docEl = document.documentElement\n const docW = Math.max(docEl.scrollWidth, docEl.clientWidth)\n const docH = Math.max(docEl.scrollHeight, docEl.clientHeight)\n return {\n pageX: c.anchorX * docW,\n pageY: c.anchorY * docH,\n resolved: false,\n }\n}\n\nfunction elementSelector(el: Element): string | undefined {\n try {\n return finder(el, { timeoutMs: 1000 })\n } catch {\n return undefined\n }\n}\n","/**\n * Thin fetch wrappers for the /widget/* endpoints. Stays JSON in / JSON out\n * and raises a typed error on any non-2xx so the UI can render a single\n * \"something went wrong\" path.\n */\n\nexport type WidgetThread = {\n _id: string\n url: string\n route: string\n anchorSelector?: string\n anchorX: number\n anchorY: number\n anchorOffsetX?: number\n anchorOffsetY?: number\n viewportW: number\n viewportY: number\n authorName: string\n authorClientId: string\n createdAt: number\n resolvedAt?: number\n screenshotUrl?: string\n comments: Array<{\n _id: string\n body: string\n authorName: string\n /** Widget identity that authored this comment (undefined for dashboard replies). */\n authorClientId?: string\n fromDashboard: boolean\n createdAt: number\n editedAt?: number\n /** True for soft-deleted comments; `body` is blanked server-side. */\n deleted: boolean\n /**\n * One entry per emoji that has at least one reactor on this comment.\n * Sorted server-side by the fixed palette order so chips render\n * stably left-to-right. `mine` reflects the calling identity, so an\n * optimistic toggle must update both `count` and `mine` together.\n * `reactors` are display names in chronological order; the viewer's\n * own entry is replaced with \"you\" client-side.\n */\n reactions: Array<{ emoji: string; count: number; mine: boolean; reactors: string[] }>\n }>\n}\n\nexport type CreateThreadPayload = {\n url: string\n route: string\n anchorSelector?: string\n anchorX: number\n anchorY: number\n anchorOffsetX?: number\n anchorOffsetY?: number\n viewportW: number\n viewportY: number\n userAgent: string\n authorName: string\n authorEmail?: string\n body: string\n screenshotStorageId?: string\n}\n\nexport type AddCommentPayload = {\n body: string\n authorName: string\n authorEmail?: string\n}\n\nexport type EditCommentPayload = {\n body: string\n}\n\nexport class WidgetApiError extends Error {\n status: number\n constructor(message: string, status: number) {\n super(message)\n this.name = 'WidgetApiError'\n this.status = status\n }\n}\n\nexport type WidgetApiClient = ReturnType<typeof createApiClient>\n\nexport interface CreateApiClientOpts {\n apiUrl: string\n apiKey: string\n /**\n * Returns the current verified-identity JWT (or null). Called on every\n * request so the api client always reflects the freshest cached token —\n * no need to recreate the client when identity changes. Tokens with a\n * past `expiresAt` are skipped client-side; the server is the source\n * of truth and 401s anything stale that slips through.\n */\n getToken?: () => { token: string; expiresAt: number } | null\n /**\n * Returns the current anonymous-identity JWT (or null). When present,\n * the client sends it as `x-markup-anon-token` on every request. The\n * server verifies the signature and treats the embedded clientId as\n * trusted for ownership checks, sidestepping the trust-the-body\n * pattern for legacy widgets.\n */\n getAnonToken?: () => string | null\n /**\n * Invoked when the server returns 401 to a request that carried a\n * Bearer token. Lets the host clear verified identity and fall back to\n * the anon clientId path. NOT called for 401s on requests sent without\n * a token (those mean the api key itself is bad).\n */\n onUnauthorized?: () => void\n}\n\nexport function createApiClient(opts: CreateApiClientOpts) {\n const baseUrl = opts.apiUrl.replace(/\\/+$/, '')\n\n async function request<T>(path: string, init: RequestInit = {}): Promise<T> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'x-markup-api-key': opts.apiKey,\n ...((init.headers ?? {}) as Record<string, string>),\n }\n\n const cached = opts.getToken?.() ?? null\n const sentBearer = cached != null && cached.token.length > 0 && cached.expiresAt > Date.now()\n if (sentBearer && cached) {\n headers['authorization'] = `Bearer ${cached.token}`\n }\n\n const anon = opts.getAnonToken?.() ?? null\n if (anon) {\n headers['x-markup-anon-token'] = anon\n }\n\n const res = await fetch(`${baseUrl}${path}`, { ...init, headers })\n const text = await res.text()\n const data = text ? safeJson(text) : null\n if (!res.ok) {\n if (res.status === 401 && sentBearer) {\n opts.onUnauthorized?.()\n }\n const message =\n (data && typeof data === 'object' && 'error' in data && typeof data.error === 'string'\n ? data.error\n : null) ?? `Request failed with ${res.status}`\n throw new WidgetApiError(message, res.status)\n }\n return data as T\n }\n\n return {\n mintAnonIdentity(): Promise<{ clientId: string; token: string; expiresAt: number }> {\n return request<{ clientId: string; token: string; expiresAt: number }>(\n '/widget/anon-identity',\n { method: 'POST' },\n )\n },\n getSubscriptionToken(): Promise<{ token: string; expiresAt: number }> {\n return request<{ token: string; expiresAt: number }>('/widget/subscription-token', {\n method: 'POST',\n })\n },\n getScreenshotUploadUrl(): Promise<{ uploadUrl: string }> {\n return request<{ uploadUrl: string }>('/widget/screenshots/upload-url', { method: 'POST' })\n },\n listThreads(route: string): Promise<{ threads: WidgetThread[] }> {\n return request<{ threads: WidgetThread[] }>(\n `/widget/threads?route=${encodeURIComponent(route)}`,\n { method: 'GET' },\n )\n },\n createThread(payload: CreateThreadPayload): Promise<{ thread: WidgetThread }> {\n return request<{ thread: WidgetThread }>(`/widget/threads`, {\n method: 'POST',\n body: JSON.stringify(payload),\n })\n },\n deleteThread(threadId: string): Promise<void> {\n return request<void>(`/widget/threads/${encodeURIComponent(threadId)}`, {\n method: 'DELETE',\n })\n },\n resolveThread(threadId: string, resolvedBy?: string): Promise<void> {\n return request<void>(`/widget/threads/${encodeURIComponent(threadId)}`, {\n method: 'PATCH',\n body: JSON.stringify({ resolvedBy }),\n })\n },\n addComment(threadId: string, payload: AddCommentPayload): Promise<{ thread: WidgetThread }> {\n return request<{ thread: WidgetThread }>(\n `/widget/threads/${encodeURIComponent(threadId)}/comments`,\n {\n method: 'POST',\n body: JSON.stringify(payload),\n },\n )\n },\n editComment(\n threadId: string,\n commentId: string,\n payload: EditCommentPayload,\n ): Promise<{ thread: WidgetThread }> {\n return request<{ thread: WidgetThread }>(\n `/widget/threads/${encodeURIComponent(threadId)}/comments/${encodeURIComponent(commentId)}`,\n {\n method: 'PATCH',\n body: JSON.stringify(payload),\n },\n )\n },\n deleteComment(threadId: string, commentId: string): Promise<{ thread: WidgetThread }> {\n return request<{ thread: WidgetThread }>(\n `/widget/threads/${encodeURIComponent(threadId)}/comments/${encodeURIComponent(commentId)}`,\n { method: 'DELETE' },\n )\n },\n toggleReaction(\n commentId: string,\n payload: { emoji: string; authorName?: string },\n ): Promise<{ thread: WidgetThread }> {\n return request<{ thread: WidgetThread }>(\n `/widget/comments/${encodeURIComponent(commentId)}/reactions`,\n {\n method: 'POST',\n body: JSON.stringify(payload),\n },\n )\n },\n }\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return null\n }\n}\n","type Listener = () => void\n\nconst PATCHED_MARKER = '__markup_history_observer__'\nconst LISTENERS_KEY = '__markup_history_listeners__'\n\nfunction dispatch(listeners: Set<Listener>) {\n listeners.forEach((fn) => fn())\n}\n\nfunction install(): Set<Listener> {\n const push = history.pushState as typeof history.pushState & {\n [PATCHED_MARKER]?: number\n [LISTENERS_KEY]?: Set<Listener>\n }\n\n // Already patched — reuse the existing listener set (survives HMR\n // module re-imports because the set lives on the wrapper itself).\n if (push[PATCHED_MARKER]) {\n return push[LISTENERS_KEY]!\n }\n\n const listeners = new Set<Listener>()\n\n const origPush = history.pushState\n const origReplace = history.replaceState\n\n function wrappedPush(this: History, ...args: Parameters<typeof History.prototype.pushState>) {\n origPush.apply(this, args)\n dispatch(listeners)\n }\n function wrappedReplace(\n this: History,\n ...args: Parameters<typeof History.prototype.replaceState>\n ) {\n origReplace.apply(this, args)\n dispatch(listeners)\n }\n\n Object.defineProperty(wrappedPush, PATCHED_MARKER, { value: 1 })\n Object.defineProperty(wrappedPush, LISTENERS_KEY, { value: listeners })\n Object.defineProperty(wrappedReplace, PATCHED_MARKER, { value: 1 })\n\n history.pushState = wrappedPush\n history.replaceState = wrappedReplace\n\n window.addEventListener('popstate', () => dispatch(listeners))\n\n return listeners\n}\n\n// Module-scoped handle. Set on first subscribeToRouteChanges() call.\n// On HMR re-import this is null again, but install() short-circuits and\n// returns the same Set that is stored on the tagged wrapper.\nlet _listeners: Set<Listener> | null = null\n\n/**\n * Subscribe `listener` to every pushState, replaceState, and popstate\n * navigation. Returns an unsubscribe function.\n *\n * The history wrappers are installed at most once per page lifetime —\n * subsequent init() → destroy() → init() cycles add/remove only from\n * the listener set without stacking new wrappers.\n */\nexport function subscribeToRouteChanges(listener: Listener): () => void {\n if (!_listeners) {\n _listeners = install()\n }\n _listeners.add(listener)\n return () => _listeners!.delete(listener)\n}\n","/**\n * Identity persistence in the widget host page's own localStorage.\n *\n * Earlier versions used a cross-origin iframe pointing at the convex.site\n * deployment so identity could be shared across every host. That doesn't work\n * any more — modern browsers partition third-party storage per top-level\n * site, so each host had its own bucket anyway. We now embrace that: store\n * identity directly on the host page. Verified identity flows in via the\n * `/widget/auth` popup flow (one-click sign-in per host); anon identity is\n * minted server-side on first need.\n *\n * The runtime state is a discriminated `IdentityState` union; the on-disk\n * shape is a flat record loose enough to accept legacy data from prior\n * widget versions. Translation happens in `loadIdentity` / `saveIdentity`.\n */\n\n/** Anonymous identity, bound to a server-issued JWT for the deployment. */\nexport interface AnonIdentity {\n clientId: string\n /**\n * Server-signed JWT binding this anonymous `clientId` to the deployment.\n * Sent as `x-markup-anon-token` so ownership checks for anon comments\n * verify the clientId server-side instead of trusting the request body.\n * Tampering with `clientId` in localStorage invalidates the signature.\n */\n anonToken: string\n name?: string\n email?: string\n}\n\n/** Verified identity, bound to a popup-signed user JWT. */\nexport interface VerifiedIdentity {\n /** Always `markup_user_<sub>` for the JWT's subject. */\n clientId: string\n /**\n * Server-signed JWT proving this identity. Attached as\n * `Authorization: Bearer` on writes. ~7-day TTL with no silent refresh,\n * so a 401 should transition state to `recovering` and trigger an\n * anon mint.\n */\n token: string\n /** Epoch milliseconds when the JWT stops being valid. */\n tokenExpiresAt: number\n name: string\n email?: string\n}\n\n/**\n * Runtime state machine for the widget identity:\n *\n * - `unresolved`: first-load anon mint is pending.\n * - `anon`: anon mint succeeded; `clientId` and `anonToken` are valid.\n * - `verified`: popup sign-in succeeded; `token` is the active Bearer.\n * - `recovering`: a verified session just 401'd. The anon mint is\n * pending again. `preserved` carries the user's display fields so\n * the next mint can roundtrip name/email without re-prompting.\n *\n * `unresolved` and `recovering` look the same to the UI today (both\n * surface as `connecting` on the author prompt) but they're distinct in\n * the type system so a future \"Reconnecting as Alice…\" UX has a slot\n * for it.\n */\nexport type IdentityState =\n | { kind: 'unresolved' }\n | { kind: 'anon'; identity: AnonIdentity }\n | { kind: 'verified'; identity: VerifiedIdentity }\n | { kind: 'recovering'; preserved: { name?: string; email?: string } }\n\n/**\n * On-disk shape. Loose because we accept legacy records: prior widget\n * versions wrote a flat record with optional fields, and a session in\n * recovery was persisted as `{clientId, name, email}` with neither token.\n */\ninterface StoredShape {\n clientId?: string\n name?: string\n email?: string\n isVerified?: boolean\n token?: string\n tokenExpiresAt?: number\n anonToken?: string\n}\n\nconst KEY = 'markup.identity'\n\nfunction readStored(): StoredShape | null {\n try {\n const raw = localStorage.getItem(KEY)\n return raw ? (JSON.parse(raw) as StoredShape) : null\n } catch {\n return null\n }\n}\n\nfunction writeStored(stored: StoredShape | null): void {\n try {\n if (stored == null) {\n localStorage.removeItem(KEY)\n return\n }\n localStorage.setItem(KEY, JSON.stringify(stored))\n } catch {\n /* storage disabled (private mode quota) — identity stays in-memory only */\n }\n}\n\n/**\n * Translate the persisted record (if any) into a runtime state.\n *\n * Returns `preserved` separately so a subsequent anon mint can carry the\n * user's display fields forward even when the persisted record didn't\n * include a usable identity (e.g., the recovery snapshot from a prior\n * 401).\n */\nexport function loadIdentity(): {\n state: IdentityState\n preserved: { name?: string; email?: string }\n} {\n const stored = readStored()\n const preserved = { name: stored?.name, email: stored?.email }\n if (!stored) return { state: { kind: 'unresolved' }, preserved }\n\n if (\n stored.isVerified &&\n typeof stored.clientId === 'string' &&\n typeof stored.token === 'string' &&\n typeof stored.tokenExpiresAt === 'number' &&\n typeof stored.name === 'string' &&\n // Don't surface a token the server will reject on the first write.\n // The server is the source of truth here (signature + revocation),\n // but matching its expiry locally avoids the UI flashing \"signed\n // in\" until the first 401 lands. A stale verified record falls\n // back to `unresolved` and the widget mints a fresh anon identity.\n stored.tokenExpiresAt > Date.now()\n ) {\n return {\n state: {\n kind: 'verified',\n identity: {\n clientId: stored.clientId,\n token: stored.token,\n tokenExpiresAt: stored.tokenExpiresAt,\n name: stored.name,\n email: stored.email,\n },\n },\n preserved,\n }\n }\n\n if (typeof stored.clientId === 'string' && typeof stored.anonToken === 'string') {\n return {\n state: {\n kind: 'anon',\n identity: {\n clientId: stored.clientId,\n anonToken: stored.anonToken,\n name: stored.name,\n email: stored.email,\n },\n },\n preserved,\n }\n }\n\n // Has display fields but no signed token. Caller mints to recover.\n return { state: { kind: 'unresolved' }, preserved }\n}\n\n/**\n * Persist the runtime state. The transient states (`unresolved`,\n * `recovering`) drop the signed-identity fields; `recovering` keeps\n * `preserved` so the next mint can carry name/email forward.\n */\nexport function saveIdentity(state: IdentityState): void {\n switch (state.kind) {\n case 'verified':\n writeStored({\n clientId: state.identity.clientId,\n token: state.identity.token,\n tokenExpiresAt: state.identity.tokenExpiresAt,\n isVerified: true,\n name: state.identity.name,\n email: state.identity.email,\n })\n return\n case 'anon':\n writeStored({\n clientId: state.identity.clientId,\n anonToken: state.identity.anonToken,\n name: state.identity.name,\n email: state.identity.email,\n })\n return\n case 'recovering':\n // No identity to persist, just the display fields. clientId is\n // intentionally omitted — the next anon mint replaces it anyway.\n writeStored({\n name: state.preserved.name,\n email: state.preserved.email,\n })\n return\n case 'unresolved':\n writeStored(null)\n return\n }\n}\n\n/**\n * Convenience: the active widget clientId, regardless of identity flavor.\n * Returns `undefined` for `unresolved` / `recovering`.\n */\nexport function clientIdOf(state: IdentityState): string | undefined {\n if (state.kind === 'anon') return state.identity.clientId\n if (state.kind === 'verified') return state.identity.clientId\n return undefined\n}\n\n/**\n * Convenience: the active display name, or null when none is set.\n * Verified identities always have a name; anon may not until the user\n * fills in the author prompt.\n */\nexport function displayNameOf(state: IdentityState): string | null {\n if (state.kind === 'anon') return state.identity.name ?? null\n if (state.kind === 'verified') return state.identity.name\n return null\n}\n\n/**\n * Convenience: read the author display fields for write paths. Returns\n * `null` when the identity has no usable display name (unresolved /\n * recovering, or an anon identity whose user hasn't filled in the\n * prompt yet) — callers should bail in that case since the server\n * requires a name on the post.\n */\nexport function authorFieldsOf(\n state: IdentityState,\n): { name: string; email: string | undefined } | null {\n if (state.kind === 'anon') {\n const name = state.identity.name\n if (!name) return null\n return { name, email: state.identity.email }\n }\n if (state.kind === 'verified') {\n return { name: state.identity.name, email: state.identity.email }\n }\n return null\n}\n","/** Shape of the identity the `/widget/auth` popup posts back. */\nexport interface PopupIdentity {\n id: string\n name: string\n email?: string\n}\n\n/**\n * What the popup resolves with — the user identity plus a server-signed\n * JWT the widget will pass as `Authorization: Bearer` on writes so the\n * server can verify the userId rather than trusting `authorClientId` from\n * the request body.\n *\n * `token`/`tokenExpiresAt` are technically optional for backwards-compat,\n * but a recent deployment will always include them. Treat null as \"no\n * verified token; behave as anonymous\" rather than failing.\n */\nexport interface PopupResult {\n identity: PopupIdentity\n token: string | null\n /** Epoch milliseconds when the JWT stops being valid. */\n tokenExpiresAt: number | null\n}\n\n/**\n * Open `${apiUrl}/widget/auth` in a popup and resolve with the verified\n * identity (plus JWT) once the popup posts back. The popup is first-party\n * to the deployment origin, so the better-auth session cookie IS sent —\n * which is the whole reason this works where the cross-origin iframe\n * approach didn't.\n *\n * The apiKey never appears in the popup URL: the host page first POSTs\n * to `/widget/popup-exchange` (validated against the apiKey + Origin\n * gate) and gets back a single-use 60-second code that's safe to embed\n * in a URL the browser will record in history / send as Referer.\n *\n * Resolves with the identity, rejects if the user closes the popup or the\n * browser blocks it.\n */\nexport async function signInWithPopup(apiUrl: string, apiKey: string): Promise<PopupResult> {\n const sessionOrigin = new URL(apiUrl).origin\n\n let popupUrl: string\n try {\n const exchangeRes = await fetch(`${apiUrl.replace(/\\/+$/, '')}/widget/popup-exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'x-markup-api-key': apiKey },\n body: '{}',\n })\n if (!exchangeRes.ok) {\n throw new Error(`popup-exchange responded with ${exchangeRes.status}`)\n }\n const { code } = (await exchangeRes.json()) as { code: string }\n const url = new URL('/widget/auth', apiUrl)\n url.searchParams.set('code', code)\n popupUrl = url.toString()\n } catch (err) {\n return Promise.reject(err instanceof Error ? err : new Error('Failed to start popup exchange'))\n }\n\n const w = 420\n const h = 560\n const left = Math.max(0, window.screenX + (window.outerWidth - w) / 2)\n const top = Math.max(0, window.screenY + (window.outerHeight - h) / 2)\n\n const popup = window.open(\n popupUrl,\n 'markup-auth',\n `width=${w},height=${h},left=${left},top=${top}`,\n )\n if (!popup) {\n return Promise.reject(new Error('Popup blocked — allow popups for this site to sign in'))\n }\n\n // Hard ceiling: if a popup loads a broken page that never posts back\n // and the user leaves it open in a background tab, the message\n // listener and close-watch interval would run forever. Each retry\n // would stack another pair. Fail hard after a few minutes so any\n // listener/timer leak is bounded.\n const TIMEOUT_MS = 5 * 60 * 1000\n\n return new Promise((resolve, reject) => {\n function cleanup() {\n window.removeEventListener('message', onMessage)\n clearInterval(closeWatch)\n clearTimeout(timeoutId)\n }\n function onMessage(e: MessageEvent) {\n if (e.origin !== sessionOrigin) return\n // Defense-in-depth: the message must come from the popup we opened.\n // Origin alone would still accept a postMessage from any other window\n // running on the deployment origin (e.g. a stale dashboard tab).\n if (e.source !== popup) return\n const d = e.data as {\n type?: string\n identity?: PopupIdentity\n token?: string | null\n tokenExpiresAt?: number | null\n }\n if (d?.type !== 'MARKUP_AUTH_RESULT') return\n cleanup()\n if (d.identity?.id && d.identity?.name) {\n resolve({\n identity: d.identity,\n token: typeof d.token === 'string' ? d.token : null,\n tokenExpiresAt: typeof d.tokenExpiresAt === 'number' ? d.tokenExpiresAt : null,\n })\n } else {\n reject(new Error('Sign-in cancelled'))\n }\n }\n const closeWatch = window.setInterval(() => {\n if (popup.closed) {\n cleanup()\n reject(new Error('Sign-in cancelled'))\n }\n }, 500)\n const timeoutId = window.setTimeout(() => {\n cleanup()\n reject(new Error('Sign-in timed out'))\n }, TIMEOUT_MS)\n window.addEventListener('message', onMessage)\n })\n}\n","export function resolveUrl(url, baseUrl) {\n // url is absolute already\n if (url.match(/^[a-z]+:\\/\\//i)) {\n return url;\n }\n // url is absolute already, without protocol\n if (url.match(/^\\/\\//)) {\n return window.location.protocol + url;\n }\n // dataURI, mailto:, tel:, etc.\n if (url.match(/^[a-z]+:/i)) {\n return url;\n }\n const doc = document.implementation.createHTMLDocument();\n const base = doc.createElement('base');\n const a = doc.createElement('a');\n doc.head.appendChild(base);\n doc.body.appendChild(a);\n if (baseUrl) {\n base.href = baseUrl;\n }\n a.href = url;\n return a.href;\n}\nexport const uuid = (() => {\n // generate uuid for className of pseudo elements.\n // We should not use GUIDs, otherwise pseudo elements sometimes cannot be captured.\n let counter = 0;\n // ref: http://stackoverflow.com/a/6248722/2519373\n const random = () => \n // eslint-disable-next-line no-bitwise\n `0000${((Math.random() * 36 ** 4) << 0).toString(36)}`.slice(-4);\n return () => {\n counter += 1;\n return `u${random()}${counter}`;\n };\n})();\nexport function delay(ms) {\n return (args) => new Promise((resolve) => {\n setTimeout(() => resolve(args), ms);\n });\n}\nexport function toArray(arrayLike) {\n const arr = [];\n for (let i = 0, l = arrayLike.length; i < l; i++) {\n arr.push(arrayLike[i]);\n }\n return arr;\n}\nlet styleProps = null;\nexport function getStyleProperties(options = {}) {\n if (styleProps) {\n return styleProps;\n }\n if (options.includeStyleProperties) {\n styleProps = options.includeStyleProperties;\n return styleProps;\n }\n styleProps = toArray(window.getComputedStyle(document.documentElement));\n return styleProps;\n}\nfunction px(node, styleProperty) {\n const win = node.ownerDocument.defaultView || window;\n const val = win.getComputedStyle(node).getPropertyValue(styleProperty);\n return val ? parseFloat(val.replace('px', '')) : 0;\n}\nfunction getNodeWidth(node) {\n const leftBorder = px(node, 'border-left-width');\n const rightBorder = px(node, 'border-right-width');\n return node.clientWidth + leftBorder + rightBorder;\n}\nfunction getNodeHeight(node) {\n const topBorder = px(node, 'border-top-width');\n const bottomBorder = px(node, 'border-bottom-width');\n return node.clientHeight + topBorder + bottomBorder;\n}\nexport function getImageSize(targetNode, options = {}) {\n const width = options.width || getNodeWidth(targetNode);\n const height = options.height || getNodeHeight(targetNode);\n return { width, height };\n}\nexport function getPixelRatio() {\n let ratio;\n let FINAL_PROCESS;\n try {\n FINAL_PROCESS = process;\n }\n catch (e) {\n // pass\n }\n const val = FINAL_PROCESS && FINAL_PROCESS.env\n ? FINAL_PROCESS.env.devicePixelRatio\n : null;\n if (val) {\n ratio = parseInt(val, 10);\n if (Number.isNaN(ratio)) {\n ratio = 1;\n }\n }\n return ratio || window.devicePixelRatio || 1;\n}\n// @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size\nconst canvasDimensionLimit = 16384;\nexport function checkCanvasDimensions(canvas) {\n if (canvas.width > canvasDimensionLimit ||\n canvas.height > canvasDimensionLimit) {\n if (canvas.width > canvasDimensionLimit &&\n canvas.height > canvasDimensionLimit) {\n if (canvas.width > canvas.height) {\n canvas.height *= canvasDimensionLimit / canvas.width;\n canvas.width = canvasDimensionLimit;\n }\n else {\n canvas.width *= canvasDimensionLimit / canvas.height;\n canvas.height = canvasDimensionLimit;\n }\n }\n else if (canvas.width > canvasDimensionLimit) {\n canvas.height *= canvasDimensionLimit / canvas.width;\n canvas.width = canvasDimensionLimit;\n }\n else {\n canvas.width *= canvasDimensionLimit / canvas.height;\n canvas.height = canvasDimensionLimit;\n }\n }\n}\nexport function canvasToBlob(canvas, options = {}) {\n if (canvas.toBlob) {\n return new Promise((resolve) => {\n canvas.toBlob(resolve, options.type ? options.type : 'image/png', options.quality ? options.quality : 1);\n });\n }\n return new Promise((resolve) => {\n const binaryString = window.atob(canvas\n .toDataURL(options.type ? options.type : undefined, options.quality ? options.quality : undefined)\n .split(',')[1]);\n const len = binaryString.length;\n const binaryArray = new Uint8Array(len);\n for (let i = 0; i < len; i += 1) {\n binaryArray[i] = binaryString.charCodeAt(i);\n }\n resolve(new Blob([binaryArray], {\n type: options.type ? options.type : 'image/png',\n }));\n });\n}\nexport function createImage(url) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => {\n img.decode().then(() => {\n requestAnimationFrame(() => resolve(img));\n });\n };\n img.onerror = reject;\n img.crossOrigin = 'anonymous';\n img.decoding = 'async';\n img.src = url;\n });\n}\nexport async function svgToDataURL(svg) {\n return Promise.resolve()\n .then(() => new XMLSerializer().serializeToString(svg))\n .then(encodeURIComponent)\n .then((html) => `data:image/svg+xml;charset=utf-8,${html}`);\n}\nexport async function nodeToDataURL(node, width, height) {\n const xmlns = 'http://www.w3.org/2000/svg';\n const svg = document.createElementNS(xmlns, 'svg');\n const foreignObject = document.createElementNS(xmlns, 'foreignObject');\n svg.setAttribute('width', `${width}`);\n svg.setAttribute('height', `${height}`);\n svg.setAttribute('viewBox', `0 0 ${width} ${height}`);\n foreignObject.setAttribute('width', '100%');\n foreignObject.setAttribute('height', '100%');\n foreignObject.setAttribute('x', '0');\n foreignObject.setAttribute('y', '0');\n foreignObject.setAttribute('externalResourcesRequired', 'true');\n svg.appendChild(foreignObject);\n foreignObject.appendChild(node);\n return svgToDataURL(svg);\n}\nexport const isInstanceOfElement = (node, instance) => {\n if (node instanceof instance)\n return true;\n const nodePrototype = Object.getPrototypeOf(node);\n if (nodePrototype === null)\n return false;\n return (nodePrototype.constructor.name === instance.name ||\n isInstanceOfElement(nodePrototype, instance));\n};\n//# sourceMappingURL=util.js.map","import { uuid, getStyleProperties } from './util';\nfunction formatCSSText(style) {\n const content = style.getPropertyValue('content');\n return `${style.cssText} content: '${content.replace(/'|\"/g, '')}';`;\n}\nfunction formatCSSProperties(style, options) {\n return getStyleProperties(options)\n .map((name) => {\n const value = style.getPropertyValue(name);\n const priority = style.getPropertyPriority(name);\n return `${name}: ${value}${priority ? ' !important' : ''};`;\n })\n .join(' ');\n}\nfunction getPseudoElementStyle(className, pseudo, style, options) {\n const selector = `.${className}:${pseudo}`;\n const cssText = style.cssText\n ? formatCSSText(style)\n : formatCSSProperties(style, options);\n return document.createTextNode(`${selector}{${cssText}}`);\n}\nfunction clonePseudoElement(nativeNode, clonedNode, pseudo, options) {\n const style = window.getComputedStyle(nativeNode, pseudo);\n const content = style.getPropertyValue('content');\n if (content === '' || content === 'none') {\n return;\n }\n const className = uuid();\n try {\n clonedNode.className = `${clonedNode.className} ${className}`;\n }\n catch (err) {\n return;\n }\n const styleElement = document.createElement('style');\n styleElement.appendChild(getPseudoElementStyle(className, pseudo, style, options));\n clonedNode.appendChild(styleElement);\n}\nexport function clonePseudoElements(nativeNode, clonedNode, options) {\n clonePseudoElement(nativeNode, clonedNode, ':before', options);\n clonePseudoElement(nativeNode, clonedNode, ':after', options);\n}\n//# sourceMappingURL=clone-pseudos.js.map","const WOFF = 'application/font-woff';\nconst JPEG = 'image/jpeg';\nconst mimes = {\n woff: WOFF,\n woff2: WOFF,\n ttf: 'application/font-truetype',\n eot: 'application/vnd.ms-fontobject',\n png: 'image/png',\n jpg: JPEG,\n jpeg: JPEG,\n gif: 'image/gif',\n tiff: 'image/tiff',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n};\nfunction getExtension(url) {\n const match = /\\.([^./]*?)$/g.exec(url);\n return match ? match[1] : '';\n}\nexport function getMimeType(url) {\n const extension = getExtension(url).toLowerCase();\n return mimes[extension] || '';\n}\n//# sourceMappingURL=mimes.js.map","function getContentFromDataUrl(dataURL) {\n return dataURL.split(/,/)[1];\n}\nexport function isDataUrl(url) {\n return url.search(/^(data:)/) !== -1;\n}\nexport function makeDataUrl(content, mimeType) {\n return `data:${mimeType};base64,${content}`;\n}\nexport async function fetchAsDataURL(url, init, process) {\n const res = await fetch(url, init);\n if (res.status === 404) {\n throw new Error(`Resource \"${res.url}\" not found`);\n }\n const blob = await res.blob();\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = () => {\n try {\n resolve(process({ res, result: reader.result }));\n }\n catch (error) {\n reject(error);\n }\n };\n reader.readAsDataURL(blob);\n });\n}\nconst cache = {};\nfunction getCacheKey(url, contentType, includeQueryParams) {\n let key = url.replace(/\\?.*/, '');\n if (includeQueryParams) {\n key = url;\n }\n // font resource\n if (/ttf|otf|eot|woff2?/i.test(key)) {\n key = key.replace(/.*\\//, '');\n }\n return contentType ? `[${contentType}]${key}` : key;\n}\nexport async function resourceToDataURL(resourceUrl, contentType, options) {\n const cacheKey = getCacheKey(resourceUrl, contentType, options.includeQueryParams);\n if (cache[cacheKey] != null) {\n return cache[cacheKey];\n }\n // ref: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache\n if (options.cacheBust) {\n // eslint-disable-next-line no-param-reassign\n resourceUrl += (/\\?/.test(resourceUrl) ? '&' : '?') + new Date().getTime();\n }\n let dataURL;\n try {\n const content = await fetchAsDataURL(resourceUrl, options.fetchRequestInit, ({ res, result }) => {\n if (!contentType) {\n // eslint-disable-next-line no-param-reassign\n contentType = res.headers.get('Content-Type') || '';\n }\n return getContentFromDataUrl(result);\n });\n dataURL = makeDataUrl(content, contentType);\n }\n catch (error) {\n dataURL = options.imagePlaceholder || '';\n let msg = `Failed to fetch resource: ${resourceUrl}`;\n if (error) {\n msg = typeof error === 'string' ? error : error.message;\n }\n if (msg) {\n console.warn(msg);\n }\n }\n cache[cacheKey] = dataURL;\n return dataURL;\n}\n//# sourceMappingURL=dataurl.js.map","import { clonePseudoElements } from './clone-pseudos';\nimport { createImage, toArray, isInstanceOfElement, getStyleProperties, } from './util';\nimport { getMimeType } from './mimes';\nimport { resourceToDataURL } from './dataurl';\nasync function cloneCanvasElement(canvas) {\n const dataURL = canvas.toDataURL();\n if (dataURL === 'data:,') {\n return canvas.cloneNode(false);\n }\n return createImage(dataURL);\n}\nasync function cloneVideoElement(video, options) {\n if (video.currentSrc) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n canvas.width = video.clientWidth;\n canvas.height = video.clientHeight;\n ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height);\n const dataURL = canvas.toDataURL();\n return createImage(dataURL);\n }\n const poster = video.poster;\n const contentType = getMimeType(poster);\n const dataURL = await resourceToDataURL(poster, contentType, options);\n return createImage(dataURL);\n}\nasync function cloneIFrameElement(iframe, options) {\n var _a;\n try {\n if ((_a = iframe === null || iframe === void 0 ? void 0 : iframe.contentDocument) === null || _a === void 0 ? void 0 : _a.body) {\n return (await cloneNode(iframe.contentDocument.body, options, true));\n }\n }\n catch (_b) {\n // Failed to clone iframe\n }\n return iframe.cloneNode(false);\n}\nasync function cloneSingleNode(node, options) {\n if (isInstanceOfElement(node, HTMLCanvasElement)) {\n return cloneCanvasElement(node);\n }\n if (isInstanceOfElement(node, HTMLVideoElement)) {\n return cloneVideoElement(node, options);\n }\n if (isInstanceOfElement(node, HTMLIFrameElement)) {\n return cloneIFrameElement(node, options);\n }\n return node.cloneNode(isSVGElement(node));\n}\nconst isSlotElement = (node) => node.tagName != null && node.tagName.toUpperCase() === 'SLOT';\nconst isSVGElement = (node) => node.tagName != null && node.tagName.toUpperCase() === 'SVG';\nasync function cloneChildren(nativeNode, clonedNode, options) {\n var _a, _b;\n if (isSVGElement(clonedNode)) {\n return clonedNode;\n }\n let children = [];\n if (isSlotElement(nativeNode) && nativeNode.assignedNodes) {\n children = toArray(nativeNode.assignedNodes());\n }\n else if (isInstanceOfElement(nativeNode, HTMLIFrameElement) &&\n ((_a = nativeNode.contentDocument) === null || _a === void 0 ? void 0 : _a.body)) {\n children = toArray(nativeNode.contentDocument.body.childNodes);\n }\n else {\n children = toArray(((_b = nativeNode.shadowRoot) !== null && _b !== void 0 ? _b : nativeNode).childNodes);\n }\n if (children.length === 0 ||\n isInstanceOfElement(nativeNode, HTMLVideoElement)) {\n return clonedNode;\n }\n await children.reduce((deferred, child) => deferred\n .then(() => cloneNode(child, options))\n .then((clonedChild) => {\n if (clonedChild) {\n clonedNode.appendChild(clonedChild);\n }\n }), Promise.resolve());\n return clonedNode;\n}\nfunction cloneCSSStyle(nativeNode, clonedNode, options) {\n const targetStyle = clonedNode.style;\n if (!targetStyle) {\n return;\n }\n const sourceStyle = window.getComputedStyle(nativeNode);\n if (sourceStyle.cssText) {\n targetStyle.cssText = sourceStyle.cssText;\n targetStyle.transformOrigin = sourceStyle.transformOrigin;\n }\n else {\n getStyleProperties(options).forEach((name) => {\n let value = sourceStyle.getPropertyValue(name);\n if (name === 'font-size' && value.endsWith('px')) {\n const reducedFont = Math.floor(parseFloat(value.substring(0, value.length - 2))) - 0.1;\n value = `${reducedFont}px`;\n }\n if (isInstanceOfElement(nativeNode, HTMLIFrameElement) &&\n name === 'display' &&\n value === 'inline') {\n value = 'block';\n }\n if (name === 'd' && clonedNode.getAttribute('d')) {\n value = `path(${clonedNode.getAttribute('d')})`;\n }\n targetStyle.setProperty(name, value, sourceStyle.getPropertyPriority(name));\n });\n }\n}\nfunction cloneInputValue(nativeNode, clonedNode) {\n if (isInstanceOfElement(nativeNode, HTMLTextAreaElement)) {\n clonedNode.innerHTML = nativeNode.value;\n }\n if (isInstanceOfElement(nativeNode, HTMLInputElement)) {\n clonedNode.setAttribute('value', nativeNode.value);\n }\n}\nfunction cloneSelectValue(nativeNode, clonedNode) {\n if (isInstanceOfElement(nativeNode, HTMLSelectElement)) {\n const clonedSelect = clonedNode;\n const selectedOption = Array.from(clonedSelect.children).find((child) => nativeNode.value === child.getAttribute('value'));\n if (selectedOption) {\n selectedOption.setAttribute('selected', '');\n }\n }\n}\nfunction decorate(nativeNode, clonedNode, options) {\n if (isInstanceOfElement(clonedNode, Element)) {\n cloneCSSStyle(nativeNode, clonedNode, options);\n clonePseudoElements(nativeNode, clonedNode, options);\n cloneInputValue(nativeNode, clonedNode);\n cloneSelectValue(nativeNode, clonedNode);\n }\n return clonedNode;\n}\nasync function ensureSVGSymbols(clone, options) {\n const uses = clone.querySelectorAll ? clone.querySelectorAll('use') : [];\n if (uses.length === 0) {\n return clone;\n }\n const processedDefs = {};\n for (let i = 0; i < uses.length; i++) {\n const use = uses[i];\n const id = use.getAttribute('xlink:href');\n if (id) {\n const exist = clone.querySelector(id);\n const definition = document.querySelector(id);\n if (!exist && definition && !processedDefs[id]) {\n // eslint-disable-next-line no-await-in-loop\n processedDefs[id] = (await cloneNode(definition, options, true));\n }\n }\n }\n const nodes = Object.values(processedDefs);\n if (nodes.length) {\n const ns = 'http://www.w3.org/1999/xhtml';\n const svg = document.createElementNS(ns, 'svg');\n svg.setAttribute('xmlns', ns);\n svg.style.position = 'absolute';\n svg.style.width = '0';\n svg.style.height = '0';\n svg.style.overflow = 'hidden';\n svg.style.display = 'none';\n const defs = document.createElementNS(ns, 'defs');\n svg.appendChild(defs);\n for (let i = 0; i < nodes.length; i++) {\n defs.appendChild(nodes[i]);\n }\n clone.appendChild(svg);\n }\n return clone;\n}\nexport async function cloneNode(node, options, isRoot) {\n if (!isRoot && options.filter && !options.filter(node)) {\n return null;\n }\n return Promise.resolve(node)\n .then((clonedNode) => cloneSingleNode(clonedNode, options))\n .then((clonedNode) => cloneChildren(node, clonedNode, options))\n .then((clonedNode) => decorate(node, clonedNode, options))\n .then((clonedNode) => ensureSVGSymbols(clonedNode, options));\n}\n//# sourceMappingURL=clone-node.js.map","import { resolveUrl } from './util';\nimport { getMimeType } from './mimes';\nimport { isDataUrl, makeDataUrl, resourceToDataURL } from './dataurl';\nconst URL_REGEX = /url\\((['\"]?)([^'\"]+?)\\1\\)/g;\nconst URL_WITH_FORMAT_REGEX = /url\\([^)]+\\)\\s*format\\(([\"']?)([^\"']+)\\1\\)/g;\nconst FONT_SRC_REGEX = /src:\\s*(?:url\\([^)]+\\)\\s*format\\([^)]+\\)[,;]\\s*)+/g;\nfunction toRegex(url) {\n // eslint-disable-next-line no-useless-escape\n const escaped = url.replace(/([.*+?^${}()|\\[\\]\\/\\\\])/g, '\\\\$1');\n return new RegExp(`(url\\\\(['\"]?)(${escaped})(['\"]?\\\\))`, 'g');\n}\nexport function parseURLs(cssText) {\n const urls = [];\n cssText.replace(URL_REGEX, (raw, quotation, url) => {\n urls.push(url);\n return raw;\n });\n return urls.filter((url) => !isDataUrl(url));\n}\nexport async function embed(cssText, resourceURL, baseURL, options, getContentFromUrl) {\n try {\n const resolvedURL = baseURL ? resolveUrl(resourceURL, baseURL) : resourceURL;\n const contentType = getMimeType(resourceURL);\n let dataURL;\n if (getContentFromUrl) {\n const content = await getContentFromUrl(resolvedURL);\n dataURL = makeDataUrl(content, contentType);\n }\n else {\n dataURL = await resourceToDataURL(resolvedURL, contentType, options);\n }\n return cssText.replace(toRegex(resourceURL), `$1${dataURL}$3`);\n }\n catch (error) {\n // pass\n }\n return cssText;\n}\nfunction filterPreferredFontFormat(str, { preferredFontFormat }) {\n return !preferredFontFormat\n ? str\n : str.replace(FONT_SRC_REGEX, (match) => {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const [src, , format] = URL_WITH_FORMAT_REGEX.exec(match) || [];\n if (!format) {\n return '';\n }\n if (format === preferredFontFormat) {\n return `src: ${src};`;\n }\n }\n });\n}\nexport function shouldEmbed(url) {\n return url.search(URL_REGEX) !== -1;\n}\nexport async function embedResources(cssText, baseUrl, options) {\n if (!shouldEmbed(cssText)) {\n return cssText;\n }\n const filteredCSSText = filterPreferredFontFormat(cssText, options);\n const urls = parseURLs(filteredCSSText);\n return urls.reduce((deferred, url) => deferred.then((css) => embed(css, url, baseUrl, options)), Promise.resolve(filteredCSSText));\n}\n//# sourceMappingURL=embed-resources.js.map","import { embedResources } from './embed-resources';\nimport { toArray, isInstanceOfElement } from './util';\nimport { isDataUrl, resourceToDataURL } from './dataurl';\nimport { getMimeType } from './mimes';\nasync function embedProp(propName, node, options) {\n var _a;\n const propValue = (_a = node.style) === null || _a === void 0 ? void 0 : _a.getPropertyValue(propName);\n if (propValue) {\n const cssString = await embedResources(propValue, null, options);\n node.style.setProperty(propName, cssString, node.style.getPropertyPriority(propName));\n return true;\n }\n return false;\n}\nasync function embedBackground(clonedNode, options) {\n ;\n (await embedProp('background', clonedNode, options)) ||\n (await embedProp('background-image', clonedNode, options));\n (await embedProp('mask', clonedNode, options)) ||\n (await embedProp('-webkit-mask', clonedNode, options)) ||\n (await embedProp('mask-image', clonedNode, options)) ||\n (await embedProp('-webkit-mask-image', clonedNode, options));\n}\nasync function embedImageNode(clonedNode, options) {\n const isImageElement = isInstanceOfElement(clonedNode, HTMLImageElement);\n if (!(isImageElement && !isDataUrl(clonedNode.src)) &&\n !(isInstanceOfElement(clonedNode, SVGImageElement) &&\n !isDataUrl(clonedNode.href.baseVal))) {\n return;\n }\n const url = isImageElement ? clonedNode.src : clonedNode.href.baseVal;\n const dataURL = await resourceToDataURL(url, getMimeType(url), options);\n await new Promise((resolve, reject) => {\n clonedNode.onload = resolve;\n clonedNode.onerror = options.onImageErrorHandler\n ? (...attributes) => {\n try {\n resolve(options.onImageErrorHandler(...attributes));\n }\n catch (error) {\n reject(error);\n }\n }\n : reject;\n const image = clonedNode;\n if (image.decode) {\n image.decode = resolve;\n }\n if (image.loading === 'lazy') {\n image.loading = 'eager';\n }\n if (isImageElement) {\n clonedNode.srcset = '';\n clonedNode.src = dataURL;\n }\n else {\n clonedNode.href.baseVal = dataURL;\n }\n });\n}\nasync function embedChildren(clonedNode, options) {\n const children = toArray(clonedNode.childNodes);\n const deferreds = children.map((child) => embedImages(child, options));\n await Promise.all(deferreds).then(() => clonedNode);\n}\nexport async function embedImages(clonedNode, options) {\n if (isInstanceOfElement(clonedNode, Element)) {\n await embedBackground(clonedNode, options);\n await embedImageNode(clonedNode, options);\n await embedChildren(clonedNode, options);\n }\n}\n//# sourceMappingURL=embed-images.js.map","export function applyStyle(node, options) {\n const { style } = node;\n if (options.backgroundColor) {\n style.backgroundColor = options.backgroundColor;\n }\n if (options.width) {\n style.width = `${options.width}px`;\n }\n if (options.height) {\n style.height = `${options.height}px`;\n }\n const manual = options.style;\n if (manual != null) {\n Object.keys(manual).forEach((key) => {\n style[key] = manual[key];\n });\n }\n return node;\n}\n//# sourceMappingURL=apply-style.js.map","import { toArray } from './util';\nimport { fetchAsDataURL } from './dataurl';\nimport { shouldEmbed, embedResources } from './embed-resources';\nconst cssFetchCache = {};\nasync function fetchCSS(url) {\n let cache = cssFetchCache[url];\n if (cache != null) {\n return cache;\n }\n const res = await fetch(url);\n const cssText = await res.text();\n cache = { url, cssText };\n cssFetchCache[url] = cache;\n return cache;\n}\nasync function embedFonts(data, options) {\n let cssText = data.cssText;\n const regexUrl = /url\\([\"']?([^\"')]+)[\"']?\\)/g;\n const fontLocs = cssText.match(/url\\([^)]+\\)/g) || [];\n const loadFonts = fontLocs.map(async (loc) => {\n let url = loc.replace(regexUrl, '$1');\n if (!url.startsWith('https://')) {\n url = new URL(url, data.url).href;\n }\n return fetchAsDataURL(url, options.fetchRequestInit, ({ result }) => {\n cssText = cssText.replace(loc, `url(${result})`);\n return [loc, result];\n });\n });\n return Promise.all(loadFonts).then(() => cssText);\n}\nfunction parseCSS(source) {\n if (source == null) {\n return [];\n }\n const result = [];\n const commentsRegex = /(\\/\\*[\\s\\S]*?\\*\\/)/gi;\n // strip out comments\n let cssText = source.replace(commentsRegex, '');\n // eslint-disable-next-line prefer-regex-literals\n const keyframesRegex = new RegExp('((@.*?keyframes [\\\\s\\\\S]*?){([\\\\s\\\\S]*?}\\\\s*?)})', 'gi');\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const matches = keyframesRegex.exec(cssText);\n if (matches === null) {\n break;\n }\n result.push(matches[0]);\n }\n cssText = cssText.replace(keyframesRegex, '');\n const importRegex = /@import[\\s\\S]*?url\\([^)]*\\)[\\s\\S]*?;/gi;\n // to match css & media queries together\n const combinedCSSRegex = '((\\\\s*?(?:\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\/)?\\\\s*?@media[\\\\s\\\\S]' +\n '*?){([\\\\s\\\\S]*?)}\\\\s*?})|(([\\\\s\\\\S]*?){([\\\\s\\\\S]*?)})';\n // unified regex\n const unifiedRegex = new RegExp(combinedCSSRegex, 'gi');\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let matches = importRegex.exec(cssText);\n if (matches === null) {\n matches = unifiedRegex.exec(cssText);\n if (matches === null) {\n break;\n }\n else {\n importRegex.lastIndex = unifiedRegex.lastIndex;\n }\n }\n else {\n unifiedRegex.lastIndex = importRegex.lastIndex;\n }\n result.push(matches[0]);\n }\n return result;\n}\nasync function getCSSRules(styleSheets, options) {\n const ret = [];\n const deferreds = [];\n // First loop inlines imports\n styleSheets.forEach((sheet) => {\n if ('cssRules' in sheet) {\n try {\n toArray(sheet.cssRules || []).forEach((item, index) => {\n if (item.type === CSSRule.IMPORT_RULE) {\n let importIndex = index + 1;\n const url = item.href;\n const deferred = fetchCSS(url)\n .then((metadata) => embedFonts(metadata, options))\n .then((cssText) => parseCSS(cssText).forEach((rule) => {\n try {\n sheet.insertRule(rule, rule.startsWith('@import')\n ? (importIndex += 1)\n : sheet.cssRules.length);\n }\n catch (error) {\n console.error('Error inserting rule from remote css', {\n rule,\n error,\n });\n }\n }))\n .catch((e) => {\n console.error('Error loading remote css', e.toString());\n });\n deferreds.push(deferred);\n }\n });\n }\n catch (e) {\n const inline = styleSheets.find((a) => a.href == null) || document.styleSheets[0];\n if (sheet.href != null) {\n deferreds.push(fetchCSS(sheet.href)\n .then((metadata) => embedFonts(metadata, options))\n .then((cssText) => parseCSS(cssText).forEach((rule) => {\n inline.insertRule(rule, inline.cssRules.length);\n }))\n .catch((err) => {\n console.error('Error loading remote stylesheet', err);\n }));\n }\n console.error('Error inlining remote css file', e);\n }\n }\n });\n return Promise.all(deferreds).then(() => {\n // Second loop parses rules\n styleSheets.forEach((sheet) => {\n if ('cssRules' in sheet) {\n try {\n toArray(sheet.cssRules || []).forEach((item) => {\n ret.push(item);\n });\n }\n catch (e) {\n console.error(`Error while reading CSS rules from ${sheet.href}`, e);\n }\n }\n });\n return ret;\n });\n}\nfunction getWebFontRules(cssRules) {\n return cssRules\n .filter((rule) => rule.type === CSSRule.FONT_FACE_RULE)\n .filter((rule) => shouldEmbed(rule.style.getPropertyValue('src')));\n}\nasync function parseWebFontRules(node, options) {\n if (node.ownerDocument == null) {\n throw new Error('Provided element is not within a Document');\n }\n const styleSheets = toArray(node.ownerDocument.styleSheets);\n const cssRules = await getCSSRules(styleSheets, options);\n return getWebFontRules(cssRules);\n}\nfunction normalizeFontFamily(font) {\n return font.trim().replace(/[\"']/g, '');\n}\nfunction getUsedFonts(node) {\n const fonts = new Set();\n function traverse(node) {\n const fontFamily = node.style.fontFamily || getComputedStyle(node).fontFamily;\n fontFamily.split(',').forEach((font) => {\n fonts.add(normalizeFontFamily(font));\n });\n Array.from(node.children).forEach((child) => {\n if (child instanceof HTMLElement) {\n traverse(child);\n }\n });\n }\n traverse(node);\n return fonts;\n}\nexport async function getWebFontCSS(node, options) {\n const rules = await parseWebFontRules(node, options);\n const usedFonts = getUsedFonts(node);\n const cssTexts = await Promise.all(rules\n .filter((rule) => usedFonts.has(normalizeFontFamily(rule.style.fontFamily)))\n .map((rule) => {\n const baseUrl = rule.parentStyleSheet\n ? rule.parentStyleSheet.href\n : null;\n return embedResources(rule.cssText, baseUrl, options);\n }));\n return cssTexts.join('\\n');\n}\nexport async function embedWebFonts(clonedNode, options) {\n const cssText = options.fontEmbedCSS != null\n ? options.fontEmbedCSS\n : options.skipFonts\n ? null\n : await getWebFontCSS(clonedNode, options);\n if (cssText) {\n const styleNode = document.createElement('style');\n const sytleContent = document.createTextNode(cssText);\n styleNode.appendChild(sytleContent);\n if (clonedNode.firstChild) {\n clonedNode.insertBefore(styleNode, clonedNode.firstChild);\n }\n else {\n clonedNode.appendChild(styleNode);\n }\n }\n}\n//# sourceMappingURL=embed-webfonts.js.map","import { cloneNode } from './clone-node';\nimport { embedImages } from './embed-images';\nimport { applyStyle } from './apply-style';\nimport { embedWebFonts, getWebFontCSS } from './embed-webfonts';\nimport { getImageSize, getPixelRatio, createImage, canvasToBlob, nodeToDataURL, checkCanvasDimensions, } from './util';\nexport async function toSvg(node, options = {}) {\n const { width, height } = getImageSize(node, options);\n const clonedNode = (await cloneNode(node, options, true));\n await embedWebFonts(clonedNode, options);\n await embedImages(clonedNode, options);\n applyStyle(clonedNode, options);\n const datauri = await nodeToDataURL(clonedNode, width, height);\n return datauri;\n}\nexport async function toCanvas(node, options = {}) {\n const { width, height } = getImageSize(node, options);\n const svg = await toSvg(node, options);\n const img = await createImage(svg);\n const canvas = document.createElement('canvas');\n const context = canvas.getContext('2d');\n const ratio = options.pixelRatio || getPixelRatio();\n const canvasWidth = options.canvasWidth || width;\n const canvasHeight = options.canvasHeight || height;\n canvas.width = canvasWidth * ratio;\n canvas.height = canvasHeight * ratio;\n if (!options.skipAutoScale) {\n checkCanvasDimensions(canvas);\n }\n canvas.style.width = `${canvasWidth}`;\n canvas.style.height = `${canvasHeight}`;\n if (options.backgroundColor) {\n context.fillStyle = options.backgroundColor;\n context.fillRect(0, 0, canvas.width, canvas.height);\n }\n context.drawImage(img, 0, 0, canvas.width, canvas.height);\n return canvas;\n}\nexport async function toPixelData(node, options = {}) {\n const { width, height } = getImageSize(node, options);\n const canvas = await toCanvas(node, options);\n const ctx = canvas.getContext('2d');\n return ctx.getImageData(0, 0, width, height).data;\n}\nexport async function toPng(node, options = {}) {\n const canvas = await toCanvas(node, options);\n return canvas.toDataURL();\n}\nexport async function toJpeg(node, options = {}) {\n const canvas = await toCanvas(node, options);\n return canvas.toDataURL('image/jpeg', options.quality || 1);\n}\nexport async function toBlob(node, options = {}) {\n const canvas = await toCanvas(node, options);\n const blob = await canvasToBlob(canvas);\n return blob;\n}\nexport async function getFontEmbedCSS(node, options = {}) {\n return getWebFontCSS(node, options);\n}\n//# sourceMappingURL=index.js.map","import { toCanvas } from 'html-to-image'\n\nconst MAX_SIZE = 2 * 1024 * 1024 // 2 MB\n\nexport interface ScrubConfig {\n strictScrub?: boolean\n redactSelector?: string\n}\n\nexport interface CaptureResult {\n blob: Blob\n redactedCount: number\n redactedSelectors: string[]\n}\n\nconst MASK_CSS =\n 'background:currentColor!important;color:transparent!important;text-shadow:none!important;-webkit-text-fill-color:transparent!important'\n\nconst SENSITIVE_SELECTOR =\n 'input[type=\"password\"],' +\n 'input[autocomplete~=\"cc-number\"],' +\n 'input[autocomplete~=\"cc-csc\"],' +\n 'input[autocomplete~=\"cc-exp\"],' +\n 'input[autocomplete~=\"cc-name\"],' +\n 'input[autocomplete~=\"cc-type\"],' +\n 'input[autocomplete~=\"current-password\"],' +\n 'input[autocomplete~=\"new-password\"],' +\n 'input[autocomplete~=\"one-time-code\"]'\n\nfunction isWithinSafe(el: Element): boolean {\n let node: Element | null = el.parentElement\n while (node) {\n if (node.hasAttribute('data-markup-safe')) return true\n node = node.parentElement\n }\n return false\n}\n\nfunction buildMaskList(cfg: ScrubConfig): Element[] {\n const seen = new Set<Element>()\n const list: Element[] = []\n\n function add(el: Element) {\n if (!seen.has(el)) {\n seen.add(el)\n list.push(el)\n }\n }\n\n // Always mask regardless of data-markup-safe\n for (const el of document.querySelectorAll('[data-markup-private],[data-markup-redact]')) {\n add(el)\n }\n\n // Auto-detect sensitive fields (exempted by data-markup-safe ancestor)\n for (const el of document.querySelectorAll(SENSITIVE_SELECTOR)) {\n if (!isWithinSafe(el)) add(el)\n }\n\n if (cfg.redactSelector) {\n try {\n for (const el of document.querySelectorAll(cfg.redactSelector)) {\n if (!isWithinSafe(el)) add(el)\n }\n } catch {\n /* invalid selector — ignore */\n }\n }\n\n if (cfg.strictScrub) {\n for (const el of document.querySelectorAll('input,select,textarea')) {\n if (!isWithinSafe(el)) add(el)\n }\n }\n\n return list\n}\n\nfunction applyMask(el: Element): () => void {\n const prev = el.getAttribute('style')\n el.setAttribute('style', prev ? `${prev};${MASK_CSS}` : MASK_CSS)\n return () => {\n if (prev === null) {\n el.removeAttribute('style')\n } else {\n el.setAttribute('style', prev)\n }\n }\n}\n\nfunction selectorFor(el: Element): string {\n if (el.id) return `#${CSS.escape(el.id)}`\n const tag = el.tagName.toLowerCase()\n const type = el.getAttribute('type')\n const name = el.getAttribute('name')\n if (type && name) return `${tag}[type=\"${type}\"][name=\"${name}\"]`\n if (type) return `${tag}[type=\"${type}\"]`\n if (name) return `${tag}[name=\"${name}\"]`\n return tag\n}\n\n/**\n * Captures the visible viewport as a JPEG blob using html-to-image.\n * The widget host element is excluded so the overlay/popover don't appear.\n * Elements with `data-markup-skip` are excluded from the capture.\n * Sensitive fields are masked before capture via inline style overrides and\n * restored immediately after — the live DOM is mutated for the duration of the\n * `toCanvas` call only.\n * Returns null if capture fails or the result exceeds 2 MB after compression.\n *\n * If `pin` is provided (viewport/client coordinates), the pin marker is drawn\n * on top of the captured canvas so the screenshot shows exactly where the\n * feedback is targeted.\n */\nexport async function captureScreenshot(\n excludeEl?: Element | null,\n pin?: { x: number; y: number },\n scrubConfig?: ScrubConfig,\n): Promise<CaptureResult | null> {\n try {\n const w = window.innerWidth\n const h = window.innerHeight\n const pixelRatio = Math.min(window.devicePixelRatio, 2)\n\n const maskList = scrubConfig ? buildMaskList(scrubConfig) : []\n const redactedSelectors = maskList.map(selectorFor)\n const restores = maskList.map(applyMask)\n\n let canvas!: HTMLCanvasElement\n try {\n canvas = await toCanvas(document.documentElement, {\n width: w,\n height: h,\n cacheBust: true,\n backgroundColor: '#ffffff',\n pixelRatio,\n filter(node: Node): boolean {\n if (excludeEl && (node === excludeEl || excludeEl.contains(node))) return false\n if (node instanceof Element && node.hasAttribute('data-markup-skip')) return false\n return true\n },\n style: {\n // Prevent any scroll-position offset from being baked in\n transform: `translateY(-${window.scrollY}px)`,\n transformOrigin: 'top left',\n },\n })\n } finally {\n for (const restore of restores) restore()\n }\n\n if (pin) {\n const ctx = canvas.getContext('2d')\n if (ctx) drawPin(ctx, pin.x, pin.y, pixelRatio)\n }\n\n const blob = await canvasToBlob(canvas, 0.85)\n if (!blob) return null\n\n if (blob.size <= MAX_SIZE) {\n return { blob, redactedCount: redactedSelectors.length, redactedSelectors }\n }\n\n // Retry at lower quality to meet the 2 MB cap\n const smaller = await canvasToBlob(canvas, 0.5)\n if (!smaller || smaller.size > MAX_SIZE) return null\n return { blob: smaller, redactedCount: redactedSelectors.length, redactedSelectors }\n } catch {\n return null\n }\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob | null> {\n return new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', quality))\n}\n\n// Draws the pin marker (matching the widget's CSS pin shape) onto the canvas.\n// x/y are viewport (clientX/clientY) coordinates; pixelRatio scales to canvas pixels.\n// The pin is upright with its bottom-left corner (the pointed 4px-radius corner,\n// matching border-radius: 50% 50% 50% 4px without rotation) at the click point,\n// and the body extending upward — matching the CSS margin-top: -28px layout.\nfunction drawPin(ctx: CanvasRenderingContext2D, x: number, y: number, pixelRatio: number) {\n const pr = pixelRatio\n const size = 28 * pr\n const half = size / 2\n const px = x * pr\n const py = y * pr\n\n ctx.save()\n\n // 2px white ring (matches box-shadow: 0 0 0 2px paper)\n const ring = 2 * pr\n ctx.beginPath()\n // roundRect radii order: top-left, top-right, bottom-right, bottom-left\n // matches CSS border-radius: 50% 50% 50% 4px (upright, no rotation)\n ctx.roundRect(px - ring, py - size - ring, size + ring * 2, size + ring * 2, [\n 14 * pr + ring,\n 14 * pr + ring,\n 14 * pr + ring,\n 4 * pr + ring,\n ])\n ctx.fillStyle = '#ffffff'\n ctx.fill()\n\n // Pin body — bottom-left corner (the 4px pointed corner) sits at (px, py)\n ctx.beginPath()\n ctx.roundRect(px, py - size, size, size, [14 * pr, 14 * pr, 14 * pr, 4 * pr])\n ctx.fillStyle = '#1a1614'\n ctx.fill()\n\n // Dot — centered in the pin body\n ctx.beginPath()\n ctx.arc(px + half, py - half, 3 * pr, 0, Math.PI * 2)\n ctx.fillStyle = '#e35d2a'\n ctx.fill()\n\n ctx.restore()\n}\n","/**\n * Manages the short-lived JWT used to authenticate the widget's Convex\n * WebSocket subscription. The token has to be re-issued well before its\n * server-side TTL elapses or an in-flight subscription would drop mid-\n * session; this hook owns the mint + scheduled-refresh + retry loop so\n * `app.tsx` doesn't carry an additional imperative `useEffect`.\n *\n * The HTTP layer enforces the apiKey + Origin gate before minting, so\n * the token's value (and not just the apiKey) is what authorizes the\n * WebSocket — a sniffed apiKey hash by itself is no longer enough to\n * subscribe from an off-allowlist origin.\n *\n * Modelled with `useMachine` for consistency with the rest of the\n * widget's state primitives. The machine is intentionally small (two\n * states, one event) — the value is in making \"do we have a usable\n * token right now\" a structural fact callers can pattern-match on, not\n * a `string | null` that consumers need to null-check by convention.\n */\n\nimport { useEffect } from 'preact/hooks'\n\nimport { defineMachine, useMachine } from '../lib/machine'\nimport type { WidgetApiClient } from './api'\n\ntype TokenState = { kind: 'idle' } | { kind: 'active'; token: string; expiresAt: number }\n\ntype TokenEvent = { type: 'issued'; token: string; expiresAt: number }\n\nconst tokenMachine = defineMachine<TokenState, TokenEvent>({\n idle: {\n issued: (_, e) => ({ kind: 'active', token: e.token, expiresAt: e.expiresAt }),\n },\n active: {\n // A refresh issues a new token that replaces the prior one in\n // place — the subscription effect downstream re-binds because the\n // returned `token` string changes.\n issued: (_, e) => ({ kind: 'active', token: e.token, expiresAt: e.expiresAt }),\n },\n})\n\n/**\n * Refresh ~30 min before expiry, but never sooner than 60s after the\n * last issuance. The floor avoids a tight retry loop in case the server\n * hands back an already-near-expiry token under clock skew, and gives\n * the WebSocket time to settle on the new credential between handoffs.\n */\nconst REFRESH_LEAD_MS = 30 * 60_000\nconst REFRESH_MIN_INTERVAL_MS = 60_000\nconst RETRY_AFTER_FAILURE_MS = 60_000\n\nexport function useSubscriptionToken(api: WidgetApiClient): string | null {\n const [state, send] = useMachine(tokenMachine, { kind: 'idle' })\n\n useEffect(() => {\n let cancelled = false\n let timer: ReturnType<typeof setTimeout> | null = null\n\n async function refresh() {\n try {\n const issued = await api.getSubscriptionToken()\n if (cancelled) return\n send({ type: 'issued', token: issued.token, expiresAt: issued.expiresAt })\n const refreshAfterMs = Math.max(\n REFRESH_MIN_INTERVAL_MS,\n issued.expiresAt - Date.now() - REFRESH_LEAD_MS,\n )\n timer = setTimeout(refresh, refreshAfterMs)\n } catch {\n if (cancelled) return\n // Deliberately don't surface this to the user — if the apiKey/\n // Origin combo is bad the HTTP write paths will fail loudly\n // anyway, and a transient mint failure shouldn't add noise to\n // a UI that's otherwise still usable.\n timer = setTimeout(refresh, RETRY_AFTER_FAILURE_MS)\n }\n }\n\n refresh()\n return () => {\n cancelled = true\n if (timer) clearTimeout(timer)\n }\n }, [api, send])\n\n return state.kind === 'active' ? state.token : null\n}\n","type ClassValue = string | boolean | null | undefined\n\nexport function cx(...classes: ClassValue[]) {\n return classes.filter(Boolean).join(' ')\n}\n","import type { RefObject } from 'preact'\nimport { useCallback, useRef, useState } from 'preact/hooks'\n\n/**\n * Pointer-drag bookkeeping shared by the FAB and both popover headers.\n *\n * Owns the gesture mechanics (capture, threshold, pointerId match,\n * pointerup/cancel split, viewport clamp) and surfaces just the\n * callbacks the caller actually needs:\n *\n * - `onMove` streams the clamped coords during the drag.\n * - `onEnd` fires once on a clean pointerup if the gesture passed\n * the threshold. Receives the final coords and the event\n * so callers can do snap-to-corner / commit-position\n * decisions.\n * - `onCancel` fires on pointercancel (system gesture interruption,\n * not a clean release). Bookkeeping is reset before the\n * callback runs.\n *\n * `consumeClickIfDragged()` is the FAB's escape hatch: a click event\n * always follows a successful pointerup, but the click should be\n * suppressed if the gesture moved past the threshold. The returned\n * helper reads the \"did drag\" flag and clears it in one shot, so a\n * caller's onClick can:\n *\n * if (consumeClickIfDragged()) return\n *\n * Popovers never need this — they don't co-locate a click handler\n * with the drag handle.\n */\nexport interface UseDragOpts {\n /**\n * Predicate evaluated on pointerdown to decide whether to start\n * the gesture. Used by the popover headers to skip the drag when\n * the pointer landed on a header button. Defaults to \"always\".\n */\n shouldStart?: (e: PointerEvent) => boolean\n /**\n * Element whose rect is used as the gesture's base coords and\n * dimensions for clamping. When the drag handle *is* the dragged\n * element (FAB), leave this undefined and the hook reads\n * `e.currentTarget`. When the handle is a sub-region of a larger\n * draggable (popover header), pass the larger element's ref here.\n */\n targetRef?: RefObject<HTMLElement>\n /** Called once when the pointer first crosses the threshold. */\n onStart?: () => void\n /** Streamed during the drag with viewport-clamped coords. */\n onMove: (coords: { left: number; top: number }) => void\n /**\n * Called on pointerup *only if* the gesture actually moved past\n * the threshold. Receives the final coords so callers can snap or\n * commit. Not called on pointercancel.\n */\n onEnd?: (coords: { left: number; top: number }, ev: PointerEvent) => void\n /** Called on pointercancel (no follow-up click expected). */\n onCancel?: () => void\n /**\n * Pixels of movement required before the gesture is considered\n * started. Default 4 — matches the previous hand-rolled values.\n */\n threshold?: number\n /** Margin from the viewport edge when clamping coords. Default 8. */\n margin?: number\n /**\n * stopPropagation on pointerdown? FAB sets this so host pages\n * with their own outside-click handlers (e.g., Radix popovers)\n * don't treat the drag start as a dismiss.\n */\n stopPropagation?: boolean\n /**\n * preventDefault on pointerdown? Pairs with `stopPropagation` for\n * the host-dismiss defense: Radix's `DismissableLayer` listens on\n * `pointerdown` in *capture* phase, so a bubble-phase\n * `stopPropagation` is too late — the layer has already seen the\n * event. It bails out when `event.defaultPrevented` is true, so\n * the FAB calls `preventDefault()` to opt out of dismissal.\n */\n preventDefault?: boolean\n}\n\nexport interface UseDragReturn {\n onPointerDown: (e: PointerEvent) => void\n /** True between threshold-crossed and pointerup/cancel. */\n isDragging: boolean\n /**\n * Returns true if the most recent gesture passed the threshold,\n * clearing the flag in the process. Use in an onClick handler to\n * suppress the synthesized click that follows pointerup. Returns\n * false (and stays false) after pointercancel since cancel doesn't\n * produce a click.\n */\n consumeClickIfDragged: () => boolean\n}\n\nexport function useDrag(opts: UseDragOpts): UseDragReturn {\n // Hold opts in a ref so the returned `onPointerDown` is stable\n // across renders even when callers pass inline callbacks.\n const optsRef = useRef(opts)\n optsRef.current = opts\n\n const [isDragging, setIsDragging] = useState(false)\n const draggedRef = useRef(false)\n\n const onPointerDown = useCallback((e: PointerEvent) => {\n const o = optsRef.current\n if (o.preventDefault) e.preventDefault()\n if (o.stopPropagation) e.stopPropagation()\n if (e.button !== 0) return\n if (o.shouldStart && !o.shouldStart(e)) return\n\n const handle = e.currentTarget as HTMLElement | null\n if (!handle) return\n // The handle is what receives pointer events / capture. The\n // *target* (defaults to handle) is what we measure for base\n // coords + dimensions. They differ when the handle is a sub-\n // region of a larger draggable (popover header → popover).\n const target = o.targetRef?.current ?? handle\n const rect = target.getBoundingClientRect()\n const startX = e.clientX\n const startY = e.clientY\n const baseLeft = rect.left\n const baseTop = rect.top\n const w = rect.width\n const h = rect.height\n const threshold = o.threshold ?? 4\n const margin = o.margin ?? 8\n const pointerId = e.pointerId\n let started = false\n let lastCoords: { left: number; top: number } | null = null\n draggedRef.current = false\n\n try {\n handle.setPointerCapture(pointerId)\n } catch {\n /* capture unsupported — fall back to bubbling events */\n }\n\n function teardown() {\n try {\n handle?.releasePointerCapture(pointerId)\n } catch {\n /* ignore */\n }\n handle?.removeEventListener('pointermove', onMove)\n handle?.removeEventListener('pointerup', onPointerUp)\n handle?.removeEventListener('pointercancel', onPointerCancel)\n setIsDragging(false)\n }\n\n function onMove(ev: PointerEvent) {\n if (ev.pointerId !== pointerId) return\n const dx = ev.clientX - startX\n const dy = ev.clientY - startY\n if (!started) {\n if (Math.abs(dx) + Math.abs(dy) < threshold) return\n started = true\n draggedRef.current = true\n setIsDragging(true)\n optsRef.current.onStart?.()\n }\n const maxLeft = Math.max(margin, window.innerWidth - w - margin)\n const maxTop = Math.max(margin, window.innerHeight - h - margin)\n const coords = {\n left: clamp(baseLeft + dx, margin, maxLeft),\n top: clamp(baseTop + dy, margin, maxTop),\n }\n lastCoords = coords\n optsRef.current.onMove(coords)\n }\n\n function onPointerUp(ev: PointerEvent) {\n if (ev.pointerId !== pointerId) return\n teardown()\n if (started && lastCoords) {\n optsRef.current.onEnd?.(lastCoords, ev)\n // Leave `draggedRef` true — the synthesized click that follows\n // will read it via consumeClickIfDragged() and clear it.\n }\n }\n\n function onPointerCancel(ev: PointerEvent) {\n if (ev.pointerId !== pointerId) return\n teardown()\n // No click follows pointercancel, so clear the flag here. If\n // we left it true, the next legitimate click would be eaten as\n // \"stale drag\".\n draggedRef.current = false\n optsRef.current.onCancel?.()\n }\n\n handle.addEventListener('pointermove', onMove)\n handle.addEventListener('pointerup', onPointerUp)\n handle.addEventListener('pointercancel', onPointerCancel)\n }, [])\n\n const consumeClickIfDragged = useCallback(() => {\n if (draggedRef.current) {\n draggedRef.current = false\n return true\n }\n return false\n }, [])\n\n return { onPointerDown, isDragging, consumeClickIfDragged }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n","import{options as r,Fragment as e}from\"preact\";export{Fragment}from\"preact\";var t=/[\"&<]/;function n(r){if(0===r.length||!1===t.test(r))return r;for(var e=0,n=0,o=\"\",f=\"\";n<r.length;n++){switch(r.charCodeAt(n)){case 34:f=\"&quot;\";break;case 38:f=\"&amp;\";break;case 60:f=\"&lt;\";break;default:continue}n!==e&&(o+=r.slice(e,n)),o+=f,e=n+1}return n!==e&&(o+=r.slice(e,n)),o}var o=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,f=0,i=Array.isArray;function u(e,t,n,o,i,u){t||(t={});var a,c,p=t;if(\"ref\"in p)for(c in p={},t)\"ref\"==c?a=t[c]:p[c]=t[c];var l={type:e,props:p,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--f,__i:-1,__u:0,__source:i,__self:u};if(\"function\"==typeof e&&(a=e.defaultProps))for(c in a)void 0===p[c]&&(p[c]=a[c]);return r.vnode&&r.vnode(l),l}function a(r){var t=u(e,{tpl:r,exprs:[].slice.call(arguments,1)});return t.key=t.__v,t}var c={},p=/[A-Z]/g;function l(e,t){if(r.attr){var f=r.attr(e,t);if(\"string\"==typeof f)return f}if(t=function(r){return null!==r&&\"object\"==typeof r&&\"function\"==typeof r.valueOf?r.valueOf():r}(t),\"ref\"===e||\"key\"===e)return\"\";if(\"style\"===e&&\"object\"==typeof t){var i=\"\";for(var u in t){var a=t[u];if(null!=a&&\"\"!==a){var l=\"-\"==u[0]?u:c[u]||(c[u]=u.replace(p,\"-$&\").toLowerCase()),s=\";\";\"number\"!=typeof a||l.startsWith(\"--\")||o.test(l)||(s=\"px;\"),i=i+l+\":\"+a+s}}return e+'=\"'+n(i)+'\"'}return null==t||!1===t||\"function\"==typeof t||\"object\"==typeof t?\"\":!0===t?e:e+'=\"'+n(\"\"+t)+'\"'}function s(r){if(null==r||\"boolean\"==typeof r||\"function\"==typeof r)return null;if(\"object\"==typeof r){if(void 0===r.constructor)return r;if(i(r)){for(var e=0;e<r.length;e++)r[e]=s(r[e]);return r}}return n(\"\"+r)}export{u as jsx,l as jsxAttr,u as jsxDEV,s as jsxEscape,a as jsxTemplate,u as jsxs};\n//# sourceMappingURL=jsxRuntime.module.js.map\n","/* Inline SVG icons — beats pulling in an icon library (~10kB saved). */\n\nexport function IconLogo({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 126 126\" fill=\"currentColor\" aria-hidden>\n <path d=\"M63.4561 0.00557731C70.6277 -0.0175584 76.9025 1.04088 83.5898 3.71066C97.7952 9.43043 109.186 20.5001 115.311 34.5359C119.708 44.8002 120.746 54.7869 119.156 65.8171C116.857 82.7956 105.129 98.8382 90.0566 106.846C83.4394 110.362 74.7336 113.029 67.2051 113.271C62.4204 113.425 61.1274 113.32 56.6807 115.204C50.2035 117.858 43.6874 120.417 37.1348 122.879C34.8442 123.763 32.3203 124.902 29.9404 125.51C29.4023 125.648 28.1978 125.009 27.7598 124.646C26.9046 123.951 27.0582 122.505 27.0264 121.484C26.8123 114.646 27.3302 107.458 26.8604 100.656C25.1578 98.6714 22.4026 96.603 20.3086 94.1989C12.1853 84.8731 7.05334 73.9949 6.18164 61.6101C4.95583 46.292 9.97176 31.1285 20.0908 19.5632C29.989 8.13202 44.0369 1.11921 59.1221 0.0788195C60.2694 -0.0356049 62.2637 0.00944821 63.4561 0.00557731ZM92.2676 55.7497C91.5754 39.5314 77.8207 26.9725 61.6064 27.7536C45.5175 28.5287 33.0758 42.1537 33.7627 58.2468C34.4496 74.3398 48.007 86.8553 64.1035 86.2566C80.3254 85.6533 92.9599 71.968 92.2676 55.7497Z\" />\n </svg>\n )\n}\n\nexport function IconClose({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 20 20\" fill=\"currentColor\">\n <path d=\"M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z\" />\n </svg>\n )\n}\n\nexport function IconEllipsis({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 20 20\" fill=\"currentColor\">\n <path d=\"M3 10a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM8.5 10a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM15.5 8.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3Z\" />\n </svg>\n )\n}\n\nexport function IconCheck({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"currentColor\">\n <path\n fillRule=\"evenodd\"\n d=\"M12.416 3.376a.75.75 0 0 1 .208 1.04l-5 7.5a.75.75 0 0 1-1.154.114l-3-3a.75.75 0 0 1 1.06-1.06l2.353 2.353 4.493-6.74a.75.75 0 0 1 1.04-.207Z\"\n clipRule=\"evenodd\"\n />\n </svg>\n )\n}\n\nexport function IconCamera({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 20 20\" fill=\"currentColor\" aria-hidden>\n <path\n fill-rule=\"evenodd\"\n d=\"M1 8a2 2 0 0 1 2-2h.93a2 2 0 0 0 1.664-.89l.812-1.22A2 2 0 0 1 8.07 3h3.86a2 2 0 0 1 1.664.89l.812 1.22A2 2 0 0 0 16.07 6H17a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8Zm13.5 3a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0ZM10 14a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z\"\n clip-rule=\"evenodd\"\n />\n </svg>\n )\n}\n\nexport function IconSend({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"currentColor\">\n <path d=\"M2.87 2.298a.75.75 0 0 0-.812 1.021L3.39 6.624a1 1 0 0 0 .928.626H8.25a.75.75 0 0 1 0 1.5H4.318a1 1 0 0 0-.927.626l-1.333 3.305a.75.75 0 0 0 .811 1.022 24.89 24.89 0 0 0 11.668-5.115.75.75 0 0 0 0-1.175A24.89 24.89 0 0 0 2.869 2.298Z\" />\n </svg>\n )\n}\n\nexport function IconSmile({ size = 16 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 256 256\" fill=\"currentColor\" aria-hidden>\n <path d=\"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216ZM80,108a12,12,0,1,1,12,12A12,12,0,0,1,80,108Zm96,0a12,12,0,1,1-12-12A12,12,0,0,1,176,108Zm-1.07,48c-10.29,17.79-27.4,28-46.93,28s-36.63-10.2-46.92-28a8,8,0,1,1,13.84-8c7.47,12.91,19.21,20,33.08,20s25.61-7.1,33.07-20a8,8,0,0,1,13.86,8Z\"></path>\n </svg>\n )\n}\n","import { useState } from 'preact/hooks'\n\nimport { useDrag } from '../use-drag'\nimport { cx } from '../utils'\nimport { IconClose, IconLogo } from './icons'\n\ntype FabPosition = 'bottom-right' | 'bottom-left' | 'bottom-center'\ntype FabVariant = 'default' | 'icon-only'\n\nexport function Fab({\n isActive,\n onToggle,\n onHide,\n position = 'bottom-right',\n onPositionChange,\n variant = 'default',\n}: {\n isActive: boolean\n onToggle: () => void\n /**\n * Cmd/Ctrl + click on the FAB hides the entire widget HUD. Same\n * effect as the keyboard shortcut, surfaced as a discoverable\n * mouse path. Plain clicks still toggle placement mode.\n */\n onHide?: () => void\n position?: FabPosition\n /**\n * Fired when a drag ends on the opposite half of the viewport from\n * the current corner. The host snaps the FAB to bottom-left or\n * bottom-right and the toast follows the same corner.\n */\n onPositionChange?: (next: FabPosition) => void\n /**\n * Visual variant. `'icon-only'` drops the \"Markup\"/\"Cancel\" label\n * and tightens padding so the FAB collapses to a circular icon\n * button. Defaults to `'default'`.\n */\n variant?: FabVariant\n}) {\n const isIconOnly = variant === 'icon-only'\n const sideClass =\n position === 'bottom-left'\n ? 'markup-fab-left'\n : position === 'bottom-center'\n ? 'markup-fab-center'\n : 'markup-fab-right'\n const [dragXY, setDragXY] = useState<{ left: number; top: number } | null>(null)\n\n const { onPointerDown, isDragging, consumeClickIfDragged } = useDrag({\n // Don't let host outside-click handlers (e.g., Radix popovers in\n // the page below) treat the FAB press as a dismiss. Radix's\n // `DismissableLayer` listens in capture phase, so `stopPropagation`\n // alone is too late — `preventDefault` is the part that gets the\n // layer to bail out (it skips when `event.defaultPrevented`).\n preventDefault: true,\n stopPropagation: true,\n onMove: setDragXY,\n onEnd: (_coords, ev) => {\n // Snap to whichever third of the viewport the pointer ends in.\n // Vertical drag is free during the gesture but always lands on\n // bottom: 24px via the side class once we drop dragXY.\n const w = window.innerWidth\n const x = ev.clientX\n const next: FabPosition =\n x < w / 3 ? 'bottom-left' : x < (w * 2) / 3 ? 'bottom-center' : 'bottom-right'\n if (next !== position) onPositionChange?.(next)\n setDragXY(null)\n },\n onCancel: () => setDragXY(null),\n })\n\n function onClick(e: MouseEvent) {\n e.preventDefault()\n e.stopPropagation()\n // Suppress the click that always follows a successful drag.\n if (consumeClickIfDragged()) return\n if ((e.metaKey || e.ctrlKey) && onHide) {\n onHide()\n return\n }\n onToggle()\n }\n\n return (\n <button\n type=\"button\"\n class={cx(\n 'markup-fab',\n !dragXY && sideClass,\n dragXY && 'is-floating',\n isDragging && 'is-dragging',\n isActive && 'is-active',\n isIconOnly && 'is-icon-only',\n )}\n style={dragXY ? { left: `${dragXY.left}px`, top: `${dragXY.top}px` } : undefined}\n onClick={onClick}\n onPointerDown={onPointerDown}\n aria-label={isActive ? 'Cancel placing markup' : 'Leave a markup'}\n aria-pressed={isActive}\n >\n <span class=\"markup-fab-icon\">\n {isActive ? <IconClose size={16} /> : <IconLogo size={16} />}\n </span>\n {isIconOnly ? null : <span class=\"markup-fab-label\">{isActive ? 'Cancel' : 'Markup'}</span>}\n </button>\n )\n}\n","import type { RefObject } from 'preact'\nimport { useEffect } from 'preact/hooks'\n\nconst FOCUSABLE_SELECTOR = [\n 'a[href]',\n 'button:not([disabled])',\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n '[tabindex]:not([tabindex=\"-1\"])',\n].join(',')\n\n/**\n * Trap Tab focus inside `ref`. Pressing Tab on the last focusable element\n * wraps to the first; Shift+Tab on the first wraps to the last. The\n * Popover API doesn't trap focus on its own (popovers are non-modal), so\n * we layer this on top.\n *\n * `getRootNode()` is used to read `activeElement` correctly when the\n * popover lives inside a shadow root.\n */\nexport function useFocusTrap(ref: RefObject<HTMLElement>, enabled: boolean): void {\n useEffect(() => {\n if (!enabled) return\n const root = ref.current\n if (!root) return\n\n function onKey(e: KeyboardEvent) {\n if (e.key !== 'Tab') return\n const focusables = Array.from(root!.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))\n const first = focusables[0]\n const last = focusables[focusables.length - 1]\n if (!first || !last) return\n\n const r = root!.getRootNode()\n const active = r instanceof ShadowRoot ? r.activeElement : document.activeElement\n\n if (e.shiftKey ? active === first : active === last) {\n e.preventDefault()\n ;(e.shiftKey ? last : first).focus()\n }\n }\n\n root.addEventListener('keydown', onKey)\n return () => root.removeEventListener('keydown', onKey)\n }, [ref, enabled])\n}\n","import { useEffect, useState } from 'preact/hooks'\n\n/**\n * Wrap a `Blob` in an object URL for the lifetime of the calling\n * component (or until the blob changes). The previous URL is revoked\n * automatically and the state is reset to `null` when the blob is\n * cleared, so consumers can render an `<img src={url ?? ''}>` without\n * worrying about a dangling revoked URL.\n *\n * The new-thread popover is the only consumer today, but the pattern\n * shows up whenever a transient blob (clipboard paste, drag-drop) needs\n * to be rendered. Keeping this in one place makes adding a second\n * caller free.\n */\nexport function useObjectURL(blob: Blob | null): string | null {\n const [url, setUrl] = useState<string | null>(null)\n\n useEffect(() => {\n if (!blob) {\n setUrl(null)\n return\n }\n const next = URL.createObjectURL(blob)\n setUrl(next)\n return () => URL.revokeObjectURL(next)\n }, [blob])\n\n return url\n}\n","import { useEffect, useRef, useState } from 'preact/hooks'\n\n/**\n * One-time identity capture. Shown the first time a user wants to post.\n *\n * Two paths:\n * - Sign in via the dashboard (popup) — verified \"team\" identity.\n * - Type name + email manually — anonymous identity, persisted to host\n * localStorage so this is asked at most once per site.\n *\n * `isConnecting` reflects \"the host hasn't resolved an identity yet\" —\n * either first-load anon mint is still in flight or we're recovering\n * from a 401 by minting a replacement. The guest path needs a signed\n * identity to attach the post to, so the inputs are disabled with a\n * hint until that resolves. The popup sign-in path is independent of\n * the anon mint, so its button stays enabled.\n */\nexport function AuthorPrompt({\n isPending,\n isConnecting = false,\n isSigningIn = false,\n onSubmit,\n onCancel,\n onSignIn,\n}: {\n isPending: boolean\n isConnecting?: boolean\n /** A popup sign-in is in flight — keep the user from launching another. */\n isSigningIn?: boolean\n onSubmit: (name: string, email?: string) => void\n onCancel: () => void\n onSignIn?: () => void\n}) {\n const [name, setName] = useState('')\n const [email, setEmail] = useState('')\n const ref = useRef<HTMLInputElement>(null)\n\n useEffect(() => {\n ref.current?.focus()\n }, [])\n\n function handleSubmit(e?: Event) {\n e?.preventDefault()\n const trimmedName = name.trim()\n if (!trimmedName || isPending || isConnecting) return\n const trimmedEmail = email.trim()\n onSubmit(trimmedName, trimmedEmail || undefined)\n }\n\n const guestDisabled = isPending || isConnecting\n\n return (\n <form class=\"markup-author-prompt\" onSubmit={handleSubmit}>\n {onSignIn ? (\n <>\n <button\n type=\"button\"\n class=\"markup-btn markup-btn-primary\"\n onClick={onSignIn}\n disabled={isPending || isSigningIn}\n >\n {isSigningIn ? 'Signing in…' : 'Sign in with Markup'}\n </button>\n <p class=\"markup-author-divider\">or continue as a guest</p>\n </>\n ) : (\n <p class=\"markup-eyebrow\">who's leaving feedback?</p>\n )}\n <input\n ref={ref}\n class=\"markup-input\"\n type=\"text\"\n name=\"name\"\n placeholder=\"Your name\"\n value={name}\n maxLength={80}\n autoComplete=\"name\"\n onInput={(e) => setName((e.currentTarget as HTMLInputElement).value)}\n disabled={guestDisabled}\n data-1p-ignore\n />\n <input\n class=\"markup-input\"\n type=\"email\"\n name=\"email\"\n placeholder=\"Email (optional)\"\n value={email}\n maxLength={254}\n autoComplete=\"email\"\n onInput={(e) => setEmail((e.currentTarget as HTMLInputElement).value)}\n disabled={guestDisabled}\n data-1p-ignore\n />\n {isConnecting ? (\n <p class=\"markup-author-status\" role=\"status\" aria-live=\"polite\">\n Connecting…\n </p>\n ) : null}\n <div class=\"markup-composer-actions\">\n <button\n type=\"button\"\n class=\"markup-btn markup-btn-ghost\"\n onClick={onCancel}\n disabled={isPending}\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n class=\"markup-btn markup-btn-primary\"\n disabled={!name.trim() || guestDisabled}\n >\n Continue\n </button>\n </div>\n </form>\n )\n}\n","import { useEffect, useRef, useState } from 'preact/hooks'\n\nimport { cx } from '../utils'\nimport { IconSend } from './icons'\n\nconst MAX_BODY = 4000\n\n/**\n * Reusable text composer used both for the first comment of a new thread and\n * for replies on an existing thread. Submits on Cmd/Ctrl+Enter; auto-grows;\n * disables submit while the parent's submit promise resolves.\n */\nexport function Composer({\n label,\n placeholder = 'Leave feedback…',\n submitLabel = 'Post',\n initialFocus = true,\n isPending,\n error,\n onSubmit,\n}: {\n label: string\n placeholder?: string\n submitLabel?: string\n initialFocus?: boolean\n isPending: boolean\n error?: string\n onSubmit: (body: string) => void\n}) {\n const [value, setValue] = useState('')\n const ref = useRef<HTMLTextAreaElement>(null)\n const wasPending = useRef(false)\n\n useEffect(() => {\n if (initialFocus) ref.current?.focus()\n }, [initialFocus])\n\n // Auto-grow up to ~6 lines.\n useEffect(() => {\n const ta = ref.current\n if (!ta) return\n ta.style.height = 'auto'\n ta.style.height = `${Math.min(ta.scrollHeight, 160)}px`\n }, [value])\n\n // After a successful submit (isPending true → false with no error) clear the\n // value and re-focus so the user can keep typing replies.\n useEffect(() => {\n if (wasPending.current && !isPending && !error) {\n setValue('')\n ref.current?.focus()\n }\n wasPending.current = isPending\n }, [isPending, error])\n\n const remaining = MAX_BODY - value.length\n const isOverLimit = remaining < 0\n\n function handleSubmit(e?: Event) {\n e?.preventDefault()\n const body = value.trim()\n // Mirror the submit button's disabled state. Without the\n // `isOverLimit` check here, Cmd/Ctrl+Enter would fire even though\n // the visible button is greyed — server rejects the body, but UX\n // is inconsistent.\n if (!body || isPending || isOverLimit) return\n onSubmit(body)\n }\n\n function onKey(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {\n handleSubmit(e)\n }\n }\n\n const isFilled = value.length > 0\n\n function submitButton(tabIndex?: number) {\n return (\n <button\n type=\"submit\"\n class=\"markup-btn markup-btn-primary\"\n disabled={isPending || !value.trim() || isOverLimit}\n aria-label={isPending ? 'Sending…' : submitLabel}\n title={isPending ? 'Sending…' : submitLabel}\n tabIndex={tabIndex}\n >\n <IconSend size={14} />\n </button>\n )\n }\n\n return (\n <form class={cx('markup-composer', isFilled && 'is-filled')} onSubmit={handleSubmit}>\n <textarea\n ref={ref}\n name=\"reply\"\n class=\"markup-composer-input\"\n placeholder={placeholder}\n rows={isFilled ? 2 : 1}\n maxLength={MAX_BODY + 100} /* lets us flag over-limit instead of hard truncating */\n value={value}\n onInput={(e) => setValue(e.currentTarget.value)}\n onKeyDown={onKey}\n disabled={isPending}\n aria-label={label}\n />\n {/* Footer always in DOM — height animated via grid-template-rows trick */}\n <div class=\"markup-composer-footer-wrap\">\n <div class=\"markup-composer-footer\">\n <span class=\"markup-composer-hint\">\n {error ? (\n <span class=\"markup-composer-error\">{error}</span>\n ) : isOverLimit ? (\n <span class=\"markup-composer-error\">{Math.abs(remaining)} too long</span>\n ) : (\n <span>⌘↵ to send</span>\n )}\n </span>\n <div class=\"markup-composer-actions\">{submitButton(isFilled ? undefined : -1)}</div>\n </div>\n </div>\n {/* Floating button shown only when empty */}\n <span class=\"markup-composer-actions-empty\" aria-hidden={isFilled || undefined}>\n {submitButton(isFilled ? -1 : undefined)}\n </span>\n </form>\n )\n}\n","import { useEffect, useRef, useState } from 'preact/hooks'\n\nimport { useDrag } from '../use-drag'\nimport { useFocusTrap } from '../use-focus-trap'\nimport { useObjectURL } from '../use-object-url'\nimport { cx } from '../utils'\nimport { AuthorPrompt } from './author-prompt'\nimport { Composer } from './composer'\nimport { IconCamera, IconClose } from './icons'\n\n/**\n * The \"you just dropped a pin\" popover. Either the author-name capture (if\n * we don't have one yet) or the thread composer. Closing it discards the pin.\n *\n * Uses the native Popover API (`popover=\"auto\"`) — ESC and outside-click\n * dismissal are handled by the browser. Position is anchored to the ghost\n * pin via CSS Anchor Positioning (with a JS-clamp fallback).\n */\nexport function NewThreadPopover({\n pageX,\n pageY,\n authorName,\n isVerified,\n isIdentityResolving,\n isSigningIn,\n isPending,\n error,\n screenshot,\n isScreenshotCapturing,\n screenshotRedactedCount,\n screenshotRedactedSelectors,\n onAuthor,\n onSignIn,\n onSubmit,\n onClose,\n}: {\n pageX: number\n pageY: number\n authorName: string | null\n isVerified: boolean\n /** Anon mint hasn't completed yet — disable the guest path. */\n isIdentityResolving: boolean\n /** A popup sign-in is already in flight — disable the sign-in button. */\n isSigningIn: boolean\n isPending: boolean\n error: string | undefined\n screenshot: Blob | null\n isScreenshotCapturing: boolean\n screenshotRedactedCount: number\n screenshotRedactedSelectors: string[]\n onAuthor: (name: string, email?: string) => void\n onSignIn: () => void\n onSubmit: (body: string, includeScreenshot: boolean) => void\n onClose: () => void\n}) {\n const ref = useRef<HTMLDivElement>(null)\n useFocusTrap(ref, true)\n\n const [includeScreenshot, setIncludeScreenshot] = useState(false)\n const [isRedactionExpanded, setIsRedactionExpanded] = useState(false)\n const previewUrl = useObjectURL(screenshot)\n // User-dragged position; `null` means \"use the anchor / fallback coords\".\n // Resets to null on every mount, so reopening snaps back to the pin.\n const [dragPos, setDragPos] = useState<{ left: number; top: number } | null>(null)\n // Drag-to-move from the header. Same shape as ThreadPopover —\n // handle is the header but we measure the popover.\n const { onPointerDown: onHeaderPointerDown, isDragging } = useDrag({\n targetRef: ref,\n shouldStart: (e) => {\n const target = e.target as HTMLElement | null\n return !target?.closest('button, a, input, textarea, select')\n },\n onMove: setDragPos,\n })\n\n useEffect(() => {\n const el = ref.current\n if (!el) return\n\n if (typeof el.showPopover === 'function' && !el.matches(':popover-open')) {\n try {\n el.showPopover()\n } catch {\n /* already showing or unsupported */\n }\n }\n\n function onToggle(e: Event) {\n const ev = e as ToggleEvent\n if (ev.newState === 'closed') onClose()\n }\n el.addEventListener('toggle', onToggle)\n return () => el.removeEventListener('toggle', onToggle)\n }, [onClose])\n\n const width = 320\n const margin = 12\n const left = clamp(pageX - window.scrollX + 16, margin, window.innerWidth - width - margin)\n const top = clamp(pageY - window.scrollY - 16, margin, window.innerHeight - 220)\n\n const hasScreenshot = screenshot != null\n const showScreenshotRow = isScreenshotCapturing || hasScreenshot\n\n return (\n <div\n ref={ref}\n class={cx('markup-popover', dragPos && 'is-floating', isDragging && 'is-dragging')}\n popover=\"auto\"\n style={{\n '--markup-pop-x': `${dragPos?.left ?? left}px`,\n '--markup-pop-y': `${dragPos?.top ?? top}px`,\n }}\n role=\"dialog\"\n aria-label=\"New markup\"\n >\n <header class=\"markup-popover-header\" onPointerDown={onHeaderPointerDown}>\n <span class=\"markup-eyebrow\">new · markup</span>\n <button type=\"button\" class=\"markup-icon-btn\" aria-label=\"Discard pin\" onClick={onClose}>\n <IconClose size={16} />\n </button>\n </header>\n\n {authorName == null ? (\n <AuthorPrompt\n isPending={isPending}\n isConnecting={isIdentityResolving}\n isSigningIn={isSigningIn}\n onSubmit={onAuthor}\n onCancel={onClose}\n onSignIn={onSignIn}\n />\n ) : (\n <div class=\"markup-popover-body\">\n <p class=\"markup-popover-byline\">\n posting as <span class=\"markup-popover-name\">{authorName}</span>\n {isVerified ? <span class=\"markup-comment-badge\">team</span> : null}\n </p>\n <Composer\n label=\"Feedback\"\n placeholder=\"What's wrong, missing, or worth noting?\"\n submitLabel=\"Post markup\"\n isPending={isPending}\n error={error}\n onSubmit={(body) => onSubmit(body, includeScreenshot && hasScreenshot)}\n />\n {showScreenshotRow ? (\n <div class=\"markup-screenshot-row\">\n {isScreenshotCapturing ? (\n <span class=\"markup-screenshot-status\">\n <input type=\"checkbox\" class=\"markup-screenshot-checkbox\" disabled />\n <IconCamera size={12} />\n <span>Capturing…</span>\n </span>\n ) : (\n <label class=\"markup-screenshot-toggle\">\n <input\n type=\"checkbox\"\n class=\"markup-screenshot-checkbox\"\n checked={includeScreenshot}\n onChange={(e) => setIncludeScreenshot(e.currentTarget.checked)}\n />\n <IconCamera size={12} />\n <span>Attach screenshot</span>\n {previewUrl && includeScreenshot ? (\n <img\n class=\"markup-screenshot-thumb\"\n src={previewUrl}\n alt=\"Screenshot preview\"\n />\n ) : null}\n </label>\n )}\n {includeScreenshot && hasScreenshot ? (\n <>\n {screenshotRedactedCount > 0 ? (\n <div class=\"markup-screenshot-redacted\">\n <button\n type=\"button\"\n class=\"markup-screenshot-redacted-chip\"\n onClick={() => setIsRedactionExpanded((v) => !v)}\n >\n <em class=\"markup-screenshot-redacted-arrow\">\n {isRedactionExpanded ? '▾' : '▸'}\n </em>\n {screenshotRedactedCount}{' '}\n {screenshotRedactedCount === 1 ? 'field' : 'fields'} redacted\n </button>\n {isRedactionExpanded ? (\n <div class=\"markup-screenshot-redacted-list\">\n {screenshotRedactedSelectors.map((sel) => (\n <code key={sel} class=\"markup-screenshot-redacted-selector\">\n {sel}\n </code>\n ))}\n </div>\n ) : null}\n </div>\n ) : null}\n <p class=\"markup-screenshot-help\">\n Password and credit-card fields are blacked out automatically. Add{' '}\n <code class=\"markup-screenshot-help-code\">data-markup-private</code> to mask\n anything else.\n </p>\n </>\n ) : null}\n </div>\n ) : null}\n </div>\n )}\n </div>\n )\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n","import { cx } from '../utils'\n\n/**\n * A single anchored pin marker. Position is set inline because it changes on\n * every render (scroll/resize) and Tailwind's compile-time classes can't\n * express dynamic pixel coords.\n */\nexport function Pin({\n pageX,\n pageY,\n count,\n isActive,\n isUnresolved,\n onClick,\n}: {\n pageX: number\n pageY: number\n count: number\n isActive: boolean\n /**\n * `true` when the pin's anchor selector didn't match a live element\n * and we're showing it at the fraction-based fallback position. Surfaces\n * a dimmed style so the wrong-looking position reads as tentative rather\n * than authoritative. Stays clickable — opening the thread is still useful\n * even if the spatial anchor is off.\n */\n isUnresolved: boolean\n onClick: () => void\n}) {\n // The host element is `position: fixed`, so subtract scroll to get\n // viewport-relative coords for `top` / `left`.\n const top = pageY - window.scrollY\n const left = pageX - window.scrollX\n // `popovertarget` tells the browser this button intentionally interacts\n // with the thread popover, so the pointerdown light-dismiss is suppressed\n // when transitioning from one open thread to another.\n return (\n <button\n type=\"button\"\n class={cx('markup-pin', isActive && 'is-active is-anchor', isUnresolved && 'is-unresolved')}\n style={{ top: `${top}px`, left: `${left}px` }}\n popovertarget=\"markup-thread-popover\"\n popovertargetaction=\"show\"\n onClick={onClick}\n aria-label={`Open feedback thread (${count} comment${count === 1 ? '' : 's'})`}\n title={`Open feedback thread (${count} comment${count === 1 ? '' : 's'})`}\n >\n <span class=\"markup-pin-dot\" aria-hidden />\n {count > 1 ? <span class=\"markup-pin-count\">{count}</span> : null}\n </button>\n )\n}\n\n/**\n * Ghost pin shown at the just-clicked location while the composer for a brand\n * new thread is open. Same visual as a real pin, no click handler. Carries\n * `is-anchor` so the new-thread popover can anchor-position to it.\n */\nexport function GhostPin({ pageX, pageY }: { pageX: number; pageY: number }) {\n const top = pageY - window.scrollY\n const left = pageX - window.scrollX\n return (\n <div\n class=\"markup-pin markup-pin-ghost is-anchor\"\n style={{ top: `${top}px`, left: `${left}px` }}\n >\n <span class=\"markup-pin-dot\" aria-hidden />\n </div>\n )\n}\n","import { useEffect } from 'preact/hooks'\n\nimport { toPageCoords, type PageCoords } from '../anchor'\n\n/**\n * Full-viewport overlay that captures the next click and translates it into\n * normalised page coordinates. Mounts only while in placing mode; ESC cancels.\n */\nexport function PlacementOverlay({\n onPlace,\n onCancel,\n}: {\n onPlace: (coords: PageCoords, screenX: number, screenY: number) => void\n onCancel: () => void\n}) {\n useEffect(() => {\n function onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') onCancel()\n }\n window.addEventListener('keydown', onKey)\n return () => window.removeEventListener('keydown', onKey)\n }, [onCancel])\n\n function handleClick(e: MouseEvent) {\n e.stopPropagation()\n e.preventDefault()\n // elementsFromPoint returns light-DOM elements top-to-bottom. Our widget\n // host is the only element with a shadowRoot — skip it to get the real\n // page element underneath the overlay.\n const elements = document.elementsFromPoint(e.clientX, e.clientY)\n const pageTarget = elements.find((el) => !el.shadowRoot) ?? null\n const coords = toPageCoords(e, pageTarget)\n onPlace(coords, e.clientX, e.clientY)\n }\n\n // Prevent the click from bubbling up to the document and triggering dismiss of other elements\n // this works for Radix-UI elements like Popover and Menu\n function handlePointerDown(e: PointerEvent) {\n e.preventDefault()\n e.stopPropagation()\n }\n\n return (\n <div\n class=\"markup-placement-overlay\"\n onPointerDown={handlePointerDown}\n onClick={handleClick}\n role=\"presentation\"\n >\n <div class=\"markup-placement-cursor-help\">\n <span>Click anywhere to drop a pin · ESC to cancel</span>\n </div>\n </div>\n )\n}\n","import { useEffect, useMemo, useRef, useState } from 'preact/hooks'\n\nimport { defineMachine, useMachine } from '../../lib/machine'\nimport { resolveCoords } from '../anchor'\nimport { useDrag } from '../use-drag'\nimport { useFocusTrap } from '../use-focus-trap'\nimport { cx } from '../utils'\nimport { AuthorPrompt } from './author-prompt'\nimport { Composer } from './composer'\nimport { IconCheck, IconClose, IconEllipsis, IconSmile } from './icons'\nimport type { WidgetThread } from '../api'\n\n/**\n * Server validates against the same allow-list — keep this in sync with\n * `convex/lib/reactions.ts#ALLOWED_REACTION_EMOJI`. The order here is\n * the picker's render order; the read shape sorts chips by the same\n * order so chips and picker line up visually.\n */\nconst REACTION_PALETTE = ['👍', '❤️', '🎉', '😮', '😄', '❓'] as const\n\n/**\n * Single source of truth for \"what overlay is currently open inside the\n * thread popover\". Modeled as a discriminated union so the four states\n * (thread menu, per-comment menu, reaction picker, comment editing) are\n * mutually exclusive by construction — opening one atomically closes\n * the others. Confirm-delete arming and the menu/picker direction\n * co-locate inside their parent overlay so they reset for free when\n * the overlay closes.\n */\ntype Overlay =\n | { kind: 'none' }\n | { kind: 'thread-menu'; confirmDelete: boolean }\n | {\n kind: 'comment-menu'\n commentId: string\n direction: 'down' | 'up'\n confirmDelete: boolean\n }\n | { kind: 'reaction-picker'; commentId: string; direction: 'down' | 'up' }\n | { kind: 'editing'; commentId: string; draft: string }\n\n/**\n * Events that mutate `Overlay`. The dual-purpose `toggle-*` events open\n * from `none` and close from the matching kind; `arm-*-delete` is the\n * first half of the two-step confirm-delete pattern (the second half\n * fires the host callback at the call site and then dispatches\n * `dismiss`). Direction is computed at the call site against the\n * scroll container so the pure transitions don't need DOM access.\n */\ntype OverlayEvent =\n | { type: 'toggle-thread-menu' }\n | { type: 'arm-thread-delete' }\n | { type: 'toggle-comment-menu'; commentId: string; direction: 'down' | 'up' }\n | { type: 'arm-comment-delete' }\n | { type: 'toggle-reaction-picker'; commentId: string; direction: 'down' | 'up' }\n | { type: 'start-edit'; commentId: string; body: string }\n | { type: 'update-draft'; draft: string }\n | { type: 'dismiss' }\n\nconst overlayMachine = defineMachine<Overlay, OverlayEvent>({\n none: {\n 'toggle-thread-menu': () => ({ kind: 'thread-menu', confirmDelete: false }),\n 'toggle-comment-menu': (_, e) => ({\n kind: 'comment-menu',\n commentId: e.commentId,\n direction: e.direction,\n confirmDelete: false,\n }),\n 'toggle-reaction-picker': (_, e) => ({\n kind: 'reaction-picker',\n commentId: e.commentId,\n direction: e.direction,\n }),\n 'start-edit': (_, e) => ({ kind: 'editing', commentId: e.commentId, draft: e.body }),\n },\n 'thread-menu': {\n 'toggle-thread-menu': () => ({ kind: 'none' }),\n 'arm-thread-delete': (s) => ({ ...s, confirmDelete: true }),\n dismiss: () => ({ kind: 'none' }),\n },\n 'comment-menu': {\n // Only the matching commentId's ellipsis can re-toggle; events from\n // any other comment fall through as no-ops (the outside-click effect\n // already closes us before a foreign click can land).\n 'toggle-comment-menu': (s, e) => (s.commentId === e.commentId ? { kind: 'none' } : s),\n 'arm-comment-delete': (s) => ({ ...s, confirmDelete: true }),\n // Edit promotes the menu directly into the edit form — the menu is\n // already showing for this comment, so a separate dismiss step would\n // just be visual churn.\n 'start-edit': (_, e) => ({ kind: 'editing', commentId: e.commentId, draft: e.body }),\n dismiss: () => ({ kind: 'none' }),\n },\n 'reaction-picker': {\n 'toggle-reaction-picker': (s, e) => (s.commentId === e.commentId ? { kind: 'none' } : s),\n dismiss: () => ({ kind: 'none' }),\n },\n editing: {\n // Functional-updater guard from the prior `setOverlay((prev) => prev.kind ===\n // 'editing' ? ... : prev)` is now implicit — the machine ignores\n // `update-draft` from any other state automatically.\n 'update-draft': (s, e) => ({ ...s, draft: e.draft }),\n dismiss: () => ({ kind: 'none' }),\n },\n})\n\n/**\n * Popover anchored near a pin showing the thread's comments and a reply\n * composer. Uses the native Popover API (`popover=\"auto\"`) for top-layer\n * rendering, ESC handling, and outside-click dismissal. Position uses CSS\n * Anchor Positioning when supported, falling back to JS-clamped coords passed\n * via custom properties.\n */\nexport function ThreadPopover({\n thread,\n authorName,\n currentClientId,\n isVerified,\n isIdentityResolving,\n isSigningIn,\n canDelete,\n isPending,\n error,\n isHidden = false,\n onAuthor,\n onSignIn,\n onClose,\n onReply,\n onEditComment,\n onDeleteComment,\n onToggleReaction,\n onResolve,\n onDelete,\n}: {\n thread: WidgetThread\n authorName: string | null\n /**\n * The current widget identity's clientId. Used to decide which comments\n * show an Edit affordance — only matches against `comment.authorClientId`\n * count, since the JWT-derived ownership path uses the same canonical\n * `markup_user_<sub>` clientId on both sides.\n */\n currentClientId: string | null\n isVerified: boolean\n /** Anon mint hasn't completed yet — disable the guest path. */\n isIdentityResolving: boolean\n /** A popup sign-in is already in flight — disable the sign-in button. */\n isSigningIn: boolean\n canDelete: boolean\n isPending: boolean\n error: string | undefined\n /**\n * Hide the popover visually while keeping it mounted. Used by the\n * HUD-hide shortcut so an in-progress reply draft, edit, or drag\n * position survives a peek.\n */\n isHidden?: boolean\n onAuthor: (name: string, email?: string) => void\n onSignIn: () => void\n onClose: () => void\n onReply: (body: string) => void\n /**\n * Resolves on a successful save (so the popover can drop out of edit\n * mode) or rejects on failure (so the user can retry from the still-\n * open form).\n */\n onEditComment: (commentId: string, body: string) => Promise<void>\n onDeleteComment: (commentId: string) => void\n /**\n * Toggle a reaction. The host swaps thread state from the server's\n * authoritative response — the popover does no optimistic update, so a\n * misclick simply re-renders with the previous count once the request\n * completes (or the next subscription tick reconciles).\n */\n onToggleReaction: (commentId: string, emoji: string) => void\n onResolve: () => void\n onDelete: () => void\n}) {\n const ref = useRef<HTMLDivElement>(null)\n const commentsRef = useRef<HTMLOListElement>(null)\n const dialogRef = useRef<HTMLDialogElement>(null)\n // Holds the currently-active overlay's container element for the\n // single mousedown-outside-click effect below. Each overlay's\n // wrapper assigns to it via an inline ref callback gated on the\n // overlay being currently active.\n const overlayElRef = useRef<HTMLElement | null>(null)\n const [overlay, sendOverlay] = useMachine(overlayMachine, { kind: 'none' })\n // User-dragged position; `null` means \"use the anchor / fallback coords\".\n // Resets to null on every mount, so reopening a thread snaps the popover\n // back to its pin.\n const [dragPos, setDragPos] = useState<{ left: number; top: number } | null>(null)\n // Drag-to-move from the header. Buttons inside the header are excluded\n // (so their clicks still work); the *handle* is the header but the\n // *target* whose rect we measure is the popover itself, since that's\n // what's actually being moved.\n const { onPointerDown: onHeaderPointerDown, isDragging } = useDrag({\n targetRef: ref,\n shouldStart: (e) => {\n const target = e.target as HTMLElement | null\n return !target?.closest('button, a, input, textarea, select')\n },\n onMove: setDragPos,\n })\n useFocusTrap(ref, true)\n\n const isResolved = thread.resolvedAt != null\n // Tombstoned comments are dropped from the rendered list — soft-delete\n // exists for referential integrity (reactions, audit log) but the user\n // doesn't need to see \"Comment deleted\" placeholders cluttering the\n // thread. The first-comment guard on the server still uses the real\n // earliest comment, so even if a deleted row precedes everything\n // visible, the user can't accidentally delete what now appears to be\n // the \"first\" comment.\n const visibleComments = useMemo(\n () => thread.comments.filter((c) => !c.deleted),\n [thread.comments],\n )\n\n // Single outside-click handler that covers all four overlay kinds.\n // Each overlay's wrapper writes its element to `overlayElRef` via an\n // inline ref callback while it's the active overlay; clicks outside\n // that element close the overlay. Closing automatically resets any\n // confirm-delete arming because that lives inside the overlay's\n // discriminated state.\n useEffect(() => {\n if (overlay.kind === 'none' || overlay.kind === 'editing') return\n function onDown(e: MouseEvent) {\n const el = overlayElRef.current\n if (el && !e.composedPath().includes(el)) {\n sendOverlay({ type: 'dismiss' })\n }\n }\n document.addEventListener('mousedown', onDown)\n return () => document.removeEventListener('mousedown', onDown)\n }, [overlay.kind, sendOverlay])\n\n // If the comment we're editing disappears from the thread (e.g., the\n // thread reloads without it), drop out of edit mode. Successful saves\n // are handled in the form's submit handler — we await onEditComment\n // and only cancel on resolve, so a save that fails leaves the draft\n // intact for the user to retry.\n useEffect(() => {\n if (overlay.kind !== 'editing') return\n const c = thread.comments.find((c) => c._id === overlay.commentId)\n if (!c || c.deleted) sendOverlay({ type: 'dismiss' })\n }, [thread.comments, overlay, sendOverlay])\n\n const isFirstOpen = useRef(true)\n useEffect(() => {\n const el = commentsRef.current\n if (!el) return\n if (isFirstOpen.current) {\n isFirstOpen.current = false\n el.scrollTop = el.scrollHeight\n return\n }\n const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight\n if (distanceFromBottom < 80) el.scrollTop = el.scrollHeight\n }, [visibleComments.length])\n\n // Promote into the top layer on mount; sync state when the browser closes\n // it (ESC, outside-click, programmatic).\n useEffect(() => {\n const el = ref.current\n if (!el) return\n\n if (typeof el.showPopover === 'function' && !el.matches(':popover-open')) {\n try {\n el.showPopover()\n } catch {\n /* element may already be showing or unsupported */\n }\n }\n\n function onToggle(e: Event) {\n const ev = e as ToggleEvent\n if (ev.newState === 'closed') onClose()\n }\n el.addEventListener('toggle', onToggle)\n return () => el.removeEventListener('toggle', onToggle)\n }, [onClose])\n\n // Fallback coords for browsers without anchor positioning.\n const fallback = useMemo(() => {\n const point = resolveCoords({\n anchorX: thread.anchorX,\n anchorY: thread.anchorY,\n anchorSelector: thread.anchorSelector,\n })\n const width = 320\n const margin = 12\n const left = clamp(\n point.pageX - window.scrollX + 16,\n margin,\n window.innerWidth - width - margin,\n )\n const top = clamp(point.pageY - window.scrollY - 16, margin, window.innerHeight - 200)\n return { left, top }\n }, [thread.anchorX, thread.anchorY, thread.anchorSelector])\n\n return (\n <div\n ref={ref}\n id=\"markup-thread-popover\"\n class={cx(\n 'markup-popover',\n dragPos && 'is-floating',\n isDragging && 'is-dragging',\n isHidden && 'is-hud-hidden',\n )}\n popover=\"auto\"\n style={{\n '--markup-pop-x': `${dragPos?.left ?? fallback.left}px`,\n '--markup-pop-y': `${dragPos?.top ?? fallback.top}px`,\n }}\n role=\"dialog\"\n aria-label=\"Markup thread\"\n aria-hidden={isHidden || undefined}\n >\n <header class=\"markup-popover-header\" onPointerDown={onHeaderPointerDown}>\n <span class=\"markup-eyebrow\">\n thread · {visibleComments.length} {visibleComments.length === 1 ? 'comment' : 'comments'}\n </span>\n <div class=\"markup-popover-header-actions\">\n <div\n class=\"markup-thread-menu\"\n ref={(el) => {\n if (overlay.kind === 'thread-menu') overlayElRef.current = el\n }}\n >\n <button\n type=\"button\"\n class={cx('markup-icon-btn', overlay.kind === 'thread-menu' && 'is-open')}\n title=\"More options\"\n onClick={() => sendOverlay({ type: 'toggle-thread-menu' })}\n >\n <IconEllipsis size={16} />\n </button>\n {overlay.kind === 'thread-menu' ? (\n <div class=\"markup-thread-menu-list\">\n <button\n type=\"button\"\n class=\"markup-thread-menu-item\"\n onClick={() => {\n const url = new URL(thread.url)\n url.hash = `markup-thread=${thread._id}`\n navigator.clipboard.writeText(url.toString()).catch(() => {})\n sendOverlay({ type: 'dismiss' })\n }}\n >\n Copy link\n </button>\n {canDelete ? (\n <button\n type=\"button\"\n class={cx('markup-thread-menu-item', overlay.confirmDelete && 'is-danger')}\n disabled={isPending}\n onClick={() => {\n // Two-step: first click arms (confirmDelete: true),\n // second click commits via the host then dismisses.\n if (overlay.kind !== 'thread-menu') return\n if (overlay.confirmDelete) {\n sendOverlay({ type: 'dismiss' })\n onDelete()\n } else {\n sendOverlay({ type: 'arm-thread-delete' })\n }\n }}\n >\n {overlay.confirmDelete ? 'Confirm delete' : 'Delete thread…'}\n </button>\n ) : null}\n </div>\n ) : null}\n </div>\n {isVerified ? (\n <button\n type=\"button\"\n class=\"markup-icon-btn\"\n title=\"Mark as resolved\"\n disabled={isPending}\n onClick={onResolve}\n >\n <IconCheck size={16} />\n </button>\n ) : null}\n <button type=\"button\" class=\"markup-icon-btn\" title=\"Close thread\" onClick={onClose}>\n <IconClose size={16} />\n </button>\n </div>\n </header>\n\n <ol ref={commentsRef} class=\"markup-comments\">\n {visibleComments.map((c, i) => {\n const isOwn =\n !c.fromDashboard && currentClientId != null && c.authorClientId === currentClientId\n const isFirst = i === 0\n const canEdit = isOwn && !isResolved && !c.deleted\n const canDelete = isOwn && !isResolved && !c.deleted && !isFirst\n const isEditing = overlay.kind === 'editing' && overlay.commentId === c._id\n const hasMenu = (canEdit || canDelete) && !isEditing && !c.deleted\n const isMenuOpen = overlay.kind === 'comment-menu' && overlay.commentId === c._id\n const isDeletePending = isMenuOpen && overlay.confirmDelete\n const isPickerOpen = overlay.kind === 'reaction-picker' && overlay.commentId === c._id\n const pickerDirection = isPickerOpen ? overlay.direction : 'down'\n const menuDirection = isMenuOpen ? overlay.direction : 'down'\n return (\n <li key={c._id} class={cx('markup-comment', c.fromDashboard && 'is-team')}>\n <div class=\"markup-comment-meta\">\n <span class=\"markup-comment-author\">{c.authorName}</span>\n {c.fromDashboard ? <span class=\"markup-comment-badge\">team</span> : null}\n <time\n class=\"markup-comment-time\"\n datetime={new Date(c.createdAt).toISOString()}\n title={formatTime(c.createdAt)}\n >\n {relativeTime(c.createdAt)}\n </time>\n <div class=\"markup-thread-actions\">\n {!isResolved && !isEditing ? (\n <ReactionAdd\n comment={c}\n pickerOpen={isPickerOpen}\n pickerDirection={pickerDirection}\n pickerSide={visibleComments.length === 1}\n pickerRef={(el) => {\n if (isPickerOpen) overlayElRef.current = el\n }}\n onPickerClick={(e) => {\n if (isPickerOpen) {\n sendOverlay({\n type: 'toggle-reaction-picker',\n commentId: c._id,\n direction: 'down',\n })\n return\n }\n // With a single comment the popover is too short\n // for a vertical picker to fit; we anchor it to\n // the left of the trigger instead (see `.is-side`).\n if (visibleComments.length === 1) {\n sendOverlay({\n type: 'toggle-reaction-picker',\n commentId: c._id,\n direction: 'down',\n })\n return\n }\n // Same flip-above measurement as the comment menu\n // — the picker is taller (one row of 6 chips\n // ~36px), so we account for that explicitly.\n const trigger = e.currentTarget as HTMLElement\n const triggerRect = trigger.getBoundingClientRect()\n const containerRect = commentsRef.current?.getBoundingClientRect()\n const estimatedHeight = 44\n const spaceBelow = containerRect\n ? containerRect.bottom - triggerRect.bottom\n : Number.POSITIVE_INFINITY\n sendOverlay({\n type: 'toggle-reaction-picker',\n commentId: c._id,\n direction: spaceBelow < estimatedHeight ? 'up' : 'down',\n })\n }}\n onPickerSelect={(emoji) => {\n sendOverlay({ type: 'dismiss' })\n onToggleReaction(c._id, emoji)\n }}\n />\n ) : null}\n {hasMenu ? (\n <div\n class={cx(\n 'markup-thread-menu markup-comment-menu',\n isMenuOpen && 'is-open',\n isMenuOpen && menuDirection === 'up' && 'is-up',\n visibleComments.length === 1 && 'is-side',\n )}\n ref={(el: HTMLDivElement | null) => {\n if (isMenuOpen) overlayElRef.current = el\n }}\n >\n <button\n type=\"button\"\n class={cx('markup-icon-btn', isMenuOpen && 'is-open')}\n title=\"More options\"\n onClick={(e) => {\n if (isMenuOpen) {\n sendOverlay({\n type: 'toggle-comment-menu',\n commentId: c._id,\n direction: 'down',\n })\n return\n }\n // With a single comment, the popover is too short\n // for a vertical dropdown to fit, so we open it to\n // the left of the trigger (see `.is-side` in CSS)\n // and skip the up/down measurement entirely.\n if (visibleComments.length === 1) {\n sendOverlay({\n type: 'toggle-comment-menu',\n commentId: c._id,\n direction: 'down',\n })\n return\n }\n // Decide direction before opening so the dropdown\n // never appears clipped at the bottom of the scroll\n // container. Estimate menu height from the visible\n // items (~32px per item + 8px padding).\n const trigger = e.currentTarget as HTMLElement\n const triggerRect = trigger.getBoundingClientRect()\n const containerRect = commentsRef.current?.getBoundingClientRect()\n const itemCount = (canEdit ? 1 : 0) + (canDelete ? 1 : 0)\n const estimatedHeight = itemCount * 32 + 8 + 6\n const spaceBelow = containerRect\n ? containerRect.bottom - triggerRect.bottom\n : Number.POSITIVE_INFINITY\n sendOverlay({\n type: 'toggle-comment-menu',\n commentId: c._id,\n direction: spaceBelow < estimatedHeight ? 'up' : 'down',\n })\n }}\n >\n <IconEllipsis size={16} />\n </button>\n {isMenuOpen ? (\n <div class=\"markup-thread-menu-list\">\n {canEdit ? (\n <button\n type=\"button\"\n class=\"markup-thread-menu-item\"\n onClick={() => {\n sendOverlay({\n type: 'start-edit',\n commentId: c._id,\n body: c.body,\n })\n }}\n >\n Edit\n </button>\n ) : null}\n {canDelete ? (\n <button\n type=\"button\"\n class={cx('markup-thread-menu-item', isDeletePending && 'is-danger')}\n onClick={() => {\n if (overlay.kind !== 'comment-menu') return\n if (overlay.confirmDelete) {\n sendOverlay({ type: 'dismiss' })\n onDeleteComment(c._id)\n } else {\n sendOverlay({ type: 'arm-comment-delete' })\n }\n }}\n >\n {isDeletePending ? 'Confirm delete' : 'Delete…'}\n </button>\n ) : null}\n </div>\n ) : null}\n </div>\n ) : null}\n </div>\n </div>\n {isEditing && overlay.kind === 'editing' ? (\n <form\n class=\"markup-comment-edit-form\"\n onSubmit={async (e) => {\n e.preventDefault()\n if (overlay.kind !== 'editing') return\n const next = overlay.draft.trim()\n if (!next || next === c.body) {\n sendOverlay({ type: 'dismiss' })\n return\n }\n try {\n await onEditComment(c._id, next)\n sendOverlay({ type: 'dismiss' })\n } catch {\n /* leave the form open so the user can fix and retry;\n * the host renders the error toast from `error`. */\n }\n }}\n >\n <textarea\n class=\"markup-textarea\"\n value={overlay.draft}\n onInput={(e) => {\n sendOverlay({\n type: 'update-draft',\n draft: (e.currentTarget as HTMLTextAreaElement).value,\n })\n }}\n rows={3}\n autoFocus\n disabled={isPending}\n />\n <div class=\"markup-comment-edit-actions\">\n <button\n type=\"button\"\n class=\"markup-btn markup-btn-ghost\"\n onClick={() => sendOverlay({ type: 'dismiss' })}\n disabled={isPending}\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n class=\"markup-btn markup-btn-primary\"\n disabled={isPending || overlay.draft.trim().length === 0}\n >\n Save\n </button>\n </div>\n </form>\n ) : (\n <p class=\"markup-comment-body\">\n {c.body}\n {c.editedAt != null ? (\n <time\n class=\"markup-comment-edited\"\n datetime={new Date(c.editedAt).toISOString()}\n title={formatTime(c.editedAt)}\n >\n {' '}\n (edited)\n </time>\n ) : null}\n </p>\n )}\n {i === 0 && thread.screenshotUrl ? (\n <button\n type=\"button\"\n class=\"markup-comment-screenshot\"\n onClick={() => dialogRef.current?.showModal()}\n >\n <img src={thread.screenshotUrl} alt=\"Screenshot\" />\n </button>\n ) : null}\n {!isEditing && c.reactions.length > 0 ? (\n <ReactionChips\n comment={c}\n isResolved={isResolved}\n onToggle={(emoji) => onToggleReaction(c._id, emoji)}\n />\n ) : null}\n </li>\n )\n })}\n </ol>\n\n {thread.screenshotUrl ? (\n <dialog ref={dialogRef} class=\"markup-lightbox\" onClick={() => dialogRef.current?.close()}>\n <button\n type=\"button\"\n class=\"markup-lightbox-close markup-icon-btn\"\n aria-label=\"Close screenshot\"\n onClick={(e) => {\n e.stopPropagation()\n dialogRef.current?.close()\n }}\n >\n <IconClose size={16} />\n </button>\n <img\n class=\"markup-lightbox-img\"\n src={thread.screenshotUrl}\n alt=\"Screenshot\"\n onClick={(e) => e.stopPropagation()}\n />\n </dialog>\n ) : null}\n\n {authorName == null ? (\n <AuthorPrompt\n isPending={isPending}\n isConnecting={isIdentityResolving}\n isSigningIn={isSigningIn}\n onSubmit={onAuthor}\n onCancel={onClose}\n onSignIn={onSignIn}\n />\n ) : (\n <div class=\"markup-popover-body\">\n <p class=\"markup-popover-byline\">\n replying as <span class=\"markup-popover-name\">{authorName}</span>\n {isVerified ? <span class=\"markup-comment-badge\">team</span> : null}\n </p>\n <Composer\n label=\"Reply\"\n placeholder=\"Write a reply…\"\n submitLabel=\"Reply\"\n initialFocus={false}\n isPending={isPending}\n error={error}\n onSubmit={onReply}\n />\n </div>\n )}\n </div>\n )\n}\n\n/**\n * The \"+\" reaction trigger that lives at the right end of the comment\n * body row. Hidden by default and revealed on comment hover (or while\n * the picker is open) so the row stays visually quiet for unreacted\n * comments. Resolved threads omit it entirely.\n */\nfunction ReactionAdd({\n comment,\n pickerOpen,\n pickerDirection,\n pickerSide,\n pickerRef,\n onPickerClick,\n onPickerSelect,\n}: {\n comment: WidgetThread['comments'][number]\n pickerOpen: boolean\n pickerDirection: 'down' | 'up'\n pickerSide: boolean\n pickerRef: (el: HTMLDivElement | null) => void\n onPickerClick: (e: MouseEvent) => void\n onPickerSelect: (emoji: string) => void\n}) {\n return (\n <div\n class={cx(\n 'markup-reaction-picker-wrap',\n pickerOpen && 'is-open',\n pickerOpen && pickerDirection === 'up' && 'is-up',\n pickerSide && 'is-side',\n )}\n ref={pickerRef}\n >\n <button\n type=\"button\"\n class={cx('markup-icon-btn', pickerOpen && 'is-open')}\n title=\"Add reaction\"\n aria-label=\"Add reaction\"\n onClick={onPickerClick}\n >\n <IconSmile size={16} />\n </button>\n {pickerOpen ? (\n <div class=\"markup-reaction-picker\" role=\"menu\">\n {REACTION_PALETTE.map((emoji) => {\n const mine = comment.reactions.find((r) => r.emoji === emoji)?.mine ?? false\n return (\n <button\n key={emoji}\n type=\"button\"\n role=\"menuitem\"\n class={cx('markup-reaction-picker-item', mine && 'is-mine')}\n onClick={() => onPickerSelect(emoji)}\n >\n {emoji}\n </button>\n )\n })}\n </div>\n ) : null}\n </div>\n )\n}\n\n/**\n * Chip strip rendered below the comment body when at least one\n * reaction exists. Resolved threads still render the chips so the\n * history is readable, but each chip is non-interactive.\n */\nfunction ReactionChips({\n comment,\n isResolved,\n onToggle,\n}: {\n comment: WidgetThread['comments'][number]\n isResolved: boolean\n onToggle: (emoji: string) => void\n}) {\n return (\n <div class=\"markup-reactions\">\n {comment.reactions.map((r) => {\n const tooltip = formatReactors(r.reactors, r.mine, r.count, r.emoji)\n return (\n <button\n key={r.emoji}\n type=\"button\"\n class={cx('markup-reaction-chip', r.mine && 'is-mine')}\n disabled={isResolved}\n onClick={() => onToggle(r.emoji)}\n aria-pressed={r.mine}\n aria-label={tooltip}\n title={tooltip}\n >\n <span class=\"markup-reaction-emoji\" aria-hidden>\n {r.emoji}\n </span>\n <span class=\"markup-reaction-count\">{r.count}</span>\n </button>\n )\n })}\n </div>\n )\n}\n\n/**\n * Builds the chip tooltip: \"Alice, Bob and you reacted with 👍\".\n * The server already strips the viewer's own row from `reactors`, so\n * `mine` is the only signal that adds \"you\". `count` may exceed\n * `reactors.length + (mine ? 1 : 0)` when anon reactors didn't supply\n * a name — those collapse into an \"and N other(s)\" clause so the\n * tooltip and the chip count always agree.\n */\nfunction formatReactors(reactors: string[], mine: boolean, count: number, emoji: string): string {\n const parts: string[] = reactors.slice()\n const accountedFor = parts.length + (mine ? 1 : 0)\n const anonExtra = Math.max(0, count - accountedFor)\n if (anonExtra > 0) {\n parts.push(`${anonExtra} other${anonExtra === 1 ? '' : 's'}`)\n }\n if (mine) parts.push('you')\n if (parts.length === 0) return `${count} reacted with ${emoji}`\n const subject =\n parts.length === 1\n ? parts[0]\n : `${parts.slice(0, -1).join(', ')} and ${parts[parts.length - 1]}`\n return `${subject} reacted with ${emoji}`\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n\nfunction relativeTime(ts: number): string {\n const diff = Date.now() - ts\n const sec = Math.floor(diff / 1000)\n if (sec < 60) return 'just now'\n const min = Math.floor(sec / 60)\n if (min < 60) return `${min} minute${min === 1 ? '' : 's'} ago`\n const hr = Math.floor(min / 60)\n if (hr < 24) return `${hr} hour${hr === 1 ? '' : 's'} ago`\n const day = Math.floor(hr / 24)\n if (day < 30) return `${day} day${day === 1 ? '' : 's'} ago`\n const isSameYear = new Date(ts).getFullYear() === new Date().getFullYear()\n if (isSameYear) {\n return new Date(ts).toLocaleDateString([], {\n month: 'long',\n day: 'numeric',\n })\n }\n return new Date(ts).toLocaleDateString([], {\n month: 'long',\n day: 'numeric',\n year: 'numeric',\n })\n}\n\nfunction formatTime(ts: number): string {\n const date = new Date(ts)\n return date.toLocaleDateString([], {\n month: 'long',\n day: 'numeric',\n year: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n })\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks'\nimport { ConvexClient } from 'convex/browser'\nimport { makeFunctionReference } from 'convex/server'\n\nimport { defineMachine, useMachine } from '../../lib/machine'\nimport { useAsyncAction } from '../../lib/use-async-action'\nimport { resolveCoords, type PageCoords } from '../anchor'\nimport { createApiClient, type WidgetApiClient, type WidgetThread } from '../api'\nimport { subscribeToRouteChanges } from '../history-observer'\nimport {\n type AnonIdentity,\n type IdentityState,\n type VerifiedIdentity,\n authorFieldsOf,\n clientIdOf,\n displayNameOf,\n loadIdentity,\n saveIdentity,\n} from '../identity-store'\nimport { type PopupResult, signInWithPopup } from '../popup-auth'\nimport { captureScreenshot, type ScrubConfig } from '../screenshot'\nimport { useSubscriptionToken } from '../use-subscription-token'\nimport { cx } from '../utils'\nimport { Fab } from './fab'\nimport { NewThreadPopover } from './new-thread-popover'\nimport { Pin, GhostPin } from './pin'\nimport { PlacementOverlay } from './placement-overlay'\nimport { ThreadPopover } from './thread-popover'\n\ntype FabPosition = 'bottom-right' | 'bottom-left' | 'bottom-center'\n\ntype FabVariant = 'default' | 'icon-only'\n\ntype ScreenshotsConfig = {\n enabled?: boolean\n strictScrub?: boolean\n redactSelector?: string\n}\n\nexport type AppProps = {\n apiUrl: string\n apiKey: string\n position?: FabPosition\n fab?: FabVariant\n screenshots?: ScreenshotsConfig\n}\n\n/**\n * Build a `VerifiedIdentity` from the popup's response. Returns `null`\n * if the popup didn't include a usable JWT — the discriminated union\n * requires `token`/`tokenExpiresAt` to be present, so we can't fabricate\n * a `verified` state without them.\n */\nfunction verifiedFromPopup(result: PopupResult): VerifiedIdentity | null {\n if (!result.token || result.tokenExpiresAt == null) return null\n return {\n clientId: `markup_user_${result.identity.id}`,\n token: result.token,\n tokenExpiresAt: result.tokenExpiresAt,\n name: result.identity.name,\n email: result.identity.email,\n }\n}\n\ntype Mode =\n | { kind: 'idle' }\n | { kind: 'placing' }\n | {\n kind: 'composing-new'\n coords: PageCoords\n pageX: number\n pageY: number\n screenshot: Blob | null\n isScreenshotCapturing: boolean\n screenshotRedactedCount: number\n screenshotRedactedSelectors: string[]\n /**\n * Monotonic id of the placement gesture that started this composer.\n * The async screenshot resolver compares against this to discard\n * stale captures from a prior place→cancel→place sequence — without\n * the guard, an in-flight capture for placement A could land its\n * blob in the composer for placement B.\n */\n captureToken: number\n }\n | { kind: 'thread'; threadId: string }\n\n// Scope key for a thread's location. Includes `host` so that the same\n// pathname served from different origins (e.g. two Vercel preview\n// deployments of the same branch, staging vs production, or a custom\n// domain vs its *.vercel.app twin) maps to distinct routes — otherwise\n// threads created on one deployment would leak into all the others.\nfunction currentRoute() {\n return window.location.host + window.location.pathname\n}\n\n/**\n * Widget HUD visibility state. Replaces the prior `hudHidden` +\n * `hudHiddenToast` boolean pair, which had a structurally invalid\n * combination (`hudHidden=false && hudHiddenToast=true`) that an\n * effect had to actively reconcile. The FAB-hide button and the\n * keyboard chord (⌘/Ctrl + .) feed different events so only the\n * FAB-initiated hide surfaces the instructional toast — keyboard\n * users already know the shortcut.\n */\ntype HudState = { kind: 'visible' } | { kind: 'hidden-with-toast' } | { kind: 'hidden' }\n\ntype HudEvent = { type: 'hide-with-toast' } | { type: 'toggle' } | { type: 'dismiss-toast' }\n\nconst hudMachine = defineMachine<HudState, HudEvent>({\n visible: {\n 'hide-with-toast': () => ({ kind: 'hidden-with-toast' }),\n toggle: () => ({ kind: 'hidden' }),\n },\n 'hidden-with-toast': {\n toggle: () => ({ kind: 'visible' }),\n 'dismiss-toast': () => ({ kind: 'hidden' }),\n },\n hidden: {\n toggle: () => ({ kind: 'visible' }),\n },\n})\n\n/**\n * Identity lifecycle as a state machine over the existing `IdentityState`\n * union from `identity-store.ts`. Transitions:\n *\n * unresolved → mint-success → anon\n * unresolved/anon/recovering → signed-in → verified\n * verified → signed-in → verified (re-auth refresh)\n * verified → unauthorized → recovering (401 on a Bearer write)\n * recovering → mint-success → anon (post-401 anon mint completed)\n * anon → author-set → anon (with name/email merged in)\n *\n * Replaces the prior orchestration:\n * - `setIdentity` + `saveIdentity` calls sprinkled across `signIn`,\n * `handleAuthor`, `onUnauthorized`, and the bootstrap effect.\n * - `mintNonce`, a counter that existed solely to re-fire the bootstrap\n * effect after a 401. The bootstrap effect now re-fires naturally\n * because the state transition `verified → recovering` flips\n * `identity.kind`, which is in its dep array.\n *\n * Events that don't fit the current state are silent no-ops (e.g.\n * `anon → unauthorized` is ignored — anon-token 401s aren't on the\n * recovery path, matching the prior `if (s.kind !== 'verified') return`\n * guard in the api callback).\n */\ntype IdentityEvent =\n | { type: 'mint-success'; identity: AnonIdentity }\n | { type: 'signed-in'; identity: VerifiedIdentity }\n | { type: 'unauthorized' }\n | { type: 'author-set'; name: string; email?: string }\n\n/**\n * Persist the next state and return it. Embedding persistence directly\n * in the transitions means every `setIdentity` site automatically writes\n * to storage — no separate `useEffect([identity])` to remember, and no\n * redundant write on mount (the bootstrap loads from storage; persisting\n * back would re-write what we just read). The transition functions are\n * no longer strictly pure, but the impurity is localized: `useMachine`\n * itself doesn't know about persistence, and other machines in the\n * widget (HUD, overlay, token, async-action) stay fully pure.\n */\nfunction persist(next: IdentityState): IdentityState {\n saveIdentity(next)\n return next\n}\n\nconst identityMachine = defineMachine<IdentityState, IdentityEvent>({\n unresolved: {\n 'mint-success': (_, e) => persist({ kind: 'anon', identity: e.identity }),\n 'signed-in': (_, e) => persist({ kind: 'verified', identity: e.identity }),\n },\n anon: {\n 'signed-in': (_, e) => persist({ kind: 'verified', identity: e.identity }),\n 'author-set': (s, e) =>\n persist({\n kind: 'anon',\n identity: { ...s.identity, name: e.name, email: e.email },\n }),\n },\n verified: {\n 'signed-in': (_, e) => persist({ kind: 'verified', identity: e.identity }),\n unauthorized: (s) =>\n persist({\n kind: 'recovering',\n preserved: { name: s.identity.name, email: s.identity.email },\n }),\n },\n recovering: {\n 'mint-success': (_, e) => persist({ kind: 'anon', identity: e.identity }),\n 'signed-in': (_, e) => persist({ kind: 'verified', identity: e.identity }),\n },\n})\n\nexport function App({\n apiUrl,\n apiKey,\n position = 'bottom-right',\n fab = 'default',\n screenshots,\n}: AppProps) {\n const [route, setRoute] = useState(currentRoute)\n const [threads, setThreads] = useState<WidgetThread[]>([])\n const [threadsLoaded, setThreadsLoaded] = useState(false)\n\n // Read storage once. The machine starts from whatever was persisted —\n // anon/verified resumes seamlessly; missing or partial records start\n // `unresolved` and the bootstrap effect mints. `preserved` is the\n // name/email pulled out of a partial record, used to roundtrip the\n // user's display fields through the very first mint.\n const initialIdentity = useMemo(() => loadIdentity(), [])\n const [identity, sendIdentity] = useMachine(identityMachine, initialIdentity.state)\n\n // Effective FAB corner. Initialized from the prop, but the user can\n // drag the FAB across the viewport midline to flip corners; the toast\n // mirrors the same corner.\n const [fabPosition, setFabPosition] = useState<FabPosition>(position)\n\n // Identity is read on every request so the api client always sees the\n // freshest token without being recreated on identity changes — see the\n // `onUnauthorized` callback below, which dispatches into the machine\n // to transition `verified → recovering` and let the bootstrap effect\n // re-mint anon on the next render cycle.\n const identityRef = useRef<IdentityState>(identity)\n identityRef.current = identity\n\n const api = useMemo<WidgetApiClient>(\n () =>\n createApiClient({\n apiUrl,\n apiKey,\n getToken: () => {\n const s = identityRef.current\n if (s.kind !== 'verified') return null\n return { token: s.identity.token, expiresAt: s.identity.tokenExpiresAt }\n },\n getAnonToken: () => {\n const s = identityRef.current\n // The verified bearer takes precedence — sending the anon\n // header alongside is harmless but redundant, so skip.\n if (s.kind !== 'anon') return null\n return s.identity.anonToken\n },\n onUnauthorized: () => {\n // The machine only defines `verified.unauthorized`, so a 401\n // arriving after the downgrade has propagated (e.g., the\n // second of a burst of concurrent verified requests) is a\n // silent no-op — no re-bump, no restarted mint loop.\n sendIdentity({ type: 'unauthorized' })\n },\n }),\n [apiUrl, apiKey, sendIdentity],\n )\n const [mode, setMode] = useState<Mode>({ kind: 'idle' })\n\n /**\n * Shared async-action machine for user-initiated writes (post, reply,\n * delete, edit, resolve). Surfaces `isPending` to gray out the popover\n * during the in-flight request and `error` to display the failure.\n * Re-entrant `run` calls while pending are silently dropped, which\n * subsumes the old per-handler guards. A separate machine for sign-in\n * isolates `isSigningIn` from the popover-wide `isPending` flag.\n */\n const action = useAsyncAction()\n const signInAction = useAsyncAction()\n /**\n * Reactions deliberately bypass `isPending` — graying out the whole\n * popover for every emoji click would feel terrible — but still feed\n * the shared `error` surface on failure via a dedicated machine.\n */\n const reactionAction = useAsyncAction()\n\n // Destructured up-front so the resulting `run`/`reset` references stay\n // stable across renders (the machine memoizes them) and can be safely\n // listed in effect/callback dep arrays — accessing them via\n // `action.run` would force `action` (a fresh object literal every\n // render) into deps and re-fire on every render.\n const { run: runAction, reset: resetAction } = action\n const { run: runSignIn } = signInAction\n const { run: runReaction, reset: resetReaction } = reactionAction\n\n const isPending = action.isPending\n // Preference order: most recent direct action error, then sign-in,\n // then reaction. In practice only one is set at a time because the\n // actions are user-initiated and serialized through the UI.\n const error = action.error ?? signInAction.error ?? reactionAction.error\n\n const [hud, sendHud] = useMachine(hudMachine, { kind: 'visible' })\n const isHudHidden = hud.kind !== 'visible'\n\n const [tick, forceTick] = useState(0) // re-render on scroll/resize\n\n // Ref to the widget's shadow host element so it can be excluded from screenshots\n const rootRef = useRef<HTMLDivElement>(null)\n\n const authorName = displayNameOf(identity)\n const isVerified = identity.kind === 'verified'\n // While `identity` is unresolved or recovering we have no signed\n // clientId to attach a post to. The author prompt uses this to\n // disable the guest path (sign-in is independent and stays\n // available) until the bootstrap mint resolves or a 401-recovery\n // mint completes.\n const isIdentityResolving = identity.kind === 'unresolved' || identity.kind === 'recovering'\n const currentClientId = clientIdOf(identity)\n\n /* — anon-identity mint loop —\n *\n * Fires whenever the machine sits at `unresolved` (first load with no\n * stored signed identity) or `recovering` (post-401 downgrade). Loops\n * with exponential backoff until `mintAnonIdentity()` resolves, then\n * dispatches `mint-success` — the machine transitions to `anon` and\n * the effect's own dep array reads `identity.kind === 'anon'` on the\n * next render and bails. Cancellation drops in-flight results from a\n * superseded mint (e.g. a sign-in lands while a retry is pending).\n *\n * Replaces the prior `mintNonce`-bump trigger: state.kind itself is\n * the trigger now, so the bootstrap re-runs naturally on `verified →\n * recovering` without a counter or imperative re-fire. */\n useEffect(() => {\n if (identity.kind !== 'unresolved' && identity.kind !== 'recovering') return\n // While `unresolved` (first mount) the bootstrap had no in-memory\n // preserved fields, so it falls back to whatever loadIdentity()\n // pulled out of storage. After a 401, `recovering` carries them in\n // the variant itself — no second storage read needed.\n const preserved =\n identity.kind === 'recovering' ? identity.preserved : initialIdentity.preserved\n\n let cancelled = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let backoffMs = 1_000\n\n function mint() {\n api\n .mintAnonIdentity()\n .then(({ clientId, token }) => {\n if (cancelled) return\n const minted: AnonIdentity = {\n clientId,\n anonToken: token,\n name: preserved.name,\n email: preserved.email,\n }\n sendIdentity({ type: 'mint-success', identity: minted })\n })\n .catch(() => {\n if (cancelled) return\n const next = Math.min(backoffMs, 30_000)\n timer = setTimeout(mint, next)\n backoffMs = Math.min(backoffMs * 2, 30_000)\n })\n }\n\n mint()\n return () => {\n cancelled = true\n if (timer) clearTimeout(timer)\n }\n }, [api, identity, sendIdentity, initialIdentity])\n\n // Short-lived JWT for the Convex WebSocket subscription below.\n // Encapsulated in a hook so the fetch + scheduled refresh + retry\n // loop doesn't sit as another raw effect on App.\n const subscriptionToken = useSubscriptionToken(api)\n\n /* — Convex client for real-time subscriptions —\n *\n * Held in `useState` rather than a ref so the subscription effect\n * below re-runs when the client is rebuilt (apiUrl change, HMR).\n * With a ref the subscription effect captured a closed client and\n * stayed bound to it until one of its other deps shifted. */\n const [convexClient, setConvexClient] = useState<ConvexClient | null>(null)\n useEffect(() => {\n // HTTP Actions use *.convex.site; the WebSocket client needs *.convex.cloud.\n const wsUrl = apiUrl.replace(/\\.convex\\.site(\\/.*)?$/, '.convex.cloud')\n const client = new ConvexClient(wsUrl)\n setConvexClient(client)\n return () => {\n client.close()\n setConvexClient((current) => (current === client ? null : current))\n }\n }, [apiUrl])\n\n /* — real-time thread subscription via Convex WebSocket — */\n const deepLinkHandled = useRef(false)\n useEffect(() => {\n if (!convexClient || !subscriptionToken) return\n // Clear any prior write/reaction error on reconnect — the\n // subscription resuming generally means the deployment is reachable\n // again, so a stale \"Failed to post\" message would be misleading.\n resetAction()\n resetReaction()\n return convexClient.onUpdate(\n makeFunctionReference<'query'>('widget/queries:subscribeThreadsForRoute'),\n // `viewerClientId` is hint-only — server uses it to compute the\n // per-reaction `mine` flag and applies no trust to it. Passing the\n // identity's clientId means the same WebSocket subscription\n // re-fires (and `mine` flips) when identity changes.\n { subscriptionToken, route, viewerClientId: currentClientId },\n (result) => {\n if (result !== undefined) {\n setThreads(result)\n setThreadsLoaded(true)\n }\n },\n )\n }, [convexClient, subscriptionToken, route, currentClientId, resetAction, resetReaction])\n\n /* — auto-open thread from URL fragment (#markup-thread=<id>) —\n *\n * Waits for the first subscription snapshot before deciding —\n * `threads` starts as `[]` from `useState`, and acting on that empty\n * initial value would scrub the hash (and mark the deep-link\n * handled) before the real threads ever arrive.\n *\n * Marks itself handled on that first delivery whether or not the\n * target was found, so a hash pointing at a deleted thread doesn't\n * loop forever on every subsequent subscription tick. */\n useEffect(() => {\n if (deepLinkHandled.current) return\n if (!threadsLoaded) return\n const match = window.location.hash.match(/^#markup-thread=(.+)$/)\n if (match) {\n const threadId = decodeURIComponent(match[1] ?? '')\n const thread = threads.find((t) => t._id === threadId)\n if (thread) {\n setMode({ kind: 'thread', threadId })\n }\n // Scrub the hash regardless — a stale `#markup-thread=` for a\n // deleted thread shouldn't linger in the URL bar.\n history.replaceState(null, '', window.location.pathname + window.location.search)\n }\n deepLinkHandled.current = true\n }, [threads, threadsLoaded])\n\n /* — track route changes (SPA navigation + back/forward) —\n *\n * A module-scoped singleton installs the pushState/replaceState wrappers\n * once per page lifetime (history-observer.ts). We subscribe here and\n * unsubscribe on unmount — no wrapper stacking across init/destroy cycles. */\n useEffect(() => subscribeToRouteChanges(() => setRoute(currentRoute())), [])\n\n /* — keyboard shortcut: ⌘/Ctrl + . toggles the entire widget HUD (FAB +\n * pins), Figma-style. Allowed even when an input is focused — the chord\n * wouldn't produce text anyway, and the user often wants to peek at the\n * page cleanly while writing a comment. */\n useEffect(() => {\n function onKeyDown(e: KeyboardEvent) {\n if (e.key !== '.') return\n if (!(e.metaKey || e.ctrlKey)) return\n if (e.altKey || e.shiftKey) return\n e.preventDefault()\n sendHud({ type: 'toggle' })\n }\n window.addEventListener('keydown', onKeyDown)\n return () => window.removeEventListener('keydown', onKeyDown)\n }, [sendHud])\n\n /* — auto-dismiss the \"HUD hidden\" toast after a few seconds. Runs only\n * while the machine is in `hidden-with-toast`; any transition out of\n * that state (toggle back to visible, manual dismiss) reruns the\n * effect and the cleanup clears the timer — no separate reconcile\n * branch needed. */\n useEffect(() => {\n if (hud.kind !== 'hidden-with-toast') return\n const t = window.setTimeout(() => sendHud({ type: 'dismiss-toast' }), 5000)\n return () => window.clearTimeout(t)\n }, [hud.kind, sendHud])\n\n /* — re-render pins on scroll/resize/layout-shift so they track their anchors — */\n useEffect(() => {\n // Coalesce notifications via rAF. ResizeObserver in particular can\n // fire dozens of times per frame on a busy host page (sticky\n // headers, virtual lists, lazy images), and each notification\n // would otherwise trigger a full App re-render. One render per\n // animation frame is plenty to keep pins anchored.\n let rafId: number | null = null\n function tick() {\n if (rafId != null) return\n rafId = requestAnimationFrame(() => {\n rafId = null\n forceTick((n) => n + 1)\n })\n }\n window.addEventListener('scroll', tick, { passive: true })\n window.addEventListener('resize', tick)\n // Catches layout shifts that don't fire resize/scroll: sticky headers\n // appearing, accordions expanding, lazy images loading, etc.\n const ro = new ResizeObserver(tick)\n ro.observe(document.body)\n return () => {\n window.removeEventListener('scroll', tick)\n window.removeEventListener('resize', tick)\n ro.disconnect()\n if (rafId != null) cancelAnimationFrame(rafId)\n }\n }, [])\n\n /* — actions —\n *\n * Mode transitions reset the error machines so a previous failure\n * doesn't carry across into the next user gesture. (Sign-in errors\n * persist on purpose — they belong to the auth surface, not the\n * placing/composing flow.) */\n const startPlacing = useCallback(() => {\n resetAction()\n resetReaction()\n setMode({ kind: 'placing' })\n }, [resetAction, resetReaction])\n\n const cancel = useCallback(() => {\n setMode({ kind: 'idle' })\n resetAction()\n resetReaction()\n }, [resetAction, resetReaction])\n\n // Monotonic counter used to scope each in-flight screenshot capture to\n // the placement gesture that started it. See `Mode.composing-new.captureToken`.\n const captureCounterRef = useRef(0)\n const handlePlace = useCallback(\n (coords: PageCoords, screenX: number, screenY: number) => {\n const pageX = screenX + window.scrollX\n const pageY = screenY + window.scrollY\n const captureToken = ++captureCounterRef.current\n\n if (screenshots?.enabled === false) {\n setMode({\n kind: 'composing-new',\n coords,\n pageX,\n pageY,\n screenshot: null,\n isScreenshotCapturing: false,\n screenshotRedactedCount: 0,\n screenshotRedactedSelectors: [],\n captureToken,\n })\n return\n }\n\n setMode({\n kind: 'composing-new',\n coords,\n pageX,\n pageY,\n screenshot: null,\n isScreenshotCapturing: true,\n screenshotRedactedCount: 0,\n screenshotRedactedSelectors: [],\n captureToken,\n })\n\n // Resolve the shadow host so it's excluded from the capture\n const shadowHost =\n rootRef.current != null && rootRef.current.getRootNode() instanceof ShadowRoot\n ? (rootRef.current.getRootNode() as ShadowRoot).host\n : null\n\n const scrubConfig: ScrubConfig = {\n strictScrub: screenshots?.strictScrub,\n redactSelector: screenshots?.redactSelector,\n }\n\n captureScreenshot(shadowHost, { x: screenX, y: screenY }, scrubConfig).then((result) => {\n setMode((current) => {\n // Drop the result if the user cancelled, opened a thread, or\n // started a fresh placement before this capture finished —\n // otherwise blob A would attach to composer B.\n if (current.kind !== 'composing-new') return current\n if (current.captureToken !== captureToken) return current\n return {\n ...current,\n screenshot: result?.blob ?? null,\n isScreenshotCapturing: false,\n screenshotRedactedCount: result?.redactedCount ?? 0,\n screenshotRedactedSelectors: result?.redactedSelectors ?? [],\n }\n })\n })\n },\n [screenshots],\n )\n\n const handleAuthor = useCallback(\n (name: string, email?: string) => {\n // The author prompt is only shown when authorName is null, which\n // happens for an anon identity that hasn't filled in display\n // fields yet. Verified identities always have a name — they\n // shouldn't reach this path, and the machine ignores\n // `verified.author-set` anyway.\n sendIdentity({ type: 'author-set', name, email })\n },\n [sendIdentity],\n )\n\n // `signInAction.isPending` mirrors the old `signingIn` flag: true\n // from the moment the user clicks Sign In until the popup resolves\n // or rejects. `useAsyncAction` drops re-entrant `run` calls while\n // pending, so spam-clicking the button no longer stacks popups —\n // the explicit `if (isSigningIn) return` guard is unnecessary.\n const isSigningIn = signInAction.isPending\n const signIn = useCallback(async () => {\n await runSignIn(async () => {\n const result = await signInWithPopup(apiUrl, apiKey)\n const verified = verifiedFromPopup(result)\n if (!verified) {\n // Server didn't include a usable JWT in the popup response.\n // Without one we can't construct a `verified` state, so refuse\n // rather than wedging the user with isVerified=true and no\n // token (the silent-401 trap PR 1 set out to fix).\n throw new Error('Sign-in did not return a verified token')\n }\n sendIdentity({ type: 'signed-in', identity: verified })\n })\n }, [apiUrl, apiKey, runSignIn, sendIdentity])\n\n const handleSubmitNew = useCallback(\n async (body: string, includeScreenshot: boolean) => {\n if (mode.kind !== 'composing-new') return\n const author = authorFieldsOf(identity)\n if (!author) return\n await runAction(async () => {\n let screenshotStorageId: string | undefined\n\n if (includeScreenshot && mode.screenshot) {\n const { uploadUrl } = await api.getScreenshotUploadUrl()\n const uploadRes = await fetch(uploadUrl, {\n method: 'POST',\n headers: { 'Content-Type': mode.screenshot.type || 'image/png' },\n body: mode.screenshot,\n })\n // Surface upload failure instead of dropping the screenshot\n // silently. The composer stays open on throw, the user sees\n // a clear error and can retry or untoggle the attachment;\n // posting without a screenshot they explicitly asked to\n // attach is a worse outcome than failing loudly.\n if (!uploadRes.ok) {\n throw new Error(`Screenshot upload failed (${uploadRes.status})`)\n }\n const { storageId } = (await uploadRes.json()) as { storageId: string }\n screenshotStorageId = storageId\n }\n\n const res = await api.createThread({\n url: window.location.href,\n route,\n anchorSelector: mode.coords.anchorSelector,\n anchorX: mode.coords.anchorX,\n anchorY: mode.coords.anchorY,\n anchorOffsetX: mode.coords.anchorOffsetX,\n anchorOffsetY: mode.coords.anchorOffsetY,\n viewportW: mode.coords.viewportW,\n viewportY: mode.coords.viewportY,\n userAgent: navigator.userAgent,\n authorName: author.name,\n authorEmail: author.email,\n body,\n screenshotStorageId,\n })\n setThreads((current) => [...current, res.thread])\n setMode({ kind: 'thread', threadId: res.thread._id })\n })\n },\n [api, identity, mode, route, runAction],\n )\n\n const handleDelete = useCallback(async () => {\n if (mode.kind !== 'thread') return\n const threadId = mode.threadId\n await runAction(async () => {\n await api.deleteThread(threadId)\n setThreads((current) => current.filter((t) => t._id !== threadId))\n setMode({ kind: 'idle' })\n })\n }, [api, mode, runAction])\n\n const handleResolve = useCallback(async () => {\n if (mode.kind !== 'thread') return\n const threadId = mode.threadId\n await runAction(async () => {\n await api.resolveThread(threadId, currentClientId)\n setThreads((current) => current.filter((t) => t._id !== threadId))\n setMode({ kind: 'idle' })\n })\n }, [api, mode, currentClientId, runAction])\n\n const handleReply = useCallback(\n async (body: string) => {\n if (mode.kind !== 'thread') return\n const author = authorFieldsOf(identity)\n if (!author) return\n const threadId = mode.threadId\n await runAction(async () => {\n const res = await api.addComment(threadId, {\n body,\n authorName: author.name,\n authorEmail: author.email,\n })\n setThreads((current) => current.map((t) => (t._id === threadId ? res.thread : t)))\n })\n },\n [api, identity, mode, runAction],\n )\n\n const handleEditComment = useCallback(\n async (commentId: string, body: string) => {\n if (mode.kind !== 'thread') return\n if (identity.kind !== 'anon' && identity.kind !== 'verified') return\n const threadId = mode.threadId\n // `rethrow` so the popover's edit form stays open on save failure\n // and the user can retry without losing their draft.\n await runAction(\n async () => {\n const res = await api.editComment(threadId, commentId, { body })\n setThreads((current) => current.map((t) => (t._id === threadId ? res.thread : t)))\n },\n { rethrow: true },\n )\n },\n [api, identity, mode, runAction],\n )\n\n const handleDeleteComment = useCallback(\n async (commentId: string) => {\n if (mode.kind !== 'thread') return\n if (identity.kind !== 'anon' && identity.kind !== 'verified') return\n const threadId = mode.threadId\n await runAction(async () => {\n const res = await api.deleteComment(threadId, commentId)\n setThreads((current) => current.map((t) => (t._id === threadId ? res.thread : t)))\n })\n },\n [api, identity, mode, runAction],\n )\n\n /**\n * Toggle a reaction. Routed through a separate `reactionAction` so it\n * doesn't flip the popover-wide `isPending` flag — reactions are cheap\n * and frequent, and graying out the whole popover for each click would\n * feel terrible. The thread state is swapped from the server's\n * authoritative response on success; failures surface via the existing\n * error display and rely on the next subscription tick to reconcile UI.\n */\n const handleToggleReaction = useCallback(\n async (commentId: string, emoji: string) => {\n if (mode.kind !== 'thread') return\n const author = authorFieldsOf(identity)\n if (!author) return\n const threadId = mode.threadId\n await runReaction(async () => {\n const res = await api.toggleReaction(commentId, {\n emoji,\n authorName: author.name,\n })\n setThreads((current) => current.map((t) => (t._id === threadId ? res.thread : t)))\n })\n },\n [api, identity, mode, runReaction],\n )\n\n /* — derived — */\n const activeThread =\n mode.kind === 'thread' ? (threads.find((t) => t._id === mode.threadId) ?? null) : null\n const canDelete =\n isVerified || (currentClientId != null && currentClientId === activeThread?.authorClientId)\n\n /* — resolved pin positions —\n *\n * Memoised across `threads` and the scroll/resize/mutation tick so we\n * don't re-run `resolveCoords` twice per render (once for the pin\n * markup, once for the unresolved-count derivation that drives the\n * MutationObserver below). `tick` is referenced as a dep so any\n * `forceTick` bump (scroll, resize, ResizeObserver, MutationObserver)\n * recomputes both positions and the resolved flag together. */\n const pinPositions = useMemo(\n () =>\n threads.map((t) => ({\n thread: t,\n point: resolveCoords({\n anchorX: t.anchorX,\n anchorY: t.anchorY,\n anchorSelector: t.anchorSelector,\n anchorOffsetX: t.anchorOffsetX,\n anchorOffsetY: t.anchorOffsetY,\n }),\n })),\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n [threads, tick],\n )\n const hasUnresolvedPins = pinPositions.some((p) => !p.point.resolved)\n\n /* — retry unresolved pins when the DOM changes —\n *\n * The widget's existing scroll/resize/ResizeObserver loop tracks\n * pins through layout shifts but doesn't help when an anchor element\n * isn't in the DOM at all — common in SPAs that render a loading\n * skeleton on route change and only mount the real UI once async\n * data resolves. While at least one pin is sitting at its fraction-\n * based fallback, watch the document for mutations and force a\n * re-render so `resolveCoords` can re-query selectors as new\n * elements appear. The observer is only attached while needed and\n * detaches as soon as every pin has anchored, so the steady-state\n * cost on a fully-rendered page is zero. */\n useEffect(() => {\n if (!hasUnresolvedPins) return\n let rafId: number | null = null\n function schedule() {\n if (rafId != null) return\n rafId = requestAnimationFrame(() => {\n rafId = null\n forceTick((n) => n + 1)\n })\n }\n const observer = new MutationObserver(schedule)\n observer.observe(document.body, { childList: true, subtree: true })\n return () => {\n observer.disconnect()\n if (rafId != null) cancelAnimationFrame(rafId)\n }\n }, [hasUnresolvedPins])\n\n /* — drop the open-thread mode if the thread disappears. Without this,\n * a teammate-initiated delete/resolve (or a route change that drops\n * the thread from the subscription) would leave `mode` pinned to a\n * missing id. The popover gate `mode.kind === 'thread' &&\n * activeThread` falls through quietly and the user sees no popover\n * but `mode` stays wedged until they take another action. Returning\n * to idle here keeps the state machine honest. */\n useEffect(() => {\n if (mode.kind === 'thread' && activeThread == null) {\n cancel()\n }\n }, [mode, activeThread, cancel])\n\n return (\n <div class=\"markup-root\" ref={rootRef}>\n {/* Pins layer — hidden during placement. Thread pins also hide when\n * the HUD is toggled off (the active thread popover hides at the\n * same time, so we don't need to preserve its anchor). The ghost\n * pin during composing-new stays visible regardless, since the\n * composer popover anchors to it. */}\n {mode.kind !== 'placing' ? (\n <div class=\"markup-pins-layer\">\n {!isHudHidden\n ? pinPositions.map(({ thread: t, point }) => {\n const isActive = mode.kind === 'thread' && mode.threadId === t._id\n // Skip tombstoned comments — they're hidden from the\n // popover too, so the badge would otherwise overcount.\n const visibleCount = t.comments.reduce((n, c) => n + (c.deleted ? 0 : 1), 0)\n return (\n <Pin\n key={t._id}\n pageX={point.pageX}\n pageY={point.pageY}\n count={visibleCount}\n isActive={isActive}\n isUnresolved={!point.resolved}\n onClick={() => setMode({ kind: 'thread', threadId: t._id })}\n />\n )\n })\n : null}\n {mode.kind === 'composing-new' ? (\n <GhostPin pageX={mode.pageX} pageY={mode.pageY} />\n ) : null}\n </div>\n ) : null}\n\n {/* Placement overlay — captures the click */}\n {mode.kind === 'placing' ? (\n <PlacementOverlay onPlace={handlePlace} onCancel={cancel} />\n ) : null}\n\n {/* Active thread popover. We keep it mounted while the HUD is\n * hidden (visually suppressed via CSS) so that an in-progress\n * reply draft, edit, or drag position survives a Cmd+. peek.\n * The new-thread popover already follows the same pattern, so\n * this aligns the two.\n *\n * Keyed on the thread id so switching from one open thread to\n * another remounts the popover. Without the key, Preact would\n * reuse the same instance and `dragPos`, `editingId`, the\n * per-comment menus and the reaction picker would all leak\n * across threads. */}\n {mode.kind === 'thread' && activeThread ? (\n <ThreadPopover\n key={activeThread._id}\n thread={activeThread}\n authorName={authorName}\n currentClientId={currentClientId ?? null}\n isVerified={isVerified}\n isIdentityResolving={isIdentityResolving}\n isSigningIn={isSigningIn}\n canDelete={canDelete}\n isPending={isPending}\n error={error}\n isHidden={isHudHidden}\n onAuthor={handleAuthor}\n onSignIn={signIn}\n onClose={cancel}\n onReply={handleReply}\n onEditComment={handleEditComment}\n onDeleteComment={handleDeleteComment}\n onToggleReaction={handleToggleReaction}\n onDelete={handleDelete}\n onResolve={handleResolve}\n />\n ) : null}\n\n {/* New-thread composer */}\n {mode.kind === 'composing-new' ? (\n <NewThreadPopover\n pageX={mode.pageX}\n pageY={mode.pageY}\n authorName={authorName}\n isVerified={isVerified}\n isIdentityResolving={isIdentityResolving}\n isSigningIn={isSigningIn}\n isPending={isPending}\n error={error}\n screenshot={mode.screenshot}\n isScreenshotCapturing={mode.isScreenshotCapturing}\n screenshotRedactedCount={mode.screenshotRedactedCount}\n screenshotRedactedSelectors={mode.screenshotRedactedSelectors}\n onAuthor={handleAuthor}\n onSignIn={signIn}\n onSubmit={handleSubmitNew}\n onClose={cancel}\n />\n ) : null}\n\n {/* FAB — hidden along with the pins when the HUD is toggled off.\n * While placing/composing the FAB stays visible regardless, so the\n * user always has a way to cancel. */}\n {!isHudHidden || mode.kind === 'placing' || mode.kind === 'composing-new' ? (\n <Fab\n isActive={mode.kind === 'placing'}\n onToggle={() => (mode.kind === 'placing' ? cancel() : startPlacing())}\n onHide={() => sendHud({ type: 'hide-with-toast' })}\n position={fabPosition}\n onPositionChange={setFabPosition}\n variant={fab}\n />\n ) : null}\n\n {/* Toast — only shown while the HUD is hidden. Lives outside the\n * HUD-hidden gate so it stays visible after the FAB disappears.\n * Auto-dismisses via the effect above. */}\n {hud.kind === 'hidden-with-toast' ? <HudHiddenToast position={fabPosition} /> : null}\n </div>\n )\n}\n\n/**\n * Brief instructional toast that appears once when the HUD is hidden.\n * Mirrors the FAB's corner so it doesn't drift across the page; the\n * shortcut hint uses the platform-typical modifier so a Mac user sees\n * \"⌘\" and everyone else sees \"Ctrl\".\n */\nfunction HudHiddenToast({ position }: { position: FabPosition }) {\n const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent)\n const modKey = isMac ? '⌘' : 'Ctrl'\n return (\n <div\n class={cx(\n 'markup-hud-hidden-toast',\n position === 'bottom-left'\n ? 'markup-hud-hidden-toast-left'\n : position === 'bottom-center'\n ? 'markup-hud-hidden-toast-center'\n : 'markup-hud-hidden-toast-right',\n )}\n role=\"status\"\n aria-live=\"polite\"\n >\n Markup hidden — press <kbd class=\"markup-kbd\">{modKey}</kbd>\n <kbd class=\"markup-kbd\">.</kbd> or refresh to bring it back.\n </div>\n )\n}\n","import { render } from 'preact'\n\nimport styles from '../styles.css?inline'\nimport { App, type AppProps } from './ui/app'\n\nexport type MountConfig = AppProps & {\n /** 'light' | 'dark' | 'auto' (default 'auto' — follow prefers-color-scheme) */\n theme?: 'light' | 'dark' | 'auto'\n}\n\n/**\n * Attach the shadow root to the host element and render the Preact App into\n * a child container. The host element is positioned `fixed; inset: 0; pointer-\n * events: none;` so it overlays the entire viewport without blocking the\n * underlying page; individual UI bits re-enable pointer-events as needed.\n *\n * The `theme` config maps to a `data-theme` attribute on the host element.\n * Stylesheet rules read it via `:host([data-theme='dark'])` etc. so explicit\n * choices override `prefers-color-scheme`.\n */\nexport function mountWidget(host: HTMLElement, config: MountConfig): () => void {\n host.style.position = 'fixed'\n host.style.inset = '0'\n host.style.zIndex = '2147483647'\n host.style.pointerEvents = 'none'\n\n const theme = config.theme ?? 'auto'\n if (theme !== 'auto') host.dataset.theme = theme\n\n const shadow = host.attachShadow({ mode: 'open' })\n\n const style = document.createElement('style')\n style.textContent = styles\n shadow.appendChild(style)\n\n const root = document.createElement('div')\n root.className = 'markup-shadow-root'\n shadow.appendChild(root)\n\n const { theme: _theme, ...appProps } = config\n render(<App {...appProps} />, root)\n\n return () => render(null, root)\n}\n","import { mountWidget } from './runtime/mount'\n\nexport type WidgetTheme = 'light' | 'dark' | 'auto'\nexport type WidgetFab = 'default' | 'icon-only'\n\nexport interface ScreenshotsConfig {\n /** Disable screenshot capture entirely. Default: enabled. */\n enabled?: boolean\n /** Also masks all inputs/selects/textareas in addition to the default sensitive set. Default: false. */\n strictScrub?: boolean\n /** Custom CSS selector — matched elements are always masked. */\n redactSelector?: string\n}\n\nexport interface WidgetConfig {\n /** Convex deployment site URL, e.g. `https://your-deployment.convex.site` */\n apiUrl: string\n /** Raw API key minted from a project's settings page */\n apiKey: string\n /** Where the floating button sits. Defaults to bottom-right. */\n position?: 'bottom-right' | 'bottom-left' | 'bottom-center'\n /**\n * Visual theme.\n * - `'light'` — force light palette\n * - `'dark'` — force dark palette\n * - `'auto'` (default) — follow the host's `prefers-color-scheme`\n */\n theme?: WidgetTheme\n /**\n * Floating action button variant.\n * - `'default'` — pill button with icon + \"Markup\" label\n * - `'icon-only'` — circular icon-only button (no label)\n *\n * Defaults to `'default'`.\n */\n fab?: WidgetFab\n /** Screenshot capture and PII-scrub options. */\n screenshots?: ScreenshotsConfig\n}\n\nlet _unmount: (() => void) | null = null\nlet _host: HTMLElement | null = null\nlet _pendingMount: (() => void) | null = null\n\n/**\n * Mounts the feedback widget on the page. Idempotent — calling init again\n * with the same config is a no-op; calling with different config tears down\n * the previous instance first.\n *\n * Returns a `destroy()` function that unmounts the widget and removes the\n * host element. Useful for SPAs that want to dispose on logout.\n */\nexport function init(config: WidgetConfig): () => void {\n if (!config.apiUrl || !config.apiKey) {\n console.warn('[markup] init() requires both apiUrl and apiKey — widget not mounted')\n return () => {}\n }\n destroy()\n\n const mount = () => {\n _pendingMount = null\n if (!document.body) return\n const host = document.createElement('div')\n host.id = 'markup-widget'\n document.body.appendChild(host)\n _host = host\n _unmount = mountWidget(host, config)\n }\n\n // Called from <head> before <body> parses, or from a deferred SPA boot:\n // wait for DOMContentLoaded instead of crashing on document.body === null.\n if (document.readyState === 'loading' || !document.body) {\n const deferred = () => mount()\n _pendingMount = () => document.removeEventListener('DOMContentLoaded', deferred)\n document.addEventListener('DOMContentLoaded', deferred, { once: true })\n } else {\n mount()\n }\n\n return destroy\n}\n\nexport function destroy(): void {\n if (_pendingMount) {\n _pendingMount()\n _pendingMount = null\n }\n if (_unmount) {\n _unmount()\n _unmount = null\n }\n if (_host?.parentNode) _host.parentNode.removeChild(_host)\n _host = null\n}\n\n/* ──────────────────────────────────────────────────────────────────────────\n * Auto-init for <script> tag usage:\n *\n * <script\n * src=\"cdn.example.com/widget.js\"\n * type=\"module\"\n * data-markup-widget=\"true\"\n * data-api-url=\"https://your-deployment.convex.site\"\n * data-api-key=\"markup_...\"\n * data-position=\"bottom-right\"\n * ></script>\n *\n * Skip when there's no document (SSR) or when the script tag carries no\n * data attributes (assumed manual init via `init()`).\n * ────────────────────────────────────────────────────────────────────────── */\n\nif (typeof document !== 'undefined') {\n // document.currentScript is null for type=\"module\" scripts — fall back to\n // querying by data-markup-widget=\"true\", which is required on the script tag\n // for auto-init to work.\n const current =\n (document.currentScript as HTMLScriptElement | null) ??\n (document.querySelector('script[data-markup-widget=\"true\"]') as HTMLScriptElement | null)\n const apiUrl = current?.dataset.apiUrl\n const apiKey = current?.dataset.apiKey\n if (apiUrl && apiKey) {\n const position = current?.dataset.position as WidgetConfig['position'] | undefined\n const theme = current?.dataset.theme as WidgetTheme | undefined\n const fab = current?.dataset.fab as WidgetFab | undefined\n const start = () => init({ apiUrl, apiKey, position, theme, fab })\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', start, { once: true })\n } else {\n start()\n }\n }\n}\n"],"x_google_ignoreList":[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,30,36,37,38,39,40,41,42,43,44,45,50],"mappings":";AAAA,IAAI,GAAEA,GAAEC,GAAIE,GAAEC,G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