UNPKG

@subscribe.dev/react

Version:

React hooks and components for SubscribeDev - provides context and hooks for managing AI predictions with billing and rate limiting

24 lines (23 loc) 42.1 kB
(function(p,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("react"),require("@clerk/clerk-react"),require("@subscribe.dev/client")):typeof define=="function"&&define.amd?define(["exports","react","@clerk/clerk-react","@subscribe.dev/client"],l):(p=typeof globalThis<"u"?globalThis:p||self,l(p.SubscribeDevReact={},p.React,p.ClerkReact,p.SubscribeDevClient))})(this,function(p,l,P,ae){"use strict";var Tt=p=>{throw TypeError(p)};var Ge=(p,l,P)=>l.has(p)||Tt("Cannot "+P);var i=(p,l,P)=>(Ge(p,l,"read from private field"),P?P.call(p):l.get(p)),b=(p,l,P)=>l.has(p)?Tt("Cannot add the same private member more than once"):l instanceof WeakSet?l.add(p):l.set(p,P),f=(p,l,P,ae)=>(Ge(p,l,"write to private field"),ae?ae.call(p,P):l.set(p,P),P),A=(p,l,P)=>(Ge(p,l,"access private method"),P);var Re=(p,l,P,ae)=>({set _(je){f(p,l,je,P)},get _(){return i(p,l,ae)}});var ee,Y,ue,ft,ce,B,le,dt,te,pt,he,re,k,se,D,Oe,ne,M,z,yt,U,gt,Q,R,ie,$,Z,mt,K,q,Ce,bt,C,J,V,fe,de,W,pe,ye,vt;function je(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const ze=je(l);var ke={exports:{}},ve={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var He;function Ft(){if(He)return ve;He=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(s,n,o){var c=null;if(o!==void 0&&(c=""+o),n.key!==void 0&&(c=""+n.key),"key"in n){o={};for(var u in n)u!=="key"&&(o[u]=n[u])}else o=n;return n=o.ref,{$$typeof:t,type:s,key:c,ref:n!==void 0?n:null,props:o}}return ve.Fragment=e,ve.jsx=r,ve.jsxs=r,ve}var Se={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Ye;function At(){return Ye||(Ye=1,process.env.NODE_ENV!=="production"&&function(){function t(a){if(a==null)return null;if(typeof a=="function")return a.$$typeof===fr?null:a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case E:return"Fragment";case x:return"Profiler";case N:return"StrictMode";case me:return"Suspense";case _e:return"SuspenseList";case hr:return"Activity"}if(typeof a=="object")switch(typeof a.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),a.$$typeof){case S:return"Portal";case oe:return(a.displayName||"Context")+".Provider";case G:return(a._context.displayName||"Context")+".Consumer";case ge:var g=a.render;return a=a.displayName,a||(a=g.displayName||g.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case lr:return g=a.displayName||null,g!==null?g:t(a.type)||"Memo";case St:g=a._payload,a=a._init;try{return t(a(g))}catch{}}return null}function e(a){return""+a}function r(a){try{e(a);var g=!1}catch{g=!0}if(g){g=console;var O=g.error,T=typeof Symbol=="function"&&Symbol.toStringTag&&a[Symbol.toStringTag]||a.constructor.name||"Object";return O.call(g,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",T),e(a)}}function s(a){if(a===E)return"<>";if(typeof a=="object"&&a!==null&&a.$$typeof===St)return"<...>";try{var g=t(a);return g?"<"+g+">":"<...>"}catch{return"<...>"}}function n(){var a=Ue.A;return a===null?null:a.getOwner()}function o(){return Error("react-stack-top-frame")}function c(a){if(wt.call(a,"key")){var g=Object.getOwnPropertyDescriptor(a,"key").get;if(g&&g.isReactWarning)return!1}return a.key!==void 0}function u(a,g){function O(){Et||(Et=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",g))}O.isReactWarning=!0,Object.defineProperty(a,"key",{get:O,configurable:!0})}function y(){var a=t(this.type);return Ot[a]||(Ot[a]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),a=this.props.ref,a!==void 0?a:null}function h(a,g,O,T,X,L,$e,Le){return O=L.ref,a={$$typeof:w,type:a,key:g,props:L,_owner:X},(O!==void 0?O:null)!==null?Object.defineProperty(a,"ref",{enumerable:!1,get:y}):Object.defineProperty(a,"ref",{enumerable:!1,value:null}),a._store={},Object.defineProperty(a._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(a,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(a,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:$e}),Object.defineProperty(a,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Le}),Object.freeze&&(Object.freeze(a.props),Object.freeze(a)),a}function v(a,g,O,T,X,L,$e,Le){var F=g.children;if(F!==void 0)if(T)if(dr(F)){for(T=0;T<F.length;T++)m(F[T]);Object.freeze&&Object.freeze(F)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else m(F);if(wt.call(g,"key")){F=t(a);var be=Object.keys(g).filter(function(pr){return pr!=="key"});T=0<be.length?"{key: someKey, "+be.join(": ..., ")+": ...}":"{key: someKey}",Dt[F+T]||(be=0<be.length?"{"+be.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,T,F,be,F),Dt[F+T]=!0)}if(F=null,O!==void 0&&(r(O),F=""+O),c(g)&&(r(g.key),F=""+g.key),"key"in g){O={};for(var Ke in g)Ke!=="key"&&(O[Ke]=g[Ke])}else O=g;return F&&u(O,typeof a=="function"?a.displayName||a.name||"Unknown":a),h(a,F,L,X,n(),O,$e,Le)}function m(a){typeof a=="object"&&a!==null&&a.$$typeof===w&&a._store&&(a._store.validated=1)}var d=l,w=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),G=Symbol.for("react.consumer"),oe=Symbol.for("react.context"),ge=Symbol.for("react.forward_ref"),me=Symbol.for("react.suspense"),_e=Symbol.for("react.suspense_list"),lr=Symbol.for("react.memo"),St=Symbol.for("react.lazy"),hr=Symbol.for("react.activity"),fr=Symbol.for("react.client.reference"),Ue=d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,wt=Object.prototype.hasOwnProperty,dr=Array.isArray,Qe=console.createTask?console.createTask:function(){return null};d={react_stack_bottom_frame:function(a){return a()}};var Et,Ot={},Ct=d.react_stack_bottom_frame.bind(d,o)(),Pt=Qe(s(o)),Dt={};Se.Fragment=E,Se.jsx=function(a,g,O,T,X){var L=1e4>Ue.recentlyCreatedOwnerStacks++;return v(a,g,O,!1,T,X,L?Error("react-stack-top-frame"):Ct,L?Qe(s(a)):Pt)},Se.jsxs=function(a,g,O,T,X){var L=1e4>Ue.recentlyCreatedOwnerStacks++;return v(a,g,O,!0,T,X,L?Error("react-stack-top-frame"):Ct,L?Qe(s(a)):Pt)}}()),Se}process.env.NODE_ENV==="production"?ke.exports=Ft():ke.exports=At();var j=ke.exports,Pe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},De=typeof window>"u"||"Deno"in globalThis;function I(){}function _t(t,e){return typeof t=="function"?t(e):t}function Rt(t){return typeof t=="number"&&t>=0&&t!==1/0}function jt(t,e){return Math.max(t+(e||0)-Date.now(),0)}function xe(t,e){return typeof t=="function"?t(e):t}function kt(t,e){return typeof t=="function"?t(e):t}function Be(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:o,queryKey:c,stale:u}=t;if(c){if(s){if(e.queryHash!==Ie(c,e.options))return!1}else if(!Ee(e.queryKey,c))return!1}if(r!=="all"){const y=e.isActive();if(r==="active"&&!y||r==="inactive"&&y)return!1}return!(typeof u=="boolean"&&e.isStale()!==u||n&&n!==e.state.fetchStatus||o&&!o(e))}function Je(t,e){const{exact:r,status:s,predicate:n,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(r){if(we(e.options.mutationKey)!==we(o))return!1}else if(!Ee(e.options.mutationKey,o))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Ie(t,e){return(e?.queryKeyHashFn||we)(t)}function we(t){return JSON.stringify(t,(e,r)=>qe(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function Ee(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>Ee(t[r],e[r])):!1}function Me(t,e){if(t===e)return t;const r=Ve(t)&&Ve(e);if(r||qe(t)&&qe(e)){const s=r?t:Object.keys(t),n=s.length,o=r?e:Object.keys(e),c=o.length,u=r?[]:{},y=new Set(s);let h=0;for(let v=0;v<c;v++){const m=r?v:o[v];(!r&&y.has(m)||r)&&t[m]===void 0&&e[m]===void 0?(u[m]=void 0,h++):(u[m]=Me(t[m],e[m]),u[m]===t[m]&&t[m]!==void 0&&h++)}return n===c&&h===n?t:u}return e}function Ve(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function qe(t){if(!We(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!We(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function We(t){return Object.prototype.toString.call(t)==="[object Object]"}function xt(t){return new Promise(e=>{setTimeout(e,t)})}function It(t,e,r){if(typeof r.structuralSharing=="function")return r.structuralSharing(t,e);if(r.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Me(t,e)}catch(s){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${r.queryHash}]: ${s}`),s}return Me(t,e)}return e}function Mt(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function qt(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Te=Symbol();function Xe(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Te&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===Te?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}var Nt=(ft=class extends Pe{constructor(){super();b(this,ee);b(this,Y);b(this,ue);f(this,ue,e=>{if(!De&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){i(this,Y)||this.setEventListener(i(this,ue))}onUnsubscribe(){var e;this.hasListeners()||((e=i(this,Y))==null||e.call(this),f(this,Y,void 0))}setEventListener(e){var r;f(this,ue,e),(r=i(this,Y))==null||r.call(this),f(this,Y,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){i(this,ee)!==e&&(f(this,ee,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){return typeof i(this,ee)=="boolean"?i(this,ee):globalThis.document?.visibilityState!=="hidden"}},ee=new WeakMap,Y=new WeakMap,ue=new WeakMap,ft),Ze=new Nt,Ut=(dt=class extends Pe{constructor(){super();b(this,ce,!0);b(this,B);b(this,le);f(this,le,e=>{if(!De&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){i(this,B)||this.setEventListener(i(this,le))}onUnsubscribe(){var e;this.hasListeners()||((e=i(this,B))==null||e.call(this),f(this,B,void 0))}setEventListener(e){var r;f(this,le,e),(r=i(this,B))==null||r.call(this),f(this,B,e(this.setOnline.bind(this)))}setOnline(e){i(this,ce)!==e&&(f(this,ce,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return i(this,ce)}},ce=new WeakMap,B=new WeakMap,le=new WeakMap,dt),Fe=new Ut;function Qt(){let t,e;const r=new Promise((n,o)=>{t=n,e=o});r.status="pending",r.catch(()=>{});function s(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{s({status:"fulfilled",value:n}),t(n)},r.reject=n=>{s({status:"rejected",reason:n}),e(n)},r}function $t(t){return Math.min(1e3*2**t,3e4)}function et(t){return(t??"online")==="online"?Fe.isOnline():!0}var tt=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ne(t){return t instanceof tt}function rt(t){let e=!1,r=0,s=!1,n;const o=Qt(),c=E=>{s||(d(new tt(E)),t.abort?.())},u=()=>{e=!0},y=()=>{e=!1},h=()=>Ze.isFocused()&&(t.networkMode==="always"||Fe.isOnline())&&t.canRun(),v=()=>et(t.networkMode)&&t.canRun(),m=E=>{s||(s=!0,t.onSuccess?.(E),n?.(),o.resolve(E))},d=E=>{s||(s=!0,t.onError?.(E),n?.(),o.reject(E))},w=()=>new Promise(E=>{n=N=>{(s||h())&&E(N)},t.onPause?.()}).then(()=>{n=void 0,s||t.onContinue?.()}),S=()=>{if(s)return;let E;const N=r===0?t.initialPromise:void 0;try{E=N??t.fn()}catch(x){E=Promise.reject(x)}Promise.resolve(E).then(m).catch(x=>{if(s)return;const G=t.retry??(De?0:3),oe=t.retryDelay??$t,ge=typeof oe=="function"?oe(r,x):oe,me=G===!0||typeof G=="number"&&r<G||typeof G=="function"&&G(r,x);if(e||!me){d(x);return}r++,t.onFail?.(r,x),xt(ge).then(()=>h()?void 0:w()).then(()=>{e?d(x):S()})})};return{promise:o,cancel:c,continue:()=>(n?.(),o),cancelRetry:u,continueRetry:y,canStart:v,start:()=>(v()?S():w().then(S),o)}}var Lt=t=>setTimeout(t,0);function Kt(){let t=[],e=0,r=u=>{u()},s=u=>{u()},n=Lt;const o=u=>{e?t.push(u):n(()=>{r(u)})},c=()=>{const u=t;t=[],u.length&&n(()=>{s(()=>{u.forEach(y=>{r(y)})})})};return{batch:u=>{let y;e++;try{y=u()}finally{e--,e||c()}return y},batchCalls:u=>(...y)=>{o(()=>{u(...y)})},schedule:o,setNotifyFunction:u=>{r=u},setBatchNotifyFunction:u=>{s=u},setScheduler:u=>{n=u}}}var _=Kt(),st=(pt=class{constructor(){b(this,te)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rt(this.gcTime)&&f(this,te,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(De?1/0:5*60*1e3))}clearGcTimeout(){i(this,te)&&(clearTimeout(i(this,te)),f(this,te,void 0))}},te=new WeakMap,pt),Gt=(yt=class extends st{constructor(e){super();b(this,M);b(this,he);b(this,re);b(this,k);b(this,se);b(this,D);b(this,Oe);b(this,ne);f(this,ne,!1),f(this,Oe,e.defaultOptions),this.setOptions(e.options),this.observers=[],f(this,se,e.client),f(this,k,i(this,se).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,f(this,he,Ht(this.options)),this.state=e.state??i(this,he),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return i(this,D)?.promise}setOptions(e){this.options={...i(this,Oe),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&i(this,k).remove(this)}setData(e,r){const s=It(this.state.data,e,this.options);return A(this,M,z).call(this,{data:s,type:"success",dataUpdatedAt:r?.updatedAt,manual:r?.manual}),s}setState(e,r){A(this,M,z).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){const r=i(this,D)?.promise;return i(this,D)?.cancel(e),r?r.then(I).catch(I):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(i(this,he))}isActive(){return this.observers.some(e=>kt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Te||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>xe(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!jt(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(r=>r.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),i(this,D)?.continue()}onOnline(){this.observers.find(r=>r.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),i(this,D)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),i(this,k).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(i(this,D)&&(i(this,ne)?i(this,D).cancel({revert:!0}):i(this,D).cancelRetry()),this.scheduleGc()),i(this,k).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||A(this,M,z).call(this,{type:"invalidate"})}fetch(e,r){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&r?.cancelRefetch)this.cancel({silent:!0});else if(i(this,D))return i(this,D).continueRetry(),i(this,D).promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(v=>v.options.queryFn);h&&this.setOptions(h.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,n=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(f(this,ne,!0),s.signal)})},o=()=>{const h=Xe(this.options,r),m=(()=>{const d={client:i(this,se),queryKey:this.queryKey,meta:this.meta};return n(d),d})();return f(this,ne,!1),this.options.persister?this.options.persister(h,m,this):h(m)},u=(()=>{const h={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:i(this,se),state:this.state,fetchFn:o};return n(h),h})();this.options.behavior?.onFetch(u,this),f(this,re,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&A(this,M,z).call(this,{type:"fetch",meta:u.fetchOptions?.meta});const y=h=>{Ne(h)&&h.silent||A(this,M,z).call(this,{type:"error",error:h}),Ne(h)||(i(this,k).config.onError?.(h,this),i(this,k).config.onSettled?.(this.state.data,h,this)),this.scheduleGc()};return f(this,D,rt({initialPromise:r?.initialPromise,fn:u.fetchFn,abort:s.abort.bind(s),onSuccess:h=>{if(h===void 0){process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),y(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(h)}catch(v){y(v);return}i(this,k).config.onSuccess?.(h,this),i(this,k).config.onSettled?.(h,this.state.error,this),this.scheduleGc()},onError:y,onFail:(h,v)=>{A(this,M,z).call(this,{type:"failed",failureCount:h,error:v})},onPause:()=>{A(this,M,z).call(this,{type:"pause"})},onContinue:()=>{A(this,M,z).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0})),i(this,D).start()}},he=new WeakMap,re=new WeakMap,k=new WeakMap,se=new WeakMap,D=new WeakMap,Oe=new WeakMap,ne=new WeakMap,M=new WeakSet,z=function(e){const r=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...zt(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,data:e.data,dataUpdateCount:s.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return f(this,re,e.manual?n:void 0),n;case"error":const o=e.error;return Ne(o)&&o.revert&&i(this,re)?{...i(this,re),fetchStatus:"idle"}:{...s,error:o,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=r(this.state),_.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),i(this,k).notify({query:this,type:"updated",action:e})})},yt);function zt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:et(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Ht(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var Yt=(gt=class extends Pe{constructor(e={}){super();b(this,U);this.config=e,f(this,U,new Map)}build(e,r,s){const n=r.queryKey,o=r.queryHash??Ie(n,r);let c=this.get(o);return c||(c=new Gt({client:e,queryKey:n,queryHash:o,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(c)),c}add(e){i(this,U).has(e.queryHash)||(i(this,U).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=i(this,U).get(e.queryHash);r&&(e.destroy(),r===e&&i(this,U).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){_.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return i(this,U).get(e)}getAll(){return[...i(this,U).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Be(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>Be(e,s)):r}notify(e){_.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){_.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){_.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},U=new WeakMap,gt),Bt=(mt=class extends st{constructor(e){super();b(this,$);b(this,Q);b(this,R);b(this,ie);this.mutationId=e.mutationId,f(this,R,e.mutationCache),f(this,Q,[]),this.state=e.state||Jt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){i(this,Q).includes(e)||(i(this,Q).push(e),this.clearGcTimeout(),i(this,R).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){f(this,Q,i(this,Q).filter(r=>r!==e)),this.scheduleGc(),i(this,R).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){i(this,Q).length||(this.state.status==="pending"?this.scheduleGc():i(this,R).remove(this))}continue(){return i(this,ie)?.continue()??this.execute(this.state.variables)}async execute(e){const r=()=>{A(this,$,Z).call(this,{type:"continue"})};f(this,ie,rt({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{A(this,$,Z).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{A(this,$,Z).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>i(this,R).canRun(this)}));const s=this.state.status==="pending",n=!i(this,ie).canStart();try{if(s)r();else{A(this,$,Z).call(this,{type:"pending",variables:e,isPaused:n}),await i(this,R).config.onMutate?.(e,this);const c=await this.options.onMutate?.(e);c!==this.state.context&&A(this,$,Z).call(this,{type:"pending",context:c,variables:e,isPaused:n})}const o=await i(this,ie).start();return await i(this,R).config.onSuccess?.(o,e,this.state.context,this),await this.options.onSuccess?.(o,e,this.state.context),await i(this,R).config.onSettled?.(o,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(o,null,e,this.state.context),A(this,$,Z).call(this,{type:"success",data:o}),o}catch(o){try{throw await i(this,R).config.onError?.(o,e,this.state.context,this),await this.options.onError?.(o,e,this.state.context),await i(this,R).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,o,e,this.state.context),o}finally{A(this,$,Z).call(this,{type:"error",error:o})}}finally{i(this,R).runNext(this)}}},Q=new WeakMap,R=new WeakMap,ie=new WeakMap,$=new WeakSet,Z=function(e){const r=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),_.batch(()=>{i(this,Q).forEach(s=>{s.onMutationUpdate(e)}),i(this,R).notify({mutation:this,type:"updated",action:e})})},mt);function Jt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Vt=(bt=class extends Pe{constructor(e={}){super();b(this,K);b(this,q);b(this,Ce);this.config=e,f(this,K,new Set),f(this,q,new Map),f(this,Ce,0)}build(e,r,s){const n=new Bt({mutationCache:this,mutationId:++Re(this,Ce)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){i(this,K).add(e);const r=Ae(e);if(typeof r=="string"){const s=i(this,q).get(r);s?s.push(e):i(this,q).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(i(this,K).delete(e)){const r=Ae(e);if(typeof r=="string"){const s=i(this,q).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&i(this,q).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ae(e);if(typeof r=="string"){const n=i(this,q).get(r)?.find(o=>o.state.status==="pending");return!n||n===e}else return!0}runNext(e){const r=Ae(e);return typeof r=="string"?i(this,q).get(r)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){_.batch(()=>{i(this,K).forEach(e=>{this.notify({type:"removed",mutation:e})}),i(this,K).clear(),i(this,q).clear()})}getAll(){return Array.from(i(this,K))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Je(r,s))}findAll(e={}){return this.getAll().filter(r=>Je(e,r))}notify(e){_.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return _.batch(()=>Promise.all(e.map(r=>r.continue().catch(I))))}},K=new WeakMap,q=new WeakMap,Ce=new WeakMap,bt);function Ae(t){return t.options.scope?.id}function nt(t){return{onFetch:(e,r)=>{const s=e.options,n=e.fetchOptions?.meta?.fetchMore?.direction,o=e.state.data?.pages||[],c=e.state.data?.pageParams||[];let u={pages:[],pageParams:[]},y=0;const h=async()=>{let v=!1;const m=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(e.signal.aborted?v=!0:e.signal.addEventListener("abort",()=>{v=!0}),e.signal)})},d=Xe(e.options,e.fetchOptions),w=async(S,E,N)=>{if(v)return Promise.reject();if(E==null&&S.pages.length)return Promise.resolve(S);const G=(()=>{const _e={client:e.client,queryKey:e.queryKey,pageParam:E,direction:N?"backward":"forward",meta:e.options.meta};return m(_e),_e})(),oe=await d(G),{maxPages:ge}=e.options,me=N?qt:Mt;return{pages:me(S.pages,oe,ge),pageParams:me(S.pageParams,E,ge)}};if(n&&o.length){const S=n==="backward",E=S?Wt:it,N={pages:o,pageParams:c},x=E(s,N);u=await w(N,x,S)}else{const S=t??o.length;do{const E=y===0?c[0]??s.initialPageParam:it(s,u);if(y>0&&E==null)break;u=await w(u,E),y++}while(y<S)}return u};e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r):e.fetchFn=h}}}function it(t,{pages:e,pageParams:r}){const s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}function Wt(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}var Xt=(vt=class{constructor(t={}){b(this,C);b(this,J);b(this,V);b(this,fe);b(this,de);b(this,W);b(this,pe);b(this,ye);f(this,C,t.queryCache||new Yt),f(this,J,t.mutationCache||new Vt),f(this,V,t.defaultOptions||{}),f(this,fe,new Map),f(this,de,new Map),f(this,W,0)}mount(){Re(this,W)._++,i(this,W)===1&&(f(this,pe,Ze.subscribe(async t=>{t&&(await this.resumePausedMutations(),i(this,C).onFocus())})),f(this,ye,Fe.subscribe(async t=>{t&&(await this.resumePausedMutations(),i(this,C).onOnline())})))}unmount(){var t,e;Re(this,W)._--,i(this,W)===0&&((t=i(this,pe))==null||t.call(this),f(this,pe,void 0),(e=i(this,ye))==null||e.call(this),f(this,ye,void 0))}isFetching(t){return i(this,C).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return i(this,J).findAll({...t,status:"pending"}).length}getQueryData(t){const e=this.defaultQueryOptions({queryKey:t});return i(this,C).get(e.queryHash)?.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=i(this,C).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(xe(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return i(this,C).findAll(t).map(({queryKey:e,state:r})=>{const s=r.data;return[e,s]})}setQueryData(t,e,r){const s=this.defaultQueryOptions({queryKey:t}),o=i(this,C).get(s.queryHash)?.state.data,c=_t(e,o);if(c!==void 0)return i(this,C).build(this,s).setData(c,{...r,manual:!0})}setQueriesData(t,e,r){return _.batch(()=>i(this,C).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){const e=this.defaultQueryOptions({queryKey:t});return i(this,C).get(e.queryHash)?.state}removeQueries(t){const e=i(this,C);_.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=i(this,C);return _.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=_.batch(()=>i(this,C).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(I).catch(I)}invalidateQueries(t,e={}){return _.batch(()=>(i(this,C).findAll(t).forEach(r=>{r.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},s=_.batch(()=>i(this,C).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let o=n.fetch(void 0,r);return r.throwOnError||(o=o.catch(I)),n.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(s).then(I)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=i(this,C).build(this,e);return r.isStaleByTime(xe(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(I).catch(I)}fetchInfiniteQuery(t){return t.behavior=nt(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(I).catch(I)}ensureInfiniteQueryData(t){return t.behavior=nt(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Fe.isOnline()?i(this,J).resumePausedMutations():Promise.resolve()}getQueryCache(){return i(this,C)}getMutationCache(){return i(this,J)}getDefaultOptions(){return i(this,V)}setDefaultOptions(t){f(this,V,t)}setQueryDefaults(t,e){i(this,fe).set(we(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...i(this,fe).values()],r={};return e.forEach(s=>{Ee(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){i(this,de).set(we(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...i(this,de).values()],r={};return e.forEach(s=>{Ee(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...i(this,V).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Ie(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Te&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...i(this,V).mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){i(this,C).clear(),i(this,J).clear()}},C=new WeakMap,J=new WeakMap,V=new WeakMap,fe=new WeakMap,de=new WeakMap,W=new WeakMap,pe=new WeakMap,ye=new WeakMap,vt),Zt=ze.createContext(void 0),er=({client:t,children:e})=>(ze.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),j.jsx(Zt.Provider,{value:t,children:e}));function tr(t){return j.jsx(P.SignIn,{...t,forceRedirectUrl:window.location.href,oauthFlow:"popup"})}function rr(t){return j.jsx(P.SignInButton,{...t,forceRedirectUrl:window.location.href,oauthFlow:"popup",mode:"modal"})}function sr(t){return j.jsx(P.UserButton,{...t,afterSignOutUrl:window.location.href})}function ot(){const[t,e]=l.useState(null),{isSignedIn:r,getToken:s}=P.useAuth();return l.useEffect(()=>{r?s({skipCache:!0,template:"default"}).then(n=>{e(n||null)}).catch(n=>{console.error("Failed to get fresh token:",n),e(null)}):e(null)},[s,r]),{token:t,isSignedIn:r}}const at=l.createContext(null);function H(){const t=l.useContext(at);if(!t)throw new Error("useSubscribeDevProvider must be used within SubscribeDevProvider");return t}function ut(t,e){const{client:r}=H(),s=ht(),[n,o]=l.useState(e),[c,u]=l.useState("local"),[y,h]=l.useState(!1);l.useEffect(()=>{y||(async()=>{if(console.log(`Initializing storage for key: ${t}, client available: ${!!r}`),!r){console.log(`Client not ready yet for key: ${t}`);return}u("syncing");try{const d=await s.get(t);if(console.log(`Retrieved stored value for ${t}:`,d),d)try{console.log("STORED VALUE: ",d);const w=JSON.parse(d);console.log("PARSED DATA: ",w);let S=w;if(w&&typeof w=="object"&&w[t]!==void 0&&(S=w[t],console.log("EXTRACTED VALUE FOR KEY: ",t,S)),S==null||typeof S=="string"&&S.includes("[object Object]"))throw new Error("Corrupted storage data detected");o(S)}catch(w){console.warn(`Corrupted storage data for key ${t}, overwriting with initial value:`,w),o(e),console.log("SETTING TO: ",e),await s.set(t,JSON.stringify(e)),console.log(`Overwrote corrupted storage for key ${t} with initial value`)}else o(e);u("synced")}catch(d){console.error("Failed to initialize data:",d),o(e),u("error")}h(!0)})()},[t,e,r,y,s]);const v=l.useCallback(async m=>{if(o(m),!r){console.warn(`setValue: No client available for key ${t}`);return}u("syncing");try{await s.set(t,JSON.stringify(m)),u("synced")}catch(d){console.error("Failed to save data:",d),u("error")}},[t,r,s]);return[n,v,c]}function nr(){const{client:t,token:e,isSignedIn:r}=H(),{subscribe:s,isSubscribed:n,subscriptionStatus:o,subscriptionLoading:c,refreshSubscriptionStatus:u}=ct(),y=lt();return{client:t,token:e,isSignedIn:r,subscribe:s,isSubscribed:n,subscriptionStatus:o,subscriptionLoading:c,refreshSubscriptionStatus:u,useStorage:ut,usage:y}}function ir(t,e){return ut(t,e)}function ct(){const{isSignedIn:t,token:e,client:r}=H(),[s,n]=l.useState(null),[o,c]=l.useState(!1),u=l.useCallback(async()=>{if(r&&t){c(!0);try{const d=await r.getSubscriptionStatus();n(d)}catch(d){console.error("Failed to refresh subscription status:",d)}finally{c(!1)}}else n(null)},[r,t]);l.useEffect(()=>{u()},[u]),l.useEffect(()=>{const d=()=>{u()};return window.addEventListener("subscribedev:refresh-subscription",d),()=>window.removeEventListener("subscribedev:refresh-subscription",d)},[u]);const y=s?.hasActiveSubscription||!1,{setSubscriptionModalUrl:h,projectToken:v}=H(),m=l.useCallback(()=>{if(!r?.pricingUrl||!e)return;const d=new URL(r.pricingUrl);e&&d.searchParams.set("user_token",e),v&&d.searchParams.set("project_token",v),h(d.toString())},[r,e,h,v]);return{isSignedIn:t,token:e,isSubscribed:y,subscribe:m,subscriptionStatus:s,subscriptionLoading:o,refreshSubscriptionStatus:u}}function lt(){const{client:t,isSignedIn:e}=H(),[r,s]=l.useState(0),[n,o]=l.useState(0),[c,u]=l.useState(0),[y,h]=l.useState(!1),[v,m]=l.useState(null),d=l.useCallback(async()=>{if(!t||!e){s(0),o(0),u(0),m(null);return}h(!0),m(null);try{const S=(await t.getUsage()).credits.userBalance;s(S?.allocatedCredits||0),o(S?.usedCredits||0),u(S?.remainingCredits||0)}catch(w){console.warn("Failed to fetch balance data:",w),w.name==="ValidationError"&&w.message.includes("User key is required")?m("User authentication required to fetch balance data"):m(w.message||"Failed to fetch balance data"),s(0),o(0),u(0)}finally{h(!1)}},[t,e]);return l.useEffect(()=>{d()},[d]),l.useEffect(()=>{if(!t)return;const w=()=>{console.log("Usage changed, refreshing..."),d()};return t.on("usage-changed",w),()=>{t.off("usage-changed",w)}},[t,d]),{allocatedCredits:r,usedCredits:n,remainingCredits:c,loading:y,error:v,refreshUsage:d}}function or(){const{client:t}=H();return async()=>{if(t)try{const r=localStorage.getItem("__session");if(r){let s={};try{s=(await t.getStorage())?.sessionData||{}}catch(o){console.warn("Could not get current storage during sync:",o)}const n={...s,__session:JSON.parse(r)};await t.setStorage(n)}else{const n=(await t.getStorage())?.sessionData?.__session;n&&localStorage.setItem("__session",JSON.stringify(n))}}catch(r){console.warn("Session sync failed:",r)}}}function ht(){const{client:t}=H();return{get:async n=>{if(!t)return console.warn(`useStorage.get: No client available for key ${n}`),null;try{console.log(`Getting remote storage for key ${n} to check for updates`);const o=await t.getStorage(),c=localStorage.getItem(n);if(o?.sessionData?.[n]!==void 0){console.log(`Successfully retrieved remote storage for key ${n}`);const u=o.sessionData[n];return localStorage.setItem(n,JSON.stringify(u)),JSON.stringify(u)}else return c&&(console.log(`No remote data for key ${n}, purging local storage`),localStorage.removeItem(n)),console.log(`No data found for key ${n}`),null}catch(o){return console.warn(`Failed to get storage for key ${n}:`,o),console.log(`Backend error for key ${n}, purging local storage`),localStorage.removeItem(n),null}},set:async(n,o)=>{if(!t){console.warn(`useStorage.set: No client available for key ${n}`);return}try{let c;try{c=JSON.parse(o)}catch{c=o}let u={};try{u=(await t.getStorage())?.sessionData||{}}catch(h){throw console.warn("Could not get current storage, using empty object:",h),localStorage.removeItem(n),h}const y={...u,[n]:c};await t.setStorage(y),console.log(`Successfully set remote storage for key ${n}`),localStorage.setItem(n,o)}catch(c){throw console.warn(`Failed to set storage for key ${n}:`,c),console.log(`Backend error setting key ${n}, purging local storage`),localStorage.removeItem(n),c}},remove:async n=>{if(t)try{let o={};try{o=(await t.getStorage())?.sessionData||{}}catch(u){console.warn("Could not get current storage for removal:",u),localStorage.removeItem(n);return}const c={...o};delete c[n],await t.setStorage(c),console.log(`Successfully removed remote storage for key ${n}`),localStorage.removeItem(n)}catch(o){console.warn(`Failed to remove storage for key ${n}:`,o),console.log(`Backend error removing key ${n}, removing from local storage anyway`),localStorage.removeItem(n)}}}}function ar({url:t,onClose:e,onSubscriptionChange:r}){return l.useEffect(()=>{if(!t)return;const s=n=>{n.data?.type==="REMETRICATE_SUBSCRIPTION_SUCCESS"&&n.data?.action==="CLOSE_MODAL"&&(console.log("Subscription completed successfully:",n.data),r?.(),e())};return window.addEventListener("message",s),()=>window.removeEventListener("message",s)},[t,e,r]),t?j.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.8)",zIndex:1e4,display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},onClick:e,children:j.jsxs("div",{style:{width:"90vw",height:"90vh",backgroundColor:"white",borderRadius:"8px",position:"relative",overflow:"hidden"},onClick:s=>s.stopPropagation(),children:[j.jsx("button",{onClick:e,style:{position:"absolute",top:"10px",right:"10px",zIndex:10001,backgroundColor:"rgba(0, 0, 0, 0.7)",color:"white",border:"none",borderRadius:"50%",width:"30px",height:"30px",cursor:"pointer",fontSize:"18px",display:"flex",alignItems:"center",justifyContent:"center"},children:"×"}),j.jsx("iframe",{src:t,style:{width:"100%",height:"100%",border:"none",overflow:"hidden"},title:"Subscription"})]})}):null}function ur({children:t,projectToken:e,clerkPublishableKey:r,baseUrl:s}){const n=new Xt({defaultOptions:{queries:{staleTime:3e5,refetchOnWindowFocus:!1}}});return j.jsx(P.ClerkProvider,{publishableKey:r,telemetry:!1,children:j.jsx(er,{client:n,children:j.jsx(cr,{projectToken:e,queryClient:n,baseUrl:s,children:t})})})}function cr({children:t,projectToken:e,queryClient:r,baseUrl:s}){const{token:n,isSignedIn:o}=ot(),[c,u]=l.useState(null),[y,h]=l.useState(null);l.useEffect(()=>{if(o&&n){const d={apiKey:e,userKey:n};s&&(d.baseUrl=s);const w=new ae.SubscribeDevClient(d);u(w)}else u(null)},[o,n,e,s]);const v=()=>{h(null),window.dispatchEvent(new CustomEvent("subscribedev:refresh-subscription"))},m={client:c,token:n,isSignedIn:!!o,queryClient:r,subscriptionModalUrl:y,setSubscriptionModalUrl:h,projectToken:e};return j.jsxs(at.Provider,{value:m,children:[t,j.jsx(ar,{url:y,onClose:v,onSubscriptionChange:()=>window.dispatchEvent(new CustomEvent("subscribedev:refresh-subscription"))})]})}p.SignIn=tr,p.SignInButton=rr,p.SubscribeDevProvider=ur,p.UserButton=sr,p.syncSession=or,p.useClerkAuth=ot,p.useStorage=ht,p.useSubscribeDev=nr,p.useSubscribeDevAuth=ct,p.useSubscribeDevProvider=H,p.useSubscribeDevStorage=ir,p.useUsage=lt,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=index.umd.js.map