@stackone/hub 1.12.0 → 1.12.1
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.
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/webcomponent.js +2 -2
- package/dist/webcomponent.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";"use strict";var e=require("react/jsx-runtime"),t=require("@stackone/malachite"),n=require("react"),i=require("@hookform/resolvers/zod"),r=require("react-hook-form"),s=require("zod");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var a=o(n),u=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},c="undefined"==typeof window||"Deno"in globalThis;function l(){}function d(e){return"number"==typeof e&&e>=0&&e!==1/0}function h(e,t){return Math.max(e+(t||0)-Date.now(),0)}function p(e,t){return"function"==typeof e?e(t):e}function f(e,t){return"function"==typeof e?e(t):e}function g(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:s,queryKey:o,stale:a}=e;if(o)if(i){if(t.queryHash!==v(o,t.options))return!1}else if(!b(t.queryKey,o))return!1;if("all"!==n){const e=t.isActive();if("active"===n&&!e)return!1;if("inactive"===n&&e)return!1}return("boolean"!=typeof a||t.isStale()===a)&&((!r||r===t.state.fetchStatus)&&!(s&&!s(t)))}function y(e,t){const{exact:n,status:i,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(m(t.options.mutationKey)!==m(s))return!1}else if(!b(t.options.mutationKey,s))return!1}return(!i||t.state.status===i)&&!(r&&!r(t))}function v(e,t){return(t?.queryKeyHashFn||m)(e)}function m(e){return JSON.stringify(e,((e,t)=>S(t)?Object.keys(t).sort().reduce(((e,n)=>(e[n]=t[n],e)),{}):t))}function b(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&Object.keys(t).every((n=>b(e[n],t[n]))))}function x(e,t){if(e===t)return e;const n=j(e)&&j(t);if(n||S(e)&&S(t)){const i=n?e:Object.keys(e),r=i.length,s=n?t:Object.keys(t),o=s.length,a=n?[]:{};let u=0;for(let r=0;r<o;r++){const o=n?r:s[r];(!n&&i.includes(o)||n)&&void 0===e[o]&&void 0===t[o]?(a[o]=void 0,u++):(a[o]=x(e[o],t[o]),a[o]===e[o]&&void 0!==e[o]&&u++)}return r===o&&u===r?e:a}return t}function C(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function j(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function S(e){if(!w(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!!w(n)&&(!!n.hasOwnProperty("isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)}function w(e){return"[object Object]"===Object.prototype.toString.call(e)}function O(e,t,n){return"function"==typeof n.structuralSharing?n.structuralSharing(e,t):!1!==n.structuralSharing?x(e,t):t}function k(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function F(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var R=Symbol();function T(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:e.queryFn&&e.queryFn!==R?e.queryFn:()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`))}var q=new class extends u{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!c&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e((e=>{"boolean"==typeof e?this.setFocused(e):this.onFocus()}))}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach((t=>{t(e)}))}isFocused(){return"boolean"==typeof this.#e?this.#e:"hidden"!==globalThis.document?.visibilityState}},D=new class extends u{#i=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!c&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#i!==e&&(this.#i=e,this.listeners.forEach((t=>{t(e)})))}isOnline(){return this.#i}};function E(){let e,t;const n=new Promise(((n,i)=>{e=n,t=i}));function i(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.status="pending",n.catch((()=>{})),n.resolve=t=>{i({status:"fulfilled",value:t}),e(t)},n.reject=e=>{i({status:"rejected",reason:e}),t(e)},n}function P(e){return Math.min(1e3*2**e,3e4)}function I(e){return"online"!==(e??"online")||D.isOnline()}var A=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Q(e){return e instanceof A}function M(e){let t,n=!1,i=0,r=!1;const s=E(),o=()=>q.isFocused()&&("always"===e.networkMode||D.isOnline())&&e.canRun(),a=()=>I(e.networkMode)&&e.canRun(),u=n=>{r||(r=!0,e.onSuccess?.(n),t?.(),s.resolve(n))},l=n=>{r||(r=!0,e.onError?.(n),t?.(),s.reject(n))},d=()=>new Promise((n=>{t=e=>{(r||o())&&n(e)},e.onPause?.()})).then((()=>{t=void 0,r||e.onContinue?.()})),h=()=>{if(r)return;let t;const s=0===i?e.initialPromise:void 0;try{t=s??e.fn()}catch(e){t=Promise.reject(e)}Promise.resolve(t).then(u).catch((t=>{if(r)return;const s=e.retry??(c?0:3),a=e.retryDelay??P,u="function"==typeof a?a(i,t):a,p=!0===s||"number"==typeof s&&i<s||"function"==typeof s&&s(i,t);var f;!n&&p?(i++,e.onFail?.(i,t),(f=u,new Promise((e=>{setTimeout(e,f)}))).then((()=>o()?void 0:d())).then((()=>{n?l(t):h()}))):l(t)}))};return{promise:s,cancel:t=>{r||(l(new A(t)),e.abort?.())},continue:()=>(t?.(),s),cancelRetry:()=>{n=!0},continueRetry:()=>{n=!1},canStart:a,start:()=>(a()?h():d().then(h),s)}}var L=e=>setTimeout(e,0);var z=function(){let e=[],t=0,n=e=>{e()},i=e=>{e()},r=L;const s=i=>{t?e.push(i):r((()=>{n(i)}))};return{batch:s=>{let o;t++;try{o=s()}finally{t--,t||(()=>{const t=e;e=[],t.length&&r((()=>{i((()=>{t.forEach((e=>{n(e)}))}))}))})()}return o},batchCalls:e=>(...t)=>{s((()=>{e(...t)}))},schedule:s,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{i=e},setScheduler:e=>{r=e}}}(),U=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),d(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(c?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}},_=class extends U{#s;#o;#a;#u;#c;#l;#d;constructor(e){super(),this.#d=!1,this.#l=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#u=e.client,this.#a=this.#u.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#s=function(e){const t="function"==typeof e.initialData?e.initialData():e.initialData,n=void 0!==t,i=n?"function"==typeof e.initialDataUpdatedAt?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}(this.options),this.state=e.state??this.#s,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#c?.promise}setOptions(e){this.options={...this.#l,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){this.observers.length||"idle"!==this.state.fetchStatus||this.#a.remove(this)}setData(e,t){const n=O(this.state.data,e,this.options);return this.#h({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#h({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#c?.promise;return this.#c?.cancel(e),t?t.then(l).catch(l):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#s)}isActive(){return this.observers.some((e=>!1!==f(e.options.enabled,this)))}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===R||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return!!this.state.isInvalidated||(this.getObserversCount()>0?this.observers.some((e=>e.getCurrentResult().isStale)):void 0===this.state.data)}isStaleByTime(e=0){return this.state.isInvalidated||void 0===this.state.data||!h(this.state.dataUpdatedAt,e)}onFocus(){const e=this.observers.find((e=>e.shouldFetchOnWindowFocus()));e?.refetch({cancelRefetch:!1}),this.#c?.continue()}onOnline(){const e=this.observers.find((e=>e.shouldFetchOnReconnect()));e?.refetch({cancelRefetch:!1}),this.#c?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter((t=>t!==e)),this.observers.length||(this.#c&&(this.#d?this.#c.cancel({revert:!0}):this.#c.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#h({type:"invalidate"})}fetch(e,t){if("idle"!==this.state.fetchStatus)if(void 0!==this.state.data&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#c)return this.#c.continueRetry(),this.#c.promise;if(e&&this.setOptions(e),!this.options.queryFn){const e=this.observers.find((e=>e.options.queryFn));e&&this.setOptions(e.options)}const n=new AbortController,i=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#d=!0,n.signal)})},r={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#u,state:this.state,fetchFn:()=>{const e=T(this.options,t),n={client:this.#u,queryKey:this.queryKey,meta:this.meta};return i(n),this.#d=!1,this.options.persister?this.options.persister(e,n,this):e(n)}};i(r),this.options.behavior?.onFetch(r,this),this.#o=this.state,"idle"!==this.state.fetchStatus&&this.state.fetchMeta===r.fetchOptions?.meta||this.#h({type:"fetch",meta:r.fetchOptions?.meta});const s=e=>{Q(e)&&e.silent||this.#h({type:"error",error:e}),Q(e)||(this.#a.config.onError?.(e,this),this.#a.config.onSettled?.(this.state.data,e,this)),this.scheduleGc()};return this.#c=M({initialPromise:t?.initialPromise,fn:r.fetchFn,abort:n.abort.bind(n),onSuccess:e=>{if(void 0!==e){try{this.setData(e)}catch(e){return void s(e)}this.#a.config.onSuccess?.(e,this),this.#a.config.onSettled?.(e,this.state.error,this),this.scheduleGc()}else s(new Error(`${this.queryHash} data is undefined`))},onError:s,onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:()=>{this.#h({type:"continue"})},retry:r.options.retry,retryDelay:r.options.retryDelay,networkMode:r.options.networkMode,canRun:()=>!0}),this.#c.start()}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...t,fetchStatus:"paused"};case"continue":return{...t,fetchStatus:"fetching"};case"fetch":return{...t,...$(t.data,this.options),fetchMeta:e.meta??null};case"success":return{...t,data:e.data,dataUpdateCount:t.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const n=e.error;return Q(n)&&n.revert&&this.#o?{...this.#o,fetchStatus:"idle"}:{...t,error:n,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...t,isInvalidated:!0};case"setState":return{...t,...e.state}}})(this.state),z.batch((()=>{this.observers.forEach((e=>{e.onQueryUpdate()})),this.#a.notify({query:this,type:"updated",action:e})}))}};function $(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:I(t.networkMode)?"fetching":"paused",...void 0===e&&{error:null,status:"pending"}}}var H=class extends u{constructor(e={}){super(),this.config=e,this.#p=new Map}#p;build(e,t,n){const i=t.queryKey,r=t.queryHash??v(i,t);let s=this.get(r);return s||(s=new _({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(s)),s}add(e){this.#p.has(e.queryHash)||(this.#p.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#p.get(e.queryHash);t&&(e.destroy(),t===e&&this.#p.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){z.batch((()=>{this.getAll().forEach((e=>{this.remove(e)}))}))}get(e){return this.#p.get(e)}getAll(){return[...this.#p.values()]}find(e){const t={exact:!0,...e};return this.getAll().find((e=>g(t,e)))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter((t=>g(e,t))):t}notify(e){z.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}onFocus(){z.batch((()=>{this.getAll().forEach((e=>{e.onFocus()}))}))}onOnline(){z.batch((()=>{this.getAll().forEach((e=>{e.onOnline()}))}))}},K=class extends U{#f;#g;#c;constructor(e){super(),this.mutationId=e.mutationId,this.#g=e.mutationCache,this.#f=[],this.state=e.state||{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0},this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#f.includes(e)||(this.#f.push(e),this.clearGcTimeout(),this.#g.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#f=this.#f.filter((t=>t!==e)),this.scheduleGc(),this.#g.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#f.length||("pending"===this.state.status?this.scheduleGc():this.#g.remove(this))}continue(){return this.#c?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#h({type:"continue"})};this.#c=M({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#g.canRun(this)});const n="pending"===this.state.status,i=!this.#c.canStart();try{if(n)t();else{this.#h({type:"pending",variables:e,isPaused:i}),await(this.#g.config.onMutate?.(e,this));const t=await(this.options.onMutate?.(e));t!==this.state.context&&this.#h({type:"pending",context:t,variables:e,isPaused:i})}const r=await this.#c.start();return await(this.#g.config.onSuccess?.(r,e,this.state.context,this)),await(this.options.onSuccess?.(r,e,this.state.context)),await(this.#g.config.onSettled?.(r,null,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(r,null,e,this.state.context)),this.#h({type:"success",data:r}),r}catch(t){try{throw await(this.#g.config.onError?.(t,e,this.state.context,this)),await(this.options.onError?.(t,e,this.state.context)),await(this.#g.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(void 0,t,e,this.state.context)),t}finally{this.#h({type:"error",error:t})}}finally{this.#g.runNext(this)}}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...t,isPaused:!0};case"continue":return{...t,isPaused:!1};case"pending":return{...t,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{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}})(this.state),z.batch((()=>{this.#f.forEach((t=>{t.onMutationUpdate(e)})),this.#g.notify({mutation:this,type:"updated",action:e})}))}};var N=class extends u{constructor(e={}){super(),this.config=e,this.#y=new Set,this.#v=new Map,this.#m=0}#y;#v;#m;build(e,t,n){const i=new K({mutationCache:this,mutationId:++this.#m,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#y.add(e);const t=B(e);if("string"==typeof t){const n=this.#v.get(t);n?n.push(e):this.#v.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#y.delete(e)){const t=B(e);if("string"==typeof t){const n=this.#v.get(t);if(n)if(n.length>1){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}else n[0]===e&&this.#v.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=B(e);if("string"==typeof t){const n=this.#v.get(t),i=n?.find((e=>"pending"===e.state.status));return!i||i===e}return!0}runNext(e){const t=B(e);if("string"==typeof t){const n=this.#v.get(t)?.find((t=>t!==e&&t.state.isPaused));return n?.continue()??Promise.resolve()}return Promise.resolve()}clear(){z.batch((()=>{this.#y.forEach((e=>{this.notify({type:"removed",mutation:e})})),this.#y.clear(),this.#v.clear()}))}getAll(){return Array.from(this.#y)}find(e){const t={exact:!0,...e};return this.getAll().find((e=>y(t,e)))}findAll(e={}){return this.getAll().filter((t=>y(e,t)))}notify(e){z.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}resumePausedMutations(){const e=this.getAll().filter((e=>e.state.isPaused));return z.batch((()=>Promise.all(e.map((e=>e.continue().catch(l))))))}};function B(e){return e.options.scope?.id}function V(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},u=0;const c=async()=>{let n=!1;const c=T(t.options,t.fetchOptions),l=async(e,i,r)=>{if(n)return Promise.reject();if(null==i&&e.pages.length)return Promise.resolve(e);const s={client:t.client,queryKey:t.queryKey,pageParam:i,direction:r?"backward":"forward",meta:t.options.meta};var o;o=s,Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(t.signal.aborted?n=!0:t.signal.addEventListener("abort",(()=>{n=!0})),t.signal)});const a=await c(s),{maxPages:u}=t.options,l=r?F:k;return{pages:l(e.pages,a,u),pageParams:l(e.pageParams,i,u)}};if(r&&s.length){const e="backward"===r,t={pages:s,pageParams:o},n=(e?W:G)(i,t);a=await l(t,n,e)}else{const t=e??s.length;do{const e=0===u?o[0]??i.initialPageParam:G(i,a);if(u>0&&null==e)break;a=await l(a,e),u++}while(u<t)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(c,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=c}}}function G(e,{pages:t,pageParams:n}){const i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,n[i],n):void 0}function W(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var J=class{#b;#g;#l;#x;#C;#j;#S;#w;constructor(e={}){this.#b=e.queryCache||new H,this.#g=e.mutationCache||new N,this.#l=e.defaultOptions||{},this.#x=new Map,this.#C=new Map,this.#j=0}mount(){this.#j++,1===this.#j&&(this.#S=q.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onFocus())})),this.#w=D.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onOnline())})))}unmount(){this.#j--,0===this.#j&&(this.#S?.(),this.#S=void 0,this.#w?.(),this.#w=void 0)}isFetching(e){return this.#b.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#g.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#b.build(this,t),i=n.state.data;return void 0===i?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(p(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(i))}getQueriesData(e){return this.#b.findAll(e).map((({queryKey:e,state:t})=>[e,t.data]))}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),r=this.#b.get(i.queryHash),s=r?.state.data,o=function(e,t){return"function"==typeof e?e(t):e}(t,s);if(void 0!==o)return this.#b.build(this,i).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return z.batch((()=>this.#b.findAll(e).map((({queryKey:e})=>[e,this.setQueryData(e,t,n)]))))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state}removeQueries(e){const t=this.#b;z.batch((()=>{t.findAll(e).forEach((e=>{t.remove(e)}))}))}resetQueries(e,t){const n=this.#b;return z.batch((()=>(n.findAll(e).forEach((e=>{e.reset()})),this.refetchQueries({type:"active",...e},t))))}cancelQueries(e,t={}){const n={revert:!0,...t},i=z.batch((()=>this.#b.findAll(e).map((e=>e.cancel(n)))));return Promise.all(i).then(l).catch(l)}invalidateQueries(e,t={}){return z.batch((()=>(this.#b.findAll(e).forEach((e=>{e.invalidate()})),"none"===e?.refetchType?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t))))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},i=z.batch((()=>this.#b.findAll(e).filter((e=>!e.isDisabled())).map((e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(l)),"paused"===e.state.fetchStatus?Promise.resolve():t}))));return Promise.all(i).then(l)}fetchQuery(e){const t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);const n=this.#b.build(this,t);return n.isStaleByTime(p(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(l).catch(l)}fetchInfiniteQuery(e){return e.behavior=V(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(l).catch(l)}ensureInfiniteQueryData(e){return e.behavior=V(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return D.isOnline()?this.#g.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#b}getMutationCache(){return this.#g}getDefaultOptions(){return this.#l}setDefaultOptions(e){this.#l=e}setQueryDefaults(e,t){this.#x.set(m(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#x.values()],n={};return t.forEach((t=>{b(e,t.queryKey)&&Object.assign(n,t.defaultOptions)})),n}setMutationDefaults(e,t){this.#C.set(m(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#C.values()],n={};return t.forEach((t=>{b(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)})),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#l.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=v(t.queryKey,t)),void 0===t.refetchOnReconnect&&(t.refetchOnReconnect="always"!==t.networkMode),void 0===t.throwOnError&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===R&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#l.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#b.clear(),this.#g.clear()}},Y=class extends u{constructor(e,t){super(),this.options=t,this.#u=e,this.#O=null,this.#k=E(),this.options.experimental_prefetchInRender||this.#k.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#u;#F=void 0;#R=void 0;#T=void 0;#q;#D;#k;#O;#E;#P;#I;#A;#Q;#M;#L=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#F.addObserver(this),X(this.#F,this.options)?this.#z():this.updateResult(),this.#U())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Z(this.#F,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Z(this.#F,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#$(),this.#F.removeObserver(this)}setOptions(e){const t=this.options,n=this.#F;if(this.options=this.#u.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof f(this.options.enabled,this.#F))throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#H(),this.#F.setOptions(this.options),t._defaulted&&!C(this.options,t)&&this.#u.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#F,observer:this});const i=this.hasListeners();i&&ee(this.#F,n,this.options,t)&&this.#z(),this.updateResult(),!i||this.#F===n&&f(this.options.enabled,this.#F)===f(t.enabled,this.#F)&&p(this.options.staleTime,this.#F)===p(t.staleTime,this.#F)||this.#K();const r=this.#N();!i||this.#F===n&&f(this.options.enabled,this.#F)===f(t.enabled,this.#F)&&r===this.#M||this.#B(r)}getOptimisticResult(e){const t=this.#u.getQueryCache().build(this.#u,e),n=this.createResult(t,e);return function(e,t){if(!C(e.getCurrentResult(),t))return!0;return!1}(this,n)&&(this.#T=n,this.#D=this.options,this.#q=this.#F.state),n}getCurrentResult(){return this.#T}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#L.add(e)}getCurrentQuery(){return this.#F}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#u.defaultQueryOptions(e),n=this.#u.getQueryCache().build(this.#u,t);return n.fetch().then((()=>this.createResult(n,t)))}fetch(e){return this.#z({...e,cancelRefetch:e.cancelRefetch??!0}).then((()=>(this.updateResult(),this.#T)))}#z(e){this.#H();let t=this.#F.fetch(this.options,e);return e?.throwOnError||(t=t.catch(l)),t}#K(){this.#_();const e=p(this.options.staleTime,this.#F);if(c||this.#T.isStale||!d(e))return;const t=h(this.#T.dataUpdatedAt,e)+1;this.#A=setTimeout((()=>{this.#T.isStale||this.updateResult()}),t)}#N(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#F):this.options.refetchInterval)??!1}#B(e){this.#$(),this.#M=e,!c&&!1!==f(this.options.enabled,this.#F)&&d(this.#M)&&0!==this.#M&&(this.#Q=setInterval((()=>{(this.options.refetchIntervalInBackground||q.isFocused())&&this.#z()}),this.#M))}#U(){this.#K(),this.#B(this.#N())}#_(){this.#A&&(clearTimeout(this.#A),this.#A=void 0)}#$(){this.#Q&&(clearInterval(this.#Q),this.#Q=void 0)}createResult(e,t){const n=this.#F,i=this.options,r=this.#T,s=this.#q,o=this.#D,a=e!==n?e.state:this.#R,{state:u}=e;let c,l={...u},d=!1;if(t._optimisticResults){const r=this.hasListeners(),s=!r&&X(e,t),o=r&&ee(e,n,t,i);(s||o)&&(l={...l,...$(u.data,e.options)}),"isRestoring"===t._optimisticResults&&(l.fetchStatus="idle")}let{error:h,errorUpdatedAt:p,status:f}=l;c=l.data;let g=!1;if(void 0!==t.placeholderData&&void 0===c&&"pending"===f){let e;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=r.data,g=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#I?.state.data,this.#I):t.placeholderData,void 0!==e&&(f="success",c=O(r?.data,e,t),d=!0)}if(t.select&&void 0!==c&&!g)if(r&&c===s?.data&&t.select===this.#E)c=this.#P;else try{this.#E=t.select,c=t.select(c),c=O(r?.data,c,t),this.#P=c,this.#O=null}catch(e){this.#O=e}this.#O&&(h=this.#O,c=this.#P,p=Date.now(),f="error");const y="fetching"===l.fetchStatus,v="pending"===f,m="error"===f,b=v&&y,x=void 0!==c,C={status:f,fetchStatus:l.fetchStatus,isPending:v,isSuccess:"success"===f,isError:m,isInitialLoading:b,isLoading:b,data:c,dataUpdatedAt:l.dataUpdatedAt,error:h,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>a.dataUpdateCount||l.errorUpdateCount>a.errorUpdateCount,isFetching:y,isRefetching:y&&!v,isLoadingError:m&&!x,isPaused:"paused"===l.fetchStatus,isPlaceholderData:d,isRefetchError:m&&x,isStale:te(e,t),refetch:this.refetch,promise:this.#k};if(this.options.experimental_prefetchInRender){const t=e=>{"error"===C.status?e.reject(C.error):void 0!==C.data&&e.resolve(C.data)},i=()=>{const e=this.#k=C.promise=E();t(e)},r=this.#k;switch(r.status){case"pending":e.queryHash===n.queryHash&&t(r);break;case"fulfilled":"error"!==C.status&&C.data===r.value||i();break;case"rejected":"error"===C.status&&C.error===r.reason||i()}}return C}updateResult(){const e=this.#T,t=this.createResult(this.#F,this.options);if(this.#q=this.#F.state,this.#D=this.options,void 0!==this.#q.data&&(this.#I=this.#F),C(t,e))return;this.#T=t;this.#V({listeners:(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options,n="function"==typeof t?t():t;if("all"===n||!n&&!this.#L.size)return!0;const i=new Set(n??this.#L);return this.options.throwOnError&&i.add("error"),Object.keys(this.#T).some((t=>{const n=t;return this.#T[n]!==e[n]&&i.has(n)}))})()})}#H(){const e=this.#u.getQueryCache().build(this.#u,this.options);if(e===this.#F)return;const t=this.#F;this.#F=e,this.#R=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#U()}#V(e){z.batch((()=>{e.listeners&&this.listeners.forEach((e=>{e(this.#T)})),this.#u.getQueryCache().notify({query:this.#F,type:"observerResultsUpdated"})}))}};function X(e,t){return function(e,t){return!1!==f(t.enabled,e)&&void 0===e.state.data&&!("error"===e.state.status&&!1===t.retryOnMount)}(e,t)||void 0!==e.state.data&&Z(e,t,t.refetchOnMount)}function Z(e,t,n){if(!1!==f(t.enabled,e)){const i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&te(e,t)}return!1}function ee(e,t,n,i){return(e!==t||!1===f(i.enabled,e))&&(!n.suspense||"error"!==e.state.status)&&te(e,n)}function te(e,t){return!1!==f(t.enabled,e)&&e.isStaleByTime(p(t.staleTime,e))}var ne=a.createContext(void 0),ie=({client:t,children:n})=>(a.useEffect((()=>(t.mount(),()=>{t.unmount()})),[t]),e.jsx(ne.Provider,{value:t,children:n})),re=a.createContext(!1);re.Provider;var se=a.createContext(function(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}()),oe=(e,t,n)=>t.fetchOptimistic(e).catch((()=>{n.clearReset()}));function ae(e,t,n){const i=(()=>{const e=a.useContext(ne);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e})(),r=a.useContext(re),s=a.useContext(se),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=r?"isRestoring":"optimistic",(e=>{const t=e.staleTime;e.suspense&&(e.staleTime="function"==typeof t?(...e)=>Math.max(t(...e),1e3):Math.max(t??1e3,1e3),"number"==typeof e.gcTime&&(e.gcTime=Math.max(e.gcTime,1e3)))})(o),((e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))})(o,s),(e=>{a.useEffect((()=>{e.clearReset()}),[e])})(s);const u=!i.getQueryCache().get(o.queryHash),[d]=a.useState((()=>new t(i,o))),h=d.getOptimisticResult(o),p=!r&&!1!==e.subscribed;if(a.useSyncExternalStore(a.useCallback((e=>{const t=p?d.subscribe(z.batchCalls(e)):l;return d.updateResult(),t}),[d,p]),(()=>d.getCurrentResult()),(()=>d.getCurrentResult())),a.useEffect((()=>{d.setOptions(o)}),[o,d]),((e,t)=>e?.suspense&&t.isPending)(o,h))throw oe(o,d,s);if((({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&void 0===e.data||function(e,t){return"function"==typeof e?e(...t):!!e}(n,[e.error,i])))({result:h,errorResetBoundary:s,throwOnError:o.throwOnError,query:i.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw h.error;if(i.getDefaultOptions().queries?._experimental_afterQuery?.(o,h),o.experimental_prefetchInRender&&!c&&((e,t)=>e.isLoading&&e.isFetching&&!t)(h,r)){const e=u?oe(o,d,s):i.getQueryCache().get(o.queryHash)?.promise;e?.catch(l).finally((()=>{d.updateResult()}))}return o.notifyOnChangeProps?h:d.trackResult(h)}function ue(e,t){return ae(e,Y)}const ce=({message:n})=>e.jsx(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:e.jsx(t.Typography.Text,{size:"medium",fontWeight:"semi-bold",children:n})});var le=Object.prototype.hasOwnProperty;function de(e,t,n){for(n of e.keys())if(he(n,t))return n}function he(e,t){var n,i,r;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((i=e.length)===t.length)for(;i--&&he(e[i],t[i]););return-1===i}if(n===Set){if(e.size!==t.size)return!1;for(i of e){if((r=i)&&"object"==typeof r&&!(r=de(t,r)))return!1;if(!t.has(r))return!1}return!0}if(n===Map){if(e.size!==t.size)return!1;for(i of e){if((r=i[0])&&"object"==typeof r&&!(r=de(t,r)))return!1;if(!he(i[1],t.get(r)))return!1}return!0}if(n===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(n===DataView){if((i=e.byteLength)===t.byteLength)for(;i--&&e.getInt8(i)===t.getInt8(i););return-1===i}if(ArrayBuffer.isView(e)){if((i=e.byteLength)===t.byteLength)for(;i--&&e[i]===t[i];);return-1===i}if(!n||"object"==typeof e){for(n in i=0,e){if(le.call(e,n)&&++i&&!le.call(t,n))return!1;if(!(n in t)||!he(e[n],t[n]))return!1}return Object.keys(t).length===i}}return e!=e&&t!=t}function pe(e,t){return a.useEffect(e,(n=t,i=a.useRef(n),r=a.useRef(0),he(n,i.current)||(i.current=n,r.current+=1),a.useMemo((function(){return i.current}),[r.current])));var n,i,r}function fe(e){return"anchor"in e&&"string"==typeof e.anchor&&e.anchor.trim().length>0}const ge=/^__secretvalue:\*\*redacted\*\*(.*)$/,ye=e=>(e=>"string"==typeof e)(e)&&ge.test(e),ve=e=>{const t="••••••••••";if(!ye(e))return e;const n=e.match(ge);if(!n)return t;const i=n[1];return i?t+i:t},me={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/};function be(e){return void 0!==e.type}function xe(e){if((e=>{const t=[];let n=!1;const i=/\{(\d+)(?:(,)(\d*))?\}/y,r=t=>{const n=e[t];if("*"===n||"+"===n)return{length:1,variable:!0,amplifying:!0};if("?"===n)return{length:1,variable:!0,amplifying:!1};if("{"===n){i.lastIndex=t;const n=i.exec(e);if(n){const e=Number(n[1]),t=void 0===n[2]?e:n[3]?Number(n[3]):1/0;return{length:n[0].length,variable:t>e,amplifying:t>=2}}}};for(let i=0;i<e.length;i++){const s=e[i];if("\\"===s){i++;continue}if(n){"]"===s&&(n=!1);continue}if("["===s){n=!0;continue}if("|"===s){t.length>0&&(t[t.length-1].hasAlternation=!0);continue}if("("===s){t.push({hasVariable:!1,hasAlternation:!1}),"?"===e[i+1]&&(i+="<"!==e[i+2]||"="!==e[i+3]&&"!"!==e[i+3]?1:2);continue}if(")"===s){const e=t.pop(),n=r(i+1);if(n){if(n.amplifying&&((null==e?void 0:e.hasVariable)||(null==e?void 0:e.hasAlternation)))return!0;i+=n.length}t.length>0&&(((null==n?void 0:n.variable)||(null==e?void 0:e.hasVariable))&&(t[t.length-1].hasVariable=!0),(null==e?void 0:e.hasAlternation)&&(t[t.length-1].hasAlternation=!0));continue}const o=r(i);o&&(o.variable&&t.length>0&&(t[t.length-1].hasVariable=!0),i+=o.length-1)}return!1})(e))return console.warn(`[stackone-hub] pattern "${e}" risks catastrophic backtracking — field validation skipped`),null;try{return new RegExp(e)}catch(t){return console.warn(`[stackone-hub] pattern "${e}" failed to compile — field validation skipped`),null}}function Ce(e){return e.validation?be(e.validation)?function(e){if("html-pattern"===e.type){const t=xe(e.pattern);return t?{pattern:t,errorMessage:e.error||`Please match the required format: ${e.pattern}`}:null}if("domain"===e.type){const t=xe(`.*${e.pattern}\\.com.*`);return t?{pattern:t,errorMessage:e.error||`Please enter a valid ${e.pattern}.com domain`}:null}return null}(e.validation):function(e,t){if(e.format){const t=Object.prototype.hasOwnProperty.call(me,e.format)?me[e.format]:void 0;return t?{pattern:t,errorMessage:e.errorMessage||`Must be a valid ${e.format}`}:(console.warn(`[stackone-hub] no pattern for format "${e.format}" — field validation skipped; hub FORMAT_PATTERNS has drifted from @stackone/core`),null)}if(e.pattern){const n=xe(e.pattern);return n?{pattern:n,errorMessage:e.errorMessage||`${t} format is invalid`}:null}return null}(e.validation,e.label):null}function je(e){const t=new Map;for(const n of e){if("number"===n.type&&!n.required)continue;const e=Ce(n);e&&t.set(n.key,e)}return t}function Se(e,t){return!(!e||"string"!=typeof t||""===t||ye(t))&&!e.pattern.test(t)}function we(e,t){let n=s.z.string();e.required&&(n=n.min(1,`${e.label} is required`));const i=t=>n=>""===n?!e.required:t(n);return"number"===e.type&&(n=n.refine(i((e=>ye(e)||/^\d+$/.test(e))),"Must be a valid number")),t&&(n=n.refine(i((e=>!Se(t,e))),t.errorMessage)),n}const Oe=({field:n,errors:i,setValue:r,onLeave:s,editingSecrets:o,setEditingSecrets:a})=>{var u,c,l,d,h,p,f,g,y,v,m,b,x,C,j,S,w,O,k,F,R,T,q;const D="object"==typeof n.key?JSON.stringify(n.key):String(n.key),E=i[D]&&e.jsx(t.Typography.Text,{color:"error",style:{marginTop:"4px",fontSize:"12px"},children:null===(u=i[D])||void 0===u?void 0:u.message});if("text"===(P=n.type)||"number"===P||"password"===P){const u=n.readOnly,b=null===(c=n.value)||void 0===c?void 0:c.toString(),x="external-trigger-token"!==n.key&&(!1!==n.secret||"password"===n.type),C=u&&b&&!x,j=null!==(l=null==o?void 0:o.has(D))&&void 0!==l&&l;if(x&&ye(b)&&!j)return e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{name:`${D}-display`,label:n.label,placeholder:n.placeholder,type:"text",required:n.required,disabled:!0,readOnly:!0,defaultValue:b?ve(b):"",description:null!==(h=null===(d=n.guide)||void 0===d?void 0:d.description)&&void 0!==h?h:n.description,tooltip:null!==(f=null===(p=n.guide)||void 0===p?void 0:p.tooltip)&&void 0!==f?f:n.tooltip,showCopyButton:!1,buttons:a?[{label:"Edit",variant:"filled",size:"xsmall",onClick:()=>{a((e=>new Set(e).add(D))),r(D,"",{shouldValidate:!0,shouldDirty:!0})}}]:void 0}),E]});const S=!x&&(n.readOnly||!1),w=x?void 0:C?()=>{}:void 0;return e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{name:D,required:!!u||n.required,placeholder:n.placeholder,disabled:S,readOnly:n.readOnly,label:n.label,tooltip:null!==(y=null===(g=n.guide)||void 0===g?void 0:g.tooltip)&&void 0!==y?y:n.tooltip,description:null!==(m=null===(v=n.guide)||void 0===v?void 0:v.description)&&void 0!==m?m:n.description,type:n.type,error:!!i[D],onChange:e=>r(D,e,{shouldValidate:!0}),onBlur:s,defaultValue:x&&j?"":b,showPasswordToggle:!1,onCopyClick:w},`${D}-${j?"editing":"view"}`),E]})}var P;return"text_area"===n.type?e.jsxs(e.Fragment,{children:[e.jsx(t.TextArea,{name:D,required:n.required,placeholder:n.placeholder,disabled:n.readOnly,label:n.label,tooltip:null!==(x=null===(b=n.guide)||void 0===b?void 0:b.tooltip)&&void 0!==x?x:n.tooltip,description:null!==(j=null===(C=n.guide)||void 0===C?void 0:C.description)&&void 0!==j?j:n.description,error:!!i[D],onChange:e=>r(D,e,{shouldValidate:!0}),onBlur:s,defaultValue:(null===(S=n.value)||void 0===S?void 0:S.toString())||""}),E]}):"select"===n.type?e.jsxs(e.Fragment,{children:[e.jsx(t.Dropdown,{defaultValue:(null===(w=n.value)||void 0===w?void 0:w.toString())||"",disabled:n.readOnly,items:null!==(k=null===(O=n.options)||void 0===O?void 0:O.map((e=>({id:e.value,label:e.label}))))&&void 0!==k?k:[],onItemSelected:e=>r(D,null!=e?e:"",{shouldValidate:!0}),name:D,label:n.label,placeholder:n.placeholder,tooltip:null!==(R=null===(F=n.guide)||void 0===F?void 0:F.tooltip)&&void 0!==R?R:n.tooltip,description:null!==(q=null===(T=n.guide)||void 0===T?void 0:T.description)&&void 0!==q?q:n.description,required:n.required,error:!!i[D]}),E]}):null},ke=({error:n})=>{if(!n)return null;try{return e.jsx(t.CodeBlock,{json:JSON.parse(n.provider_response)})}catch(i){return(null==n?void 0:n.provider_response)&&(null==n?void 0:n.provider_response.length)>0?e.jsx(t.CodeBlock,{code:null==n?void 0:n.provider_response}):null}},Fe=({integrationName:n,error:i,notices:r=[]})=>{var s;return e.jsxs(t.Padded,{vertical:"large",horizontal:"medium",overflow:"auto",fullHeight:!0,children:[i&&e.jsx(t.Alert,{type:"error",message:(null===(s=i.provider_response)||void 0===s?void 0:s.trim())||i.message,hasMargin:!1,children:e.jsx(ke,{error:i})}),r.map((n=>e.jsx(t.Alert,{type:n.type,message:n.description,hasMargin:!1},n.key))),e.jsx(t.Flex,{direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,justify:t.FlexJustify.Center,align:t.FlexAlign.Center,children:e.jsxs(t.Spacer,{direction:"vertical",size:8,fullWidth:!0,children:[e.jsx(t.Typography.Text,{size:"small",fontWeight:"semi-bold",children:'Press "Connect" below to authenticate'}),e.jsxs(t.Typography.Text,{size:"small",color:"secondary",children:["An authentication window for ",n," will display,",e.jsx("br",{}),"please complete the necessary steps."]})]})})]})},Re=({fields:o,notices:a=[],onChange:u,error:c,onValidationChange:l,integrationName:d,connectorKey:h,editingSecrets:p,setEditingSecrets:f})=>{const g=o.filter((e=>!1!==e.display)),y=g.map((e=>"object"==typeof e.key?JSON.stringify(e.key):String(e.key))),{noticesBefore:v,noticesAfter:m}=function(e,t=[]){const n=t[0],i=t[t.length-1];return{noticesBefore:t=>e.filter((e=>fe(e)?e.anchor===t:(!e.position||"top"===e.position)&&t===n)),noticesAfter:t=>e.filter((e=>!fe(e)&&"bottom"===e.position&&t===i))}}(a,y),b=n.useMemo((()=>function(e){const t=new Set;return(n,i)=>{if("undefined"==typeof window||t.has(n.key))return;t.add(n.key);const r=be(i)?void 0:i.format;window.dispatchEvent(new CustomEvent("stackone-hub:field-validation-failed",{detail:Object.assign(Object.assign(Object.assign({},e?{connector:e}:{}),{field:n.key,ruleKind:be(i)?"legacy":r?"format":"pattern"}),r?{format:r}:{})}))}}(h)),[h]),x=n.useMemo((()=>je(o)),[o]),C=n.useMemo((()=>function(e,t=je(e)){const n={};for(const i of e)n[i.key]=we(i,t.get(i.key));return s.z.object(n)}(o,x)),[o,x]),j=n.useMemo((()=>{const e={};return o.forEach((t=>{void 0!==t.value?e[t.key]=t.value.toString():e[t.key]=""})),e}),[o]),{formState:S,watch:w,reset:O,setValue:k,getValues:F}=r.useForm({resolver:i.zodResolver(C),mode:"onTouched",defaultValues:j}),{errors:R,isValid:T}=S;pe((()=>{O(j)}),[j]);const q=w();pe((()=>{u(q)}),[q]),n.useEffect((()=>{null==l||l(T)}),[T,l]);const D=e=>{document.hasFocus()&&e.validation&&function(e,t,n){return Se(t.get(e.key),n)}(e,x,F(e.key))&&b(e,e.validation)};return 0===g.length?e.jsx(Fe,{integrationName:d,error:c,notices:a}):e.jsx(t.Padded,{vertical:"large",horizontal:"medium",overflow:"auto",children:e.jsxs(t.Spacer,{direction:"vertical",size:8,fullWidth:!0,children:[c&&e.jsx(t.Alert,{type:"error",message:c.message,hasMargin:!1,children:e.jsx(ke,{error:c})}),e.jsx(t.Form,{children:g.map((n=>{const i="object"==typeof n.key?JSON.stringify(n.key):String(n.key),r=v(i).length>0||m(i).length>0;return e.jsxs("div",{style:Object.assign(Object.assign({},r&&{display:"flex",flexDirection:"column",gap:"8px"}),{width:"100%"}),children:[v(i).map((n=>e.jsx(t.Alert,{type:n.type,message:n.description,hasMargin:!1},n.key))),e.jsx(Oe,{field:n,errors:R,setValue:k,onLeave:()=>D(n),editingSecrets:p,setEditingSecrets:f}),m(i).map((n=>e.jsx(t.Alert,{type:n.type,message:n.description,hasMargin:!1},n.key)))]},i)}))})]})})},Te=({fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:u,setEditingSecrets:c})=>e.jsx(Re,{fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:u,setEditingSecrets:c}),qe=e=>e.split(/[-_\s]+/).filter(Boolean),De=e=>qe(e).join(" ").toLowerCase(),Ee=e=>qe(e).join(" ").toUpperCase(),Pe=({src:t,alt:i,fallbackUrl:r="https://stackone-logos.com/api/stackone/filled/png",style:s,className:o})=>{const[a,u]=n.useState(t);return e.jsx("img",{src:a,alt:i,style:s,className:o,onError:()=>{u(r)}})},Ie=e=>Boolean(e.active&&e.name),Ae=({integration:n})=>{var i;return e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.SpaceBetween,width:"100%",children:[e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.Left,width:"100%",children:[e.jsx(Pe,{src:n.logo_url,alt:n.provider,style:{width:"24px",height:"24px"}}),e.jsx(t.Typography.Text,{textAlign:"left",children:null!==(i=n.name)&&void 0!==i?i:"N/A"})]}),e.jsx(t.Typography.SecondaryText,{size:"xsmall",style:{maxWidth:"45%",flexShrink:0},children:e.jsx(t.TruncatedTooltip,{text:Ee(n.type),children:Ee(n.type)})})]})},Qe=({integrations:i,selectedCategory:r,onCategoryChange:s,onSearchChange:o})=>{const a=n.useCallback((e=>{s(r===e?null:e)}),[r,s]),u=n.useMemo((()=>Array.from(new Set(i.filter(Ie).map((e=>De(e.type)))))),[i]);return e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{name:"search",placeholder:"Search Integrations",variant:"ghost",size:"large",onChange:o}),u.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(t.Divider,{}),e.jsx(t.Padded,{vertical:"small",horizontal:"none",fullHeight:!1,children:e.jsx("div",{style:{overflowX:"auto",overflowY:"hidden",backgroundColor:"var(--malachite-card-background)",scrollbarWidth:"none",msOverflowStyle:"none"},className:"hide-scrollbar",children:e.jsx("div",{style:{display:"flex",minWidth:"max-content"},children:u.map((n=>e.jsx(t.Padded,{vertical:"none",horizontal:"small",fullHeight:!1,children:e.jsx(t.PillButton,{size:"xsmall",label:Ee(n),selected:r===n,onClick:()=>a(n)})},n)))})})})]})]})},Me=({integrations:i,onSelect:r,selectedCategory:s,search:o})=>{const a=n.useMemo((()=>i.filter((e=>Ie(e)&&(!s||De(e.type)===s)&&(!o||e.name.toLowerCase().includes(o.toLowerCase()))))),[i,s,o]);return e.jsx(e.Fragment,{children:a.length>0?e.jsx(t.Padded,{vertical:"small",horizontal:"small",fullHeight:!1,children:e.jsx(t.Spacer,{direction:"vertical",size:10,align:"start",children:e.jsx(t.ButtonList,{buttons:a.map((t=>({key:`${t.provider}@${t.version}`,children:e.jsx(Ae,{integration:t}),onClick:()=>r(t)})))})})}):e.jsx(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,fullHeight:!0,children:e.jsx(t.Typography.SecondaryText,{children:"No integrations found"})})})},Le=({integrations:t,onSelect:n,selectedCategory:i,search:r})=>t.length?e.jsx(Me,{integrations:t,onSelect:n,selectedCategory:i,search:r}):e.jsx("div",{children:"No integrations found."}),ze=({title:i,description:r,onCancel:s})=>{const[o,a]=n.useState(!1),u=n.useRef(null);return n.useEffect((()=>{if(s)return u.current=setTimeout((()=>a(!0)),5e3),()=>{u.current&&clearTimeout(u.current)}}),[s]),e.jsxs(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:[e.jsx(t.Spinner,{size:"xxxsmall"}),e.jsx(t.Typography.Text,{fontWeight:"bold",size:"large",children:i}),e.jsx(t.Typography.SecondaryText,{children:r}),o&&s&&e.jsxs(t.Typography.SecondaryText,{children:["Having trouble?"," ",e.jsx("button",{type:"button",onClick:s,style:{background:"none",border:"none",padding:0,cursor:"pointer",textDecoration:"underline",font:"inherit",color:"inherit"},children:"Cancel and start over"})]})]})},Ue=({title:t,description:n,onCancel:i})=>e.jsx(ze,{title:t,description:n,onCancel:i}),_e=({integrationName:n})=>{const i=t.getCurrentTheme();return e.jsxs(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:[e.jsx(t.CustomIcons.CheckCircleFilled,{size:16,style:{color:i.colors.success.foreground}}),e.jsx(t.Typography.Text,{fontWeight:"bold",size:"large",children:"Connection Successful"}),e.jsxs(t.Typography.SecondaryText,{children:["Account successfully connected to ",n]})]})},$e=({integrationName:t})=>e.jsx(_e,{integrationName:t}),He=({isLoading:t,hasError:n,connectionState:i,selectedIntegration:r,connectorData:s,hubData:o,fields:a,notices:u,selectedCategory:c,search:l,errorHubData:d,errorConnectorData:h,onSelect:p,onChange:f,onValidationChange:g,onCancelOAuth:y,editingSecrets:v,setEditingSecrets:m})=>{var b,x;return t?e.jsx(Ue,{title:"Loading integration data",description:"Please wait, this may take a moment."}):i.loading&&r?e.jsx(Ue,{title:`Connecting to ${null!==(b=null==s?void 0:s.name)&&void 0!==b?b:r.name}`,description:"Please wait, this may take a moment.",onCancel:y}):n?e.jsx(ce,{message:(null==d?void 0:d.message)||(null==h?void 0:h.message)||"Unknown error"}):i.success&&r?e.jsx($e,{integrationName:null!==(x=null==s?void 0:s.name)&&void 0!==x?x:r.name}):r?s?e.jsx(Te,{fields:a,notices:u,error:i.error,onChange:f,onValidationChange:g,integrationName:s.name,connectorKey:s.key,editingSecrets:v,setEditingSecrets:m}):null:(null==o?void 0:o.integrations.length)?e.jsx(Le,{integrations:o.integrations,onSelect:p,selectedCategory:c,search:l}):e.jsx(ce,{message:"No configured integrations available."})},Ke=({connectorData:n,onBack:i,guide:r})=>{var s;return e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.SpaceBetween,children:[e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.Left,children:[i&&e.jsx(t.Button,{variant:"ghost",onClick:i,icon:"←",size:"small"}),e.jsx(Pe,{src:null===(s=n.assets)||void 0===s?void 0:s.icon,alt:n.key,style:{width:"16px",height:"16px"}}),e.jsx(t.Typography.Text,{fontWeight:"semi-bold",size:"medium",children:n.name})]}),(null==r?void 0:r.supportLink)?e.jsx(t.Typography.LinkText,{href:r.supportLink,target:"_blank",children:e.jsx(t.Button,{variant:"outline",size:"small",children:"Connection guide"})}):null]})},Ne=({connectorData:t,accountData:n,onBack:i,guide:r,isLoading:s,hasError:o,hubData:a,selectedCategory:u,onCategoryChange:c,onSearchChange:l,hideBackButton:d})=>{if(t)return e.jsx(Ke,{connectorData:t,onBack:n||d?void 0:i,guide:r});return!s&&!o&&(null==a?void 0:a.integrations)?e.jsx(Qe,{integrations:a.integrations,selectedCategory:u,onCategoryChange:c,onSearchChange:l}):null},Be=({fullWidth:i=!0,selectedIntegration:r,showActions:s,onBack:o,onNext:a,isFormValid:u=!0,isLoading:c=!1,showFooterLinks:l=!0})=>{const d=n.useMemo((()=>{if(!r||!s)return[];const e=[];return o&&e.push({label:"Back",type:"outline",onClick:o,disabled:c,loading:!1}),e.push({label:"Connect",type:"filled",onClick:a,disabled:!u||c,loading:c}),e}),[r,o,a,s,u,c]);return 0===d.length?l?e.jsx(t.FooterLinks,{fullWidth:i}):null:e.jsxs(t.Spacer,{direction:"horizontal",size:4,justifyContent:"space-between",children:[l&&e.jsx(t.FooterLinks,{fullWidth:i}),e.jsx(t.Padded,{vertical:"none",horizontal:"small",fullHeight:!1,children:e.jsx(t.Flex,{direction:t.FlexDirection.Horizontal,justify:t.FlexJustify.Right,children:e.jsx(t.Spacer,{direction:"horizontal",size:10,children:d.map((n=>e.jsx(t.Button,{size:"small",variant:n.type,onClick:n.onClick,disabled:n.disabled,loading:n.loading,iconPosition:"end",children:n.label},n.label)))})})})]})},Ve=({showFooterLinks:n=!0,onClose:i,onCloseLabel:r})=>{const s=n,o=Boolean(i);return s||o?e.jsxs(t.Spacer,{direction:"horizontal",size:4,justifyContent:s&&o?"space-between":o?"end":void 0,children:[s&&e.jsx(t.FooterLinks,{fullWidth:!0}),o&&e.jsx(t.Padded,{vertical:"none",horizontal:"small",fullHeight:!1,children:e.jsx(t.Flex,{direction:t.FlexDirection.Horizontal,justify:t.FlexJustify.Right,children:e.jsx(t.Spacer,{direction:"horizontal",size:10,children:e.jsx(t.Button,{size:"small",variant:"filled",onClick:i,children:null!=r?r:"Close"})})})})]}):null};function Ge(e,t,n,i){return new(n||(n=Promise))((function(r,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}u((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const We="x-hub-version",Je=e=>{const t={};for(const[n,i]of Object.entries(null!=e?e:{}))n.toLowerCase()!==We.toLowerCase()&&(t[n]=i);return t[We]="1.12.0",t};function Ye(e){return Ge(this,arguments,void 0,(function*({url:e,body:t,headers:n,method:i,requestFn:r=fetch,logger:s=console}){try{const a=yield r(e,{method:i,headers:Je(n),body:JSON.stringify(t)});if((e=>401===(null==e?void 0:e.status)||403===(null==e?void 0:e.status))(a))return s.warn("Token expired"),null;{if(!a.ok){const e=yield a.json();if(e&&void 0!==(o=e).statusCode){const{statusCode:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["statusCode"]);throw new Error(JSON.stringify(Object.assign({status:t},n)))}}const e=yield a.text();return e?JSON.parse(e):null}}catch(o){throw s.error(`Error making request to ${e}`,o),o}var o}))}function Xe(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"POST"}))}))}function Ze(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"GET"}))}))}const et=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){const i={"Content-Type":"application/json","x-hub-session-token":e};let r=`${t}/hub/connectors`;return n&&(r+=`?provider=${encodeURIComponent(n)}`),yield Ze({url:r,headers:i})})),tt=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/connectors/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),nt=e=>Ge(void 0,[e],void 0,(function*({baseUrl:e,accountId:t,token:n,credentials:i,integrationId:r}){return yield function(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"PATCH"}))}))}({url:`${e}/hub/accounts/${t}`,headers:{"Content-Type":"application/json","x-hub-session-token":n},body:{integration_id:r,credentials:i}})})),it=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),rt=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield function(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"DELETE"}))}))}({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),st={retry:(e,t)=>{if(t&&"object"==typeof t&&"message"in t)try{const e=JSON.parse(t.message);if(401===e.status||403===e.status)return!1}catch(e){}return e<2},retryDelay:e=>Math.min(1e3*Math.pow(2,e),3e4)};var ot;!function(e){e.AccountConnected="AccountConnected"}(ot||(ot={}));const at=({token:e,baseUrl:t,accountId:i,onSuccess:r,dashboardUrl:s,debug:o})=>{const[a,u]=n.useState(null),[c,l]=n.useState({}),[d,h]=n.useState(new Set),p=n.useCallback((e=>{l(e)}),[]),f=n.useRef(null),g=n.useRef(null),y=n.useRef(null),v=n.useRef(null),m=n.useRef(!1),[b,x]=n.useState({loading:!1,success:!1}),C=n.useCallback((()=>{null!==y.current&&(clearTimeout(y.current),y.current=null),g.current=null}),[]),j=n.useCallback((e=>{x({loading:!1,success:!0}),null==r||r(e)}),[r]),S=n.useRef(o);S.current=o;const w=n.useCallback((()=>{null!==v.current&&(clearTimeout(v.current),v.current=null)}),[]),O=n.useCallback((()=>{C(),w(),f.current&&(f.current.close(),f.current=null)}),[C,w]);n.useEffect((()=>()=>{C(),w()}),[C,w]);const{data:k,isLoading:F,error:R}=ue(Object.assign({queryKey:["accountData",i],queryFn:()=>Ge(void 0,void 0,void 0,(function*(){return i?((e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/accounts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,i):null})),enabled:!!i},st)),{data:T,isLoading:q,error:D}=ue(Object.assign({queryKey:["hubData",null==k?void 0:k.provider],queryFn:()=>(null==k?void 0:k.provider)?et(e,t,k.provider):et(e,t),enabled:!i||!!k},st));n.useEffect((()=>{if(k&&T){const e=T.integrations.find((e=>e.provider===k.provider));u(null!=e?e:null)}}),[k,T]),n.useEffect((()=>{if(T&&!a){const e=T.integrations.filter((e=>e.active));1===e.length&&u(e[0])}}),[T,a]);const{data:E,isLoading:P,error:I}=ue(Object.assign({queryKey:["connectorData",null==k?void 0:k.integrationId,null==a?void 0:a.integration_id],queryFn:()=>Ge(void 0,void 0,void 0,(function*(){return k?tt(t,e,k.integrationId):a?tt(t,e,a.integration_id):null})),enabled:Boolean(a)||Boolean(k)},st)),{fields:A,guide:Q,notices:M}=n.useMemo((()=>{var e,t,n,i,r,s,o,u,c;if(!E||!a){return{fields:[],notices:[]}}if(("configFields"in(c=E.config)||"configNotices"in c)&&!("authentication"in c)){const s=(null!==(e=E.config.configFields)&&void 0!==e?e:[]).map((e=>{var t,n;const i=null===(t=null==k?void 0:k.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==T?void 0:T.external_trigger_token});if(k&&(!1!==e.secret||"password"===e.type)){const t=null===(n=k.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:s,notices:null!==(t=E.config.configNotices)&&void 0!==t?t:[],guide:{supportLink:null===(n=E.config.support)||void 0===n?void 0:n.link,description:null!==(r=null===(i=E.config.support)||void 0===i?void 0:i.description)&&void 0!==r?r:""}}}let l=a.authentication_config_key,d=a.environment;k&&k.authConfigKey&&(null===(s=E.config.authentication)||void 0===s?void 0:s[k.authConfigKey])&&(l=k.authConfigKey,d=null!==(o=k.environment)&&void 0!==o?o:a.environment);const h=null===(u=E.config.authentication)||void 0===u?void 0:u[l],p=null==h?void 0:h[d],f=((null==p?void 0:p.fields)||[]).map((e=>{var t,n;const i=null===(t=null==k?void 0:k.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==T?void 0:T.external_trigger_token});if(k&&(!1!==e.secret||"password"===e.type)){const t=null===(n=k.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:f,notices:[],guide:null==p?void 0:p.guide}}),[E,a,k,T]),L=n.useMemo((()=>{var e,t,n,i,r;if(!E||!a)return null;if("authentication"in(r=E.config)&&!("configFields"in r)){let r=a.authentication_config_key,s=a.environment;return k&&k.authConfigKey&&(null===(e=E.config.authentication)||void 0===e?void 0:e[k.authConfigKey])&&(r=k.authConfigKey,s=null!==(t=k.environment)&&void 0!==t?t:a.environment),null===(i=null===(n=E.config.authentication)||void 0===n?void 0:n[r])||void 0===i?void 0:i[s]}return E.config}),[E,a,k]),[z,U]=n.useState(!0),_=n.useCallback(((n,i)=>{const r=Date.now(),s=()=>Ge(void 0,void 0,void 0,(function*(){var o,a,u,c;if(!y.current)return;if(Date.now()-r>3e5)return S.current&&console.debug("[hub] poll timed out",{attemptId:n}),O(),rt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})})),void x({loading:!1,success:!1,timedOut:!0});const l=yield it(t,e,n).catch((()=>null));if(y.current){if(!l)return S.current&&console.debug("[hub] poll failed (network error), retrying"),void(y.current=window.setTimeout(s,2e3));S.current&&"pending"!==l.status&&console.debug("[hub] poll result",Object.assign({attemptId:n},l)),"authenticated"===l.status&&l.account?(O(),j({id:l.account.id,provider:i}),parent.postMessage({type:ot.AccountConnected,account:{id:l.account.id,provider:i}},"*")):"error"===l.status?(O(),x({loading:!1,success:!1,error:{message:null!==(a=null===(o=l.error)||void 0===o?void 0:o.code)&&void 0!==a?a:"OAuth error",provider_response:null!==(c=null===(u=l.error)||void 0===u?void 0:u.description)&&void 0!==c?c:"No description"}})):"cancelled"===l.status||"expired"===l.status?(O(),x({loading:!1,success:!1})):y.current=window.setTimeout(s,2e3)}}));y.current=window.setTimeout(s,2e3)}),[t,e,O,j]),$=n.useCallback((n=>{let i=!0;const r=()=>Ge(void 0,void 0,void 0,(function*(){if(i&&(i=!1,!f.current||f.current.closed))return S.current&&console.debug("[hub] popup reads as closed on first tick, assuming COOP isolation — popup-close detection disabled"),m.current=!0,void(v.current=null);if(f.current&&!f.current.closed)return void(v.current=window.setTimeout(r,1e3));if(v.current=null,!y.current)return;if(m.current)return;const s=g.current;if(!s)return;const o=yield it(t,e,s).catch((e=>(S.current&&console.debug("[hub] final poll failed after popup closed",{attemptId:s,error:e}),null)));return y.current?"authenticated"===(null==o?void 0:o.status)&&o.account?(S.current&&console.debug("[hub] popup closed but auth completed",{attemptId:s}),O(),j({id:o.account.id,provider:n}),void parent.postMessage({type:ot.AccountConnected,account:{id:o.account.id,provider:n}},"*")):void(S.current&&console.debug("[hub] popup reported closed but attempt still pending — deferring to poll loop (likely cross-origin/COOP false-close)",{attemptId:s})):void 0}));v.current=window.setTimeout(r,1e3)}),[t,e,O,j]),H=n.useCallback((()=>Ge(void 0,void 0,void 0,(function*(){var n;if(a)if(z){x({loading:!0,success:!1});try{const r=Object.assign({},c);k&&A.forEach((e=>{if(!1!==e.secret||"password"===e.type){const t=r[e.key];ye(t)&&!d.has(e.key)&&delete r[e.key]}})),Object.keys(r).forEach((e=>{""===r[e]&&delete r[e]}));const o="oauth2"===(null==L?void 0:L.type)&&(!("grantType"in L)||"authorization_code"===L.grantType);if(S.current&&console.debug("[hub] handleConnect",{integration:a.integration_id,path:o?"oauth-redirect":"credential-form",updating:!!i}),o){const i=yield((e,t)=>Ge(void 0,void 0,void 0,(function*(){return yield Xe({url:`${e}/hub/connection_attempts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{token:t}})})))(t,e).catch((()=>null)),o=null!==(n=null==i?void 0:i.id)&&void 0!==n?n:null;if(g.current=o,!o)return S.current&&console.debug("[hub] connection attempt creation failed"),void x({loading:!1,success:!1,error:{message:"Failed to start OAuth flow",provider_response:"Could not create a connection attempt. Please try again."}});S.current&&console.debug("[hub] connection attempt created",{attemptId:o});const u=encodeURIComponent(`${s}/embedded/accounts/callback`);let c=`${t}/connect/oauth2/${a.integration_id}?redirect_uri=${u}&token=${e}&connection_attempt_id=${o}`;Object.keys(r).forEach((e=>{c+=`&${e}=${encodeURIComponent(r[e])}`}));const l=1024,d=800,h=void 0!==window.screenX?window.screenX:window.screenLeft,p=void 0!==window.screenY?window.screenY:window.screenTop,y=void 0!==window.outerWidth?window.outerWidth:document.body.clientWidth,v=void 0!==window.outerHeight?window.outerHeight:document.body.clientHeight-22,b=parseInt((h+(y-l)/2).toString(),10),C=`width=${l},height=${d},left=${b},top=${parseInt((p+(v-d)/2.5).toString(),10)},noopener=0`;return f.current=window.open(c,"Connect Account",C),f.current?(m.current=!1,"function"==typeof f.current.focus&&f.current.focus(),_(o,a.provider),void $(a.provider)):(S.current&&console.debug("[hub] popup was blocked by browser"),O(),rt(t,e,o).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:o,error:e})})),void x({loading:!1,success:!1,error:{message:"Popup blocked",provider_response:"Your browser blocked the login popup. Please allow popups for this site and try again."}}))}let u;if(i)yield nt({baseUrl:t,accountId:i,token:e,integrationId:a.integration_id,credentials:r}),u={id:i,provider:a.provider};else{const n=yield(e=>Ge(void 0,[e],void 0,(function*({baseUrl:e,token:t,credentials:n,integrationId:i}){return yield Xe({url:`${e}/hub/accounts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{integration_id:i,credentials:n}})})))({baseUrl:t,token:e,credentials:r,integrationId:a.integration_id});if(!n)throw new Error("Failed to create account");u={id:n.id,provider:a.provider}}j(u)}catch(e){let t="An unexpected error occurred",n="Please try again later";try{const i=JSON.parse(e.message);try{const e=JSON.parse(i.message);t=e.message||t,n=e.provider_response||n}catch(e){t=i.message||t,n=i.provider_response||n}}catch(n){t=e.message||t}x({loading:!1,success:!1,error:{message:t,provider_response:n}})}}else x({loading:!1,success:!1,error:{message:"Please fix the validation errors before continuing",provider_response:"Form validation failed"}})}))),[t,s,e,a,c,d,j,k,A,i,L,O,_,$,z]),K=n.useCallback((()=>{const n=g.current;S.current&&console.debug("[hub] OAuth cancelled by user",{attemptId:n}),O(),x({loading:!1,success:!1}),n&&rt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})}))}),[t,e,O]),N=q||P||F,B=!!(D||I||R);n.useEffect((()=>{h(new Set)}),[a]),n.useEffect((()=>{B&&b.loading&&x((e=>Object.assign(Object.assign({},e),{loading:!1})))}),[B,b.loading]);const V=n.useRef(b.loading);n.useEffect((()=>{o&&V.current&&!b.loading&&console.debug("[hub] connectionState.loading → false",b),V.current=b.loading}),[o,b]);const G=n.useCallback((()=>{x({loading:!1,success:!1}),h(new Set)}),[]),W=n.useCallback((()=>{x({loading:!1,success:!1}),h(new Set)}),[]);return{hubData:T,accountData:k,connectorData:E,selectedIntegration:a,fields:A,notices:M,guide:Q,formData:c,connectionState:b,isLoading:N,hasError:B,isFormValid:z,errorHubData:D,errorConnectorData:I,errorAccountData:R,setSelectedIntegration:u,setFormData:p,setIsFormValid:U,handleConnect:H,handleCancelOAuth:K,resetConnectionState:G,resetAllErrors:W,editingSecrets:d,setEditingSecrets:h}},ut=({token:i,baseUrl:r,height:s,accountId:o,onSuccess:a,onClose:u,dashboardUrl:c,showFooterLinks:l=!0,onCloseLabel:d,debug:h})=>{var p,f,g,y;const[v,m]=n.useState(null),[b,x]=n.useState(""),{hubData:C,accountData:j,connectorData:S,selectedIntegration:w,fields:O,notices:k,guide:F,connectionState:R,isLoading:T,hasError:q,isFormValid:D,errorHubData:E,errorConnectorData:P,setSelectedIntegration:I,setFormData:A,setIsFormValid:Q,handleConnect:M,handleCancelOAuth:L,resetConnectionState:z,editingSecrets:U,setEditingSecrets:_}=at({token:i,baseUrl:r,accountId:o,onSuccess:a,dashboardUrl:c,debug:h}),$=n.useCallback((e=>{Q(e)}),[Q]),H=n.useMemo((()=>{if(!C)return!1;return 1===C.integrations.filter((e=>e.active)).length}),[C]),K=()=>{I(null),z(),m(null),x("")};return e.jsxs(t.Card,{glassFooter:!0,footer:R.success?e.jsx(Ve,{onClose:u,showFooterLinks:l,onCloseLabel:d}):e.jsx(Be,{selectedIntegration:w,showActions:!R.loading&&!R.success,onBack:j||H?void 0:K,onNext:M,isFormValid:D,isLoading:T,showFooterLinks:l}),title:T||R.loading||R.success?null:e.jsx(Ne,{accountData:j,onBack:K,guide:F,isLoading:T,hasError:q,hubData:C,selectedCategory:v,onCategoryChange:m,onSearchChange:x,hideBackButton:R.loading||R.success||H,connectorData:null!==(p=null==S?void 0:S.config)&&void 0!==p?p:null}),height:s,padding:"0",headerConfig:w?void 0:{padding:"0"},children:[R.timedOut&&e.jsx(t.Alert,{type:"warning",message:"Connection timed out. Please try again.",hasMargin:!0}),e.jsx(He,{isLoading:T,hasError:q,connectionState:R,selectedIntegration:w,connectorData:null!==(f=null==S?void 0:S.config)&&void 0!==f?f:null,hubData:null!=C?C:null,fields:O,notices:k,errorHubData:null!==(g=E)&&void 0!==g?g:null,errorConnectorData:null!==(y=P)&&void 0!==y?y:null,onSelect:I,onChange:A,onValidationChange:$,onCancelOAuth:L,selectedCategory:v,search:b,editingSecrets:U,setEditingSecrets:_})]})},ct=n.createContext({featureFlags:[]}),lt=({featureFlags:t,children:i})=>{const r=n.useMemo((()=>({featureFlags:t})),[t]);return e.jsx(ct.Provider,{value:r,children:i})},dt=n.memo((({mode:t,token:n,apiUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,accountId:u,showFooterLinks:c,onCloseLabel:l,debug:d})=>{var h;const{data:p}=ue({queryKey:["settings"],queryFn:()=>((e,t)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/settings`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(i,n)});return e.jsx(lt,{featureFlags:null!==(h=null==p?void 0:p.enabled_features)&&void 0!==h?h:[],children:"integration-picker"===t&&e.jsx(ut,{token:n,baseUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,onCloseLabel:l,accountId:null!=u?u:null==p?void 0:p.existing_account_id,showFooterLinks:c,debug:d})})})),ht=()=>e.jsxs(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:[e.jsx(t.CustomIcons.RejectIcon,{style:{color:"red"}}),e.jsx(t.Typography.Text,{fontWeight:"bold",size:"large",children:"Error"}),e.jsx(t.Typography.SecondaryText,{children:"Something went wrong, our team has been notified."})]});class pt extends n.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?this.props.fallback:this.props.children}}exports.StackOneHub=({mode:i,token:r,baseUrl:s,appUrl:o,height:a="500px",theme:u="light",accountId:c,onSuccess:l,onClose:d,onCloseLabel:h,showFooterLinks:p,debug:f})=>{const g=null!=s?s:"https://api.stackone.com",y=null!=o?o:"https://app.stackone.com";n.useEffect((()=>{"dark"===u?t.applyDarkTheme():"light"===u?t.applyLightTheme():t.applyTheme(u)}),[u]);const[v]=n.useState((()=>new J({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,retryDelay:500,refetchOnMount:!1,retryOnMount:!1}}}))),m=n.useRef(r);return n.useEffect((()=>{m.current!==r&&(m.current=r,v.clear())}),[r,v]),r?e.jsx(t.MalachiteContext,{children:e.jsx(pt,{fallback:e.jsx(t.Card,{height:a,children:e.jsx(ht,{})}),children:e.jsx(ie,{client:v,children:e.jsx(dt,{mode:null!=i?i:"integration-picker",token:r,apiUrl:g,dashboardUrl:y,height:a,onSuccess:l,accountId:c,onClose:d,onCloseLabel:h,showFooterLinks:p,debug:f})})})}):e.jsx(t.MalachiteContext,{children:e.jsx(pt,{fallback:e.jsx(t.Card,{height:a,children:e.jsx(ht,{})}),children:e.jsx(t.Card,{height:a,footer:e.jsx(t.FooterLinks,{}),children:e.jsx(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,fullHeight:!0,children:e.jsx(t.Typography.PageTitle,{children:"No token provided"})})})})})};
|
|
1
|
+
"use client";"use strict";var e=require("react/jsx-runtime"),t=require("@stackone/malachite"),n=require("react"),i=require("@hookform/resolvers/zod"),r=require("react-hook-form"),s=require("zod");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var a=o(n),u=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},c="undefined"==typeof window||"Deno"in globalThis;function l(){}function d(e){return"number"==typeof e&&e>=0&&e!==1/0}function h(e,t){return Math.max(e+(t||0)-Date.now(),0)}function p(e,t){return"function"==typeof e?e(t):e}function f(e,t){return"function"==typeof e?e(t):e}function g(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:s,queryKey:o,stale:a}=e;if(o)if(i){if(t.queryHash!==v(o,t.options))return!1}else if(!b(t.queryKey,o))return!1;if("all"!==n){const e=t.isActive();if("active"===n&&!e)return!1;if("inactive"===n&&e)return!1}return("boolean"!=typeof a||t.isStale()===a)&&((!r||r===t.state.fetchStatus)&&!(s&&!s(t)))}function y(e,t){const{exact:n,status:i,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(m(t.options.mutationKey)!==m(s))return!1}else if(!b(t.options.mutationKey,s))return!1}return(!i||t.state.status===i)&&!(r&&!r(t))}function v(e,t){return(t?.queryKeyHashFn||m)(e)}function m(e){return JSON.stringify(e,((e,t)=>S(t)?Object.keys(t).sort().reduce(((e,n)=>(e[n]=t[n],e)),{}):t))}function b(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&Object.keys(t).every((n=>b(e[n],t[n]))))}function x(e,t){if(e===t)return e;const n=j(e)&&j(t);if(n||S(e)&&S(t)){const i=n?e:Object.keys(e),r=i.length,s=n?t:Object.keys(t),o=s.length,a=n?[]:{};let u=0;for(let r=0;r<o;r++){const o=n?r:s[r];(!n&&i.includes(o)||n)&&void 0===e[o]&&void 0===t[o]?(a[o]=void 0,u++):(a[o]=x(e[o],t[o]),a[o]===e[o]&&void 0!==e[o]&&u++)}return r===o&&u===r?e:a}return t}function C(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function j(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function S(e){if(!w(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!!w(n)&&(!!n.hasOwnProperty("isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)}function w(e){return"[object Object]"===Object.prototype.toString.call(e)}function O(e,t,n){return"function"==typeof n.structuralSharing?n.structuralSharing(e,t):!1!==n.structuralSharing?x(e,t):t}function k(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function F(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var R=Symbol();function T(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:e.queryFn&&e.queryFn!==R?e.queryFn:()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`))}var q=new class extends u{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!c&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e((e=>{"boolean"==typeof e?this.setFocused(e):this.onFocus()}))}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach((t=>{t(e)}))}isFocused(){return"boolean"==typeof this.#e?this.#e:"hidden"!==globalThis.document?.visibilityState}},D=new class extends u{#i=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!c&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#i!==e&&(this.#i=e,this.listeners.forEach((t=>{t(e)})))}isOnline(){return this.#i}};function E(){let e,t;const n=new Promise(((n,i)=>{e=n,t=i}));function i(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.status="pending",n.catch((()=>{})),n.resolve=t=>{i({status:"fulfilled",value:t}),e(t)},n.reject=e=>{i({status:"rejected",reason:e}),t(e)},n}function P(e){return Math.min(1e3*2**e,3e4)}function I(e){return"online"!==(e??"online")||D.isOnline()}var A=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Q(e){return e instanceof A}function M(e){let t,n=!1,i=0,r=!1;const s=E(),o=()=>q.isFocused()&&("always"===e.networkMode||D.isOnline())&&e.canRun(),a=()=>I(e.networkMode)&&e.canRun(),u=n=>{r||(r=!0,e.onSuccess?.(n),t?.(),s.resolve(n))},l=n=>{r||(r=!0,e.onError?.(n),t?.(),s.reject(n))},d=()=>new Promise((n=>{t=e=>{(r||o())&&n(e)},e.onPause?.()})).then((()=>{t=void 0,r||e.onContinue?.()})),h=()=>{if(r)return;let t;const s=0===i?e.initialPromise:void 0;try{t=s??e.fn()}catch(e){t=Promise.reject(e)}Promise.resolve(t).then(u).catch((t=>{if(r)return;const s=e.retry??(c?0:3),a=e.retryDelay??P,u="function"==typeof a?a(i,t):a,p=!0===s||"number"==typeof s&&i<s||"function"==typeof s&&s(i,t);var f;!n&&p?(i++,e.onFail?.(i,t),(f=u,new Promise((e=>{setTimeout(e,f)}))).then((()=>o()?void 0:d())).then((()=>{n?l(t):h()}))):l(t)}))};return{promise:s,cancel:t=>{r||(l(new A(t)),e.abort?.())},continue:()=>(t?.(),s),cancelRetry:()=>{n=!0},continueRetry:()=>{n=!1},canStart:a,start:()=>(a()?h():d().then(h),s)}}var L=e=>setTimeout(e,0);var z=function(){let e=[],t=0,n=e=>{e()},i=e=>{e()},r=L;const s=i=>{t?e.push(i):r((()=>{n(i)}))};return{batch:s=>{let o;t++;try{o=s()}finally{t--,t||(()=>{const t=e;e=[],t.length&&r((()=>{i((()=>{t.forEach((e=>{n(e)}))}))}))})()}return o},batchCalls:e=>(...t)=>{s((()=>{e(...t)}))},schedule:s,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{i=e},setScheduler:e=>{r=e}}}(),U=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),d(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(c?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}},_=class extends U{#s;#o;#a;#u;#c;#l;#d;constructor(e){super(),this.#d=!1,this.#l=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#u=e.client,this.#a=this.#u.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#s=function(e){const t="function"==typeof e.initialData?e.initialData():e.initialData,n=void 0!==t,i=n?"function"==typeof e.initialDataUpdatedAt?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}(this.options),this.state=e.state??this.#s,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#c?.promise}setOptions(e){this.options={...this.#l,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){this.observers.length||"idle"!==this.state.fetchStatus||this.#a.remove(this)}setData(e,t){const n=O(this.state.data,e,this.options);return this.#h({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#h({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#c?.promise;return this.#c?.cancel(e),t?t.then(l).catch(l):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#s)}isActive(){return this.observers.some((e=>!1!==f(e.options.enabled,this)))}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===R||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return!!this.state.isInvalidated||(this.getObserversCount()>0?this.observers.some((e=>e.getCurrentResult().isStale)):void 0===this.state.data)}isStaleByTime(e=0){return this.state.isInvalidated||void 0===this.state.data||!h(this.state.dataUpdatedAt,e)}onFocus(){const e=this.observers.find((e=>e.shouldFetchOnWindowFocus()));e?.refetch({cancelRefetch:!1}),this.#c?.continue()}onOnline(){const e=this.observers.find((e=>e.shouldFetchOnReconnect()));e?.refetch({cancelRefetch:!1}),this.#c?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter((t=>t!==e)),this.observers.length||(this.#c&&(this.#d?this.#c.cancel({revert:!0}):this.#c.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#h({type:"invalidate"})}fetch(e,t){if("idle"!==this.state.fetchStatus)if(void 0!==this.state.data&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#c)return this.#c.continueRetry(),this.#c.promise;if(e&&this.setOptions(e),!this.options.queryFn){const e=this.observers.find((e=>e.options.queryFn));e&&this.setOptions(e.options)}const n=new AbortController,i=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#d=!0,n.signal)})},r={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#u,state:this.state,fetchFn:()=>{const e=T(this.options,t),n={client:this.#u,queryKey:this.queryKey,meta:this.meta};return i(n),this.#d=!1,this.options.persister?this.options.persister(e,n,this):e(n)}};i(r),this.options.behavior?.onFetch(r,this),this.#o=this.state,"idle"!==this.state.fetchStatus&&this.state.fetchMeta===r.fetchOptions?.meta||this.#h({type:"fetch",meta:r.fetchOptions?.meta});const s=e=>{Q(e)&&e.silent||this.#h({type:"error",error:e}),Q(e)||(this.#a.config.onError?.(e,this),this.#a.config.onSettled?.(this.state.data,e,this)),this.scheduleGc()};return this.#c=M({initialPromise:t?.initialPromise,fn:r.fetchFn,abort:n.abort.bind(n),onSuccess:e=>{if(void 0!==e){try{this.setData(e)}catch(e){return void s(e)}this.#a.config.onSuccess?.(e,this),this.#a.config.onSettled?.(e,this.state.error,this),this.scheduleGc()}else s(new Error(`${this.queryHash} data is undefined`))},onError:s,onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:()=>{this.#h({type:"continue"})},retry:r.options.retry,retryDelay:r.options.retryDelay,networkMode:r.options.networkMode,canRun:()=>!0}),this.#c.start()}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...t,fetchStatus:"paused"};case"continue":return{...t,fetchStatus:"fetching"};case"fetch":return{...t,...$(t.data,this.options),fetchMeta:e.meta??null};case"success":return{...t,data:e.data,dataUpdateCount:t.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const n=e.error;return Q(n)&&n.revert&&this.#o?{...this.#o,fetchStatus:"idle"}:{...t,error:n,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...t,isInvalidated:!0};case"setState":return{...t,...e.state}}})(this.state),z.batch((()=>{this.observers.forEach((e=>{e.onQueryUpdate()})),this.#a.notify({query:this,type:"updated",action:e})}))}};function $(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:I(t.networkMode)?"fetching":"paused",...void 0===e&&{error:null,status:"pending"}}}var H=class extends u{constructor(e={}){super(),this.config=e,this.#p=new Map}#p;build(e,t,n){const i=t.queryKey,r=t.queryHash??v(i,t);let s=this.get(r);return s||(s=new _({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(s)),s}add(e){this.#p.has(e.queryHash)||(this.#p.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#p.get(e.queryHash);t&&(e.destroy(),t===e&&this.#p.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){z.batch((()=>{this.getAll().forEach((e=>{this.remove(e)}))}))}get(e){return this.#p.get(e)}getAll(){return[...this.#p.values()]}find(e){const t={exact:!0,...e};return this.getAll().find((e=>g(t,e)))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter((t=>g(e,t))):t}notify(e){z.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}onFocus(){z.batch((()=>{this.getAll().forEach((e=>{e.onFocus()}))}))}onOnline(){z.batch((()=>{this.getAll().forEach((e=>{e.onOnline()}))}))}},K=class extends U{#f;#g;#c;constructor(e){super(),this.mutationId=e.mutationId,this.#g=e.mutationCache,this.#f=[],this.state=e.state||{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0},this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#f.includes(e)||(this.#f.push(e),this.clearGcTimeout(),this.#g.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#f=this.#f.filter((t=>t!==e)),this.scheduleGc(),this.#g.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#f.length||("pending"===this.state.status?this.scheduleGc():this.#g.remove(this))}continue(){return this.#c?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#h({type:"continue"})};this.#c=M({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#g.canRun(this)});const n="pending"===this.state.status,i=!this.#c.canStart();try{if(n)t();else{this.#h({type:"pending",variables:e,isPaused:i}),await(this.#g.config.onMutate?.(e,this));const t=await(this.options.onMutate?.(e));t!==this.state.context&&this.#h({type:"pending",context:t,variables:e,isPaused:i})}const r=await this.#c.start();return await(this.#g.config.onSuccess?.(r,e,this.state.context,this)),await(this.options.onSuccess?.(r,e,this.state.context)),await(this.#g.config.onSettled?.(r,null,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(r,null,e,this.state.context)),this.#h({type:"success",data:r}),r}catch(t){try{throw await(this.#g.config.onError?.(t,e,this.state.context,this)),await(this.options.onError?.(t,e,this.state.context)),await(this.#g.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(void 0,t,e,this.state.context)),t}finally{this.#h({type:"error",error:t})}}finally{this.#g.runNext(this)}}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...t,isPaused:!0};case"continue":return{...t,isPaused:!1};case"pending":return{...t,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{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}})(this.state),z.batch((()=>{this.#f.forEach((t=>{t.onMutationUpdate(e)})),this.#g.notify({mutation:this,type:"updated",action:e})}))}};var N=class extends u{constructor(e={}){super(),this.config=e,this.#y=new Set,this.#v=new Map,this.#m=0}#y;#v;#m;build(e,t,n){const i=new K({mutationCache:this,mutationId:++this.#m,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#y.add(e);const t=B(e);if("string"==typeof t){const n=this.#v.get(t);n?n.push(e):this.#v.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#y.delete(e)){const t=B(e);if("string"==typeof t){const n=this.#v.get(t);if(n)if(n.length>1){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}else n[0]===e&&this.#v.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=B(e);if("string"==typeof t){const n=this.#v.get(t),i=n?.find((e=>"pending"===e.state.status));return!i||i===e}return!0}runNext(e){const t=B(e);if("string"==typeof t){const n=this.#v.get(t)?.find((t=>t!==e&&t.state.isPaused));return n?.continue()??Promise.resolve()}return Promise.resolve()}clear(){z.batch((()=>{this.#y.forEach((e=>{this.notify({type:"removed",mutation:e})})),this.#y.clear(),this.#v.clear()}))}getAll(){return Array.from(this.#y)}find(e){const t={exact:!0,...e};return this.getAll().find((e=>y(t,e)))}findAll(e={}){return this.getAll().filter((t=>y(e,t)))}notify(e){z.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}resumePausedMutations(){const e=this.getAll().filter((e=>e.state.isPaused));return z.batch((()=>Promise.all(e.map((e=>e.continue().catch(l))))))}};function B(e){return e.options.scope?.id}function V(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},u=0;const c=async()=>{let n=!1;const c=T(t.options,t.fetchOptions),l=async(e,i,r)=>{if(n)return Promise.reject();if(null==i&&e.pages.length)return Promise.resolve(e);const s={client:t.client,queryKey:t.queryKey,pageParam:i,direction:r?"backward":"forward",meta:t.options.meta};var o;o=s,Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(t.signal.aborted?n=!0:t.signal.addEventListener("abort",(()=>{n=!0})),t.signal)});const a=await c(s),{maxPages:u}=t.options,l=r?F:k;return{pages:l(e.pages,a,u),pageParams:l(e.pageParams,i,u)}};if(r&&s.length){const e="backward"===r,t={pages:s,pageParams:o},n=(e?W:G)(i,t);a=await l(t,n,e)}else{const t=e??s.length;do{const e=0===u?o[0]??i.initialPageParam:G(i,a);if(u>0&&null==e)break;a=await l(a,e),u++}while(u<t)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(c,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=c}}}function G(e,{pages:t,pageParams:n}){const i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,n[i],n):void 0}function W(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var J=class{#b;#g;#l;#x;#C;#j;#S;#w;constructor(e={}){this.#b=e.queryCache||new H,this.#g=e.mutationCache||new N,this.#l=e.defaultOptions||{},this.#x=new Map,this.#C=new Map,this.#j=0}mount(){this.#j++,1===this.#j&&(this.#S=q.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onFocus())})),this.#w=D.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onOnline())})))}unmount(){this.#j--,0===this.#j&&(this.#S?.(),this.#S=void 0,this.#w?.(),this.#w=void 0)}isFetching(e){return this.#b.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#g.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#b.build(this,t),i=n.state.data;return void 0===i?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(p(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(i))}getQueriesData(e){return this.#b.findAll(e).map((({queryKey:e,state:t})=>[e,t.data]))}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),r=this.#b.get(i.queryHash),s=r?.state.data,o=function(e,t){return"function"==typeof e?e(t):e}(t,s);if(void 0!==o)return this.#b.build(this,i).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return z.batch((()=>this.#b.findAll(e).map((({queryKey:e})=>[e,this.setQueryData(e,t,n)]))))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state}removeQueries(e){const t=this.#b;z.batch((()=>{t.findAll(e).forEach((e=>{t.remove(e)}))}))}resetQueries(e,t){const n=this.#b;return z.batch((()=>(n.findAll(e).forEach((e=>{e.reset()})),this.refetchQueries({type:"active",...e},t))))}cancelQueries(e,t={}){const n={revert:!0,...t},i=z.batch((()=>this.#b.findAll(e).map((e=>e.cancel(n)))));return Promise.all(i).then(l).catch(l)}invalidateQueries(e,t={}){return z.batch((()=>(this.#b.findAll(e).forEach((e=>{e.invalidate()})),"none"===e?.refetchType?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t))))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},i=z.batch((()=>this.#b.findAll(e).filter((e=>!e.isDisabled())).map((e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(l)),"paused"===e.state.fetchStatus?Promise.resolve():t}))));return Promise.all(i).then(l)}fetchQuery(e){const t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);const n=this.#b.build(this,t);return n.isStaleByTime(p(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(l).catch(l)}fetchInfiniteQuery(e){return e.behavior=V(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(l).catch(l)}ensureInfiniteQueryData(e){return e.behavior=V(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return D.isOnline()?this.#g.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#b}getMutationCache(){return this.#g}getDefaultOptions(){return this.#l}setDefaultOptions(e){this.#l=e}setQueryDefaults(e,t){this.#x.set(m(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#x.values()],n={};return t.forEach((t=>{b(e,t.queryKey)&&Object.assign(n,t.defaultOptions)})),n}setMutationDefaults(e,t){this.#C.set(m(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#C.values()],n={};return t.forEach((t=>{b(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)})),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#l.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=v(t.queryKey,t)),void 0===t.refetchOnReconnect&&(t.refetchOnReconnect="always"!==t.networkMode),void 0===t.throwOnError&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===R&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#l.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#b.clear(),this.#g.clear()}},Y=class extends u{constructor(e,t){super(),this.options=t,this.#u=e,this.#O=null,this.#k=E(),this.options.experimental_prefetchInRender||this.#k.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#u;#F=void 0;#R=void 0;#T=void 0;#q;#D;#k;#O;#E;#P;#I;#A;#Q;#M;#L=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#F.addObserver(this),X(this.#F,this.options)?this.#z():this.updateResult(),this.#U())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Z(this.#F,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Z(this.#F,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#$(),this.#F.removeObserver(this)}setOptions(e){const t=this.options,n=this.#F;if(this.options=this.#u.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof f(this.options.enabled,this.#F))throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#H(),this.#F.setOptions(this.options),t._defaulted&&!C(this.options,t)&&this.#u.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#F,observer:this});const i=this.hasListeners();i&&ee(this.#F,n,this.options,t)&&this.#z(),this.updateResult(),!i||this.#F===n&&f(this.options.enabled,this.#F)===f(t.enabled,this.#F)&&p(this.options.staleTime,this.#F)===p(t.staleTime,this.#F)||this.#K();const r=this.#N();!i||this.#F===n&&f(this.options.enabled,this.#F)===f(t.enabled,this.#F)&&r===this.#M||this.#B(r)}getOptimisticResult(e){const t=this.#u.getQueryCache().build(this.#u,e),n=this.createResult(t,e);return function(e,t){if(!C(e.getCurrentResult(),t))return!0;return!1}(this,n)&&(this.#T=n,this.#D=this.options,this.#q=this.#F.state),n}getCurrentResult(){return this.#T}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#L.add(e)}getCurrentQuery(){return this.#F}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#u.defaultQueryOptions(e),n=this.#u.getQueryCache().build(this.#u,t);return n.fetch().then((()=>this.createResult(n,t)))}fetch(e){return this.#z({...e,cancelRefetch:e.cancelRefetch??!0}).then((()=>(this.updateResult(),this.#T)))}#z(e){this.#H();let t=this.#F.fetch(this.options,e);return e?.throwOnError||(t=t.catch(l)),t}#K(){this.#_();const e=p(this.options.staleTime,this.#F);if(c||this.#T.isStale||!d(e))return;const t=h(this.#T.dataUpdatedAt,e)+1;this.#A=setTimeout((()=>{this.#T.isStale||this.updateResult()}),t)}#N(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#F):this.options.refetchInterval)??!1}#B(e){this.#$(),this.#M=e,!c&&!1!==f(this.options.enabled,this.#F)&&d(this.#M)&&0!==this.#M&&(this.#Q=setInterval((()=>{(this.options.refetchIntervalInBackground||q.isFocused())&&this.#z()}),this.#M))}#U(){this.#K(),this.#B(this.#N())}#_(){this.#A&&(clearTimeout(this.#A),this.#A=void 0)}#$(){this.#Q&&(clearInterval(this.#Q),this.#Q=void 0)}createResult(e,t){const n=this.#F,i=this.options,r=this.#T,s=this.#q,o=this.#D,a=e!==n?e.state:this.#R,{state:u}=e;let c,l={...u},d=!1;if(t._optimisticResults){const r=this.hasListeners(),s=!r&&X(e,t),o=r&&ee(e,n,t,i);(s||o)&&(l={...l,...$(u.data,e.options)}),"isRestoring"===t._optimisticResults&&(l.fetchStatus="idle")}let{error:h,errorUpdatedAt:p,status:f}=l;c=l.data;let g=!1;if(void 0!==t.placeholderData&&void 0===c&&"pending"===f){let e;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=r.data,g=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#I?.state.data,this.#I):t.placeholderData,void 0!==e&&(f="success",c=O(r?.data,e,t),d=!0)}if(t.select&&void 0!==c&&!g)if(r&&c===s?.data&&t.select===this.#E)c=this.#P;else try{this.#E=t.select,c=t.select(c),c=O(r?.data,c,t),this.#P=c,this.#O=null}catch(e){this.#O=e}this.#O&&(h=this.#O,c=this.#P,p=Date.now(),f="error");const y="fetching"===l.fetchStatus,v="pending"===f,m="error"===f,b=v&&y,x=void 0!==c,C={status:f,fetchStatus:l.fetchStatus,isPending:v,isSuccess:"success"===f,isError:m,isInitialLoading:b,isLoading:b,data:c,dataUpdatedAt:l.dataUpdatedAt,error:h,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>a.dataUpdateCount||l.errorUpdateCount>a.errorUpdateCount,isFetching:y,isRefetching:y&&!v,isLoadingError:m&&!x,isPaused:"paused"===l.fetchStatus,isPlaceholderData:d,isRefetchError:m&&x,isStale:te(e,t),refetch:this.refetch,promise:this.#k};if(this.options.experimental_prefetchInRender){const t=e=>{"error"===C.status?e.reject(C.error):void 0!==C.data&&e.resolve(C.data)},i=()=>{const e=this.#k=C.promise=E();t(e)},r=this.#k;switch(r.status){case"pending":e.queryHash===n.queryHash&&t(r);break;case"fulfilled":"error"!==C.status&&C.data===r.value||i();break;case"rejected":"error"===C.status&&C.error===r.reason||i()}}return C}updateResult(){const e=this.#T,t=this.createResult(this.#F,this.options);if(this.#q=this.#F.state,this.#D=this.options,void 0!==this.#q.data&&(this.#I=this.#F),C(t,e))return;this.#T=t;this.#V({listeners:(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options,n="function"==typeof t?t():t;if("all"===n||!n&&!this.#L.size)return!0;const i=new Set(n??this.#L);return this.options.throwOnError&&i.add("error"),Object.keys(this.#T).some((t=>{const n=t;return this.#T[n]!==e[n]&&i.has(n)}))})()})}#H(){const e=this.#u.getQueryCache().build(this.#u,this.options);if(e===this.#F)return;const t=this.#F;this.#F=e,this.#R=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#U()}#V(e){z.batch((()=>{e.listeners&&this.listeners.forEach((e=>{e(this.#T)})),this.#u.getQueryCache().notify({query:this.#F,type:"observerResultsUpdated"})}))}};function X(e,t){return function(e,t){return!1!==f(t.enabled,e)&&void 0===e.state.data&&!("error"===e.state.status&&!1===t.retryOnMount)}(e,t)||void 0!==e.state.data&&Z(e,t,t.refetchOnMount)}function Z(e,t,n){if(!1!==f(t.enabled,e)){const i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&te(e,t)}return!1}function ee(e,t,n,i){return(e!==t||!1===f(i.enabled,e))&&(!n.suspense||"error"!==e.state.status)&&te(e,n)}function te(e,t){return!1!==f(t.enabled,e)&&e.isStaleByTime(p(t.staleTime,e))}var ne=a.createContext(void 0),ie=({client:t,children:n})=>(a.useEffect((()=>(t.mount(),()=>{t.unmount()})),[t]),e.jsx(ne.Provider,{value:t,children:n})),re=a.createContext(!1);re.Provider;var se=a.createContext(function(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}()),oe=(e,t,n)=>t.fetchOptimistic(e).catch((()=>{n.clearReset()}));function ae(e,t,n){const i=(()=>{const e=a.useContext(ne);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e})(),r=a.useContext(re),s=a.useContext(se),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=r?"isRestoring":"optimistic",(e=>{const t=e.staleTime;e.suspense&&(e.staleTime="function"==typeof t?(...e)=>Math.max(t(...e),1e3):Math.max(t??1e3,1e3),"number"==typeof e.gcTime&&(e.gcTime=Math.max(e.gcTime,1e3)))})(o),((e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))})(o,s),(e=>{a.useEffect((()=>{e.clearReset()}),[e])})(s);const u=!i.getQueryCache().get(o.queryHash),[d]=a.useState((()=>new t(i,o))),h=d.getOptimisticResult(o),p=!r&&!1!==e.subscribed;if(a.useSyncExternalStore(a.useCallback((e=>{const t=p?d.subscribe(z.batchCalls(e)):l;return d.updateResult(),t}),[d,p]),(()=>d.getCurrentResult()),(()=>d.getCurrentResult())),a.useEffect((()=>{d.setOptions(o)}),[o,d]),((e,t)=>e?.suspense&&t.isPending)(o,h))throw oe(o,d,s);if((({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&void 0===e.data||function(e,t){return"function"==typeof e?e(...t):!!e}(n,[e.error,i])))({result:h,errorResetBoundary:s,throwOnError:o.throwOnError,query:i.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw h.error;if(i.getDefaultOptions().queries?._experimental_afterQuery?.(o,h),o.experimental_prefetchInRender&&!c&&((e,t)=>e.isLoading&&e.isFetching&&!t)(h,r)){const e=u?oe(o,d,s):i.getQueryCache().get(o.queryHash)?.promise;e?.catch(l).finally((()=>{d.updateResult()}))}return o.notifyOnChangeProps?h:d.trackResult(h)}function ue(e,t){return ae(e,Y)}const ce=({message:n})=>e.jsx(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:e.jsx(t.Typography.Text,{size:"medium",fontWeight:"semi-bold",children:n})});var le=Object.prototype.hasOwnProperty;function de(e,t,n){for(n of e.keys())if(he(n,t))return n}function he(e,t){var n,i,r;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((i=e.length)===t.length)for(;i--&&he(e[i],t[i]););return-1===i}if(n===Set){if(e.size!==t.size)return!1;for(i of e){if((r=i)&&"object"==typeof r&&!(r=de(t,r)))return!1;if(!t.has(r))return!1}return!0}if(n===Map){if(e.size!==t.size)return!1;for(i of e){if((r=i[0])&&"object"==typeof r&&!(r=de(t,r)))return!1;if(!he(i[1],t.get(r)))return!1}return!0}if(n===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(n===DataView){if((i=e.byteLength)===t.byteLength)for(;i--&&e.getInt8(i)===t.getInt8(i););return-1===i}if(ArrayBuffer.isView(e)){if((i=e.byteLength)===t.byteLength)for(;i--&&e[i]===t[i];);return-1===i}if(!n||"object"==typeof e){for(n in i=0,e){if(le.call(e,n)&&++i&&!le.call(t,n))return!1;if(!(n in t)||!he(e[n],t[n]))return!1}return Object.keys(t).length===i}}return e!=e&&t!=t}function pe(e,t){return a.useEffect(e,(n=t,i=a.useRef(n),r=a.useRef(0),he(n,i.current)||(i.current=n,r.current+=1),a.useMemo((function(){return i.current}),[r.current])));var n,i,r}function fe(e){return"anchor"in e&&"string"==typeof e.anchor&&e.anchor.trim().length>0}const ge=/^__secretvalue:\*\*redacted\*\*(.*)$/,ye=e=>(e=>"string"==typeof e)(e)&&ge.test(e),ve=e=>{const t="••••••••••";if(!ye(e))return e;const n=e.match(ge);if(!n)return t;const i=n[1];return i?t+i:t},me={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/};function be(e){return void 0!==e.type}function xe(e){if((e=>{const t=[];let n=!1;const i=/\{(\d+)(?:(,)(\d*))?\}/y,r=t=>{const n=e[t];if("*"===n||"+"===n)return{length:1,variable:!0,amplifying:!0};if("?"===n)return{length:1,variable:!0,amplifying:!1};if("{"===n){i.lastIndex=t;const n=i.exec(e);if(n){const e=Number(n[1]),t=void 0===n[2]?e:n[3]?Number(n[3]):1/0;return{length:n[0].length,variable:t>e,amplifying:t>=2}}}};for(let i=0;i<e.length;i++){const s=e[i];if("\\"===s){i++;continue}if(n){"]"===s&&(n=!1);continue}if("["===s){n=!0;continue}if("|"===s){t.length>0&&(t[t.length-1].hasAlternation=!0);continue}if("("===s){t.push({hasVariable:!1,hasAlternation:!1}),"?"===e[i+1]&&(i+="<"!==e[i+2]||"="!==e[i+3]&&"!"!==e[i+3]?1:2);continue}if(")"===s){const e=t.pop(),n=r(i+1);if(n){if(n.amplifying&&((null==e?void 0:e.hasVariable)||(null==e?void 0:e.hasAlternation)))return!0;i+=n.length}t.length>0&&(((null==n?void 0:n.variable)||(null==e?void 0:e.hasVariable))&&(t[t.length-1].hasVariable=!0),(null==e?void 0:e.hasAlternation)&&(t[t.length-1].hasAlternation=!0));continue}const o=r(i);o&&(o.variable&&t.length>0&&(t[t.length-1].hasVariable=!0),i+=o.length-1)}return!1})(e))return console.warn(`[stackone-hub] pattern "${e}" risks catastrophic backtracking — field validation skipped`),null;try{return new RegExp(e)}catch(t){return console.warn(`[stackone-hub] pattern "${e}" failed to compile — field validation skipped`),null}}function Ce(e){return e.validation?be(e.validation)?function(e){if("html-pattern"===e.type){const t=xe(e.pattern);return t?{pattern:t,errorMessage:e.error||`Please match the required format: ${e.pattern}`}:null}if("domain"===e.type){const t=xe(`.*${e.pattern}\\.com.*`);return t?{pattern:t,errorMessage:e.error||`Please enter a valid ${e.pattern}.com domain`}:null}return null}(e.validation):function(e,t){if(e.format){const t=Object.prototype.hasOwnProperty.call(me,e.format)?me[e.format]:void 0;return t?{pattern:t,errorMessage:e.errorMessage||`Must be a valid ${e.format}`}:(console.warn(`[stackone-hub] no pattern for format "${e.format}" — field validation skipped; hub FORMAT_PATTERNS has drifted from @stackone/core`),null)}if(e.pattern){const n=xe(e.pattern);return n?{pattern:n,errorMessage:e.errorMessage||`${t} format is invalid`}:null}return null}(e.validation,e.label):null}function je(e){const t=new Map;for(const n of e){if("number"===n.type&&!n.required)continue;const e=Ce(n);e&&t.set(n.key,e)}return t}function Se(e,t){return!(!e||"string"!=typeof t||""===t||ye(t))&&!e.pattern.test(t)}function we(e,t){let n=s.z.string();e.required&&(n=n.min(1,`${e.label} is required`));const i=t=>n=>""===n?!e.required:t(n);return"number"===e.type&&(n=n.refine(i((e=>ye(e)||/^\d+$/.test(e))),"Must be a valid number")),t&&(n=n.refine(i((e=>!Se(t,e))),t.errorMessage)),n}const Oe=({field:n,errors:i,setValue:r,onLeave:s,editingSecrets:o,setEditingSecrets:a})=>{var u,c,l,d,h,p,f,g,y,v,m,b,x,C,j,S,w,O,k,F,R,T,q;const D="object"==typeof n.key?JSON.stringify(n.key):String(n.key),E=i[D]&&e.jsx(t.Typography.Text,{color:"error",style:{marginTop:"4px",fontSize:"12px"},children:null===(u=i[D])||void 0===u?void 0:u.message});if("text"===(P=n.type)||"number"===P||"password"===P){const u=n.readOnly,b=null===(c=n.value)||void 0===c?void 0:c.toString(),x="external-trigger-token"!==n.key&&(!1!==n.secret||"password"===n.type),C=u&&b&&!x,j=null!==(l=null==o?void 0:o.has(D))&&void 0!==l&&l;if(x&&ye(b)&&!j)return e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{name:`${D}-display`,label:n.label,placeholder:n.placeholder,type:"text",required:n.required,disabled:!0,readOnly:!0,defaultValue:b?ve(b):"",description:null!==(h=null===(d=n.guide)||void 0===d?void 0:d.description)&&void 0!==h?h:n.description,tooltip:null!==(f=null===(p=n.guide)||void 0===p?void 0:p.tooltip)&&void 0!==f?f:n.tooltip,showCopyButton:!1,buttons:a?[{label:"Edit",variant:"filled",size:"xsmall",onClick:()=>{a((e=>new Set(e).add(D))),r(D,"",{shouldValidate:!0,shouldDirty:!0})}}]:void 0}),E]});const S=!x&&(n.readOnly||!1),w=x?void 0:C?()=>{}:void 0;return e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{name:D,required:!!u||n.required,placeholder:n.placeholder,disabled:S,readOnly:n.readOnly,label:n.label,tooltip:null!==(y=null===(g=n.guide)||void 0===g?void 0:g.tooltip)&&void 0!==y?y:n.tooltip,description:null!==(m=null===(v=n.guide)||void 0===v?void 0:v.description)&&void 0!==m?m:n.description,type:n.type,error:!!i[D],onChange:e=>r(D,e,{shouldValidate:!0}),onBlur:s,defaultValue:x&&j?"":b,showPasswordToggle:!1,onCopyClick:w},`${D}-${j?"editing":"view"}`),E]})}var P;return"text_area"===n.type?e.jsxs(e.Fragment,{children:[e.jsx(t.TextArea,{name:D,required:n.required,placeholder:n.placeholder,disabled:n.readOnly,label:n.label,tooltip:null!==(x=null===(b=n.guide)||void 0===b?void 0:b.tooltip)&&void 0!==x?x:n.tooltip,description:null!==(j=null===(C=n.guide)||void 0===C?void 0:C.description)&&void 0!==j?j:n.description,error:!!i[D],onChange:e=>r(D,e,{shouldValidate:!0}),onBlur:s,defaultValue:(null===(S=n.value)||void 0===S?void 0:S.toString())||""}),E]}):"select"===n.type?e.jsxs(e.Fragment,{children:[e.jsx(t.Dropdown,{defaultValue:(null===(w=n.value)||void 0===w?void 0:w.toString())||"",disabled:n.readOnly,items:null!==(k=null===(O=n.options)||void 0===O?void 0:O.map((e=>({id:e.value,label:e.label}))))&&void 0!==k?k:[],onItemSelected:e=>r(D,null!=e?e:"",{shouldValidate:!0}),name:D,label:n.label,placeholder:n.placeholder,tooltip:null!==(R=null===(F=n.guide)||void 0===F?void 0:F.tooltip)&&void 0!==R?R:n.tooltip,description:null!==(q=null===(T=n.guide)||void 0===T?void 0:T.description)&&void 0!==q?q:n.description,required:n.required,error:!!i[D]}),E]}):null},ke=({error:n})=>{if(!n)return null;try{return e.jsx(t.CodeBlock,{json:JSON.parse(n.provider_response)})}catch(i){return(null==n?void 0:n.provider_response)&&(null==n?void 0:n.provider_response.length)>0?e.jsx(t.CodeBlock,{code:null==n?void 0:n.provider_response}):null}},Fe=({integrationName:n,error:i,notices:r=[]})=>{var s;return e.jsxs(t.Padded,{vertical:"large",horizontal:"medium",overflow:"auto",fullHeight:!0,children:[i&&e.jsx(t.Alert,{type:"error",message:(null===(s=i.provider_response)||void 0===s?void 0:s.trim())||i.message,hasMargin:!1,children:e.jsx(ke,{error:i})}),r.map((n=>e.jsx(t.Alert,{type:n.type,message:n.description,hasMargin:!1},n.key))),e.jsx(t.Flex,{direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,justify:t.FlexJustify.Center,align:t.FlexAlign.Center,children:e.jsxs(t.Spacer,{direction:"vertical",size:8,fullWidth:!0,children:[e.jsx(t.Typography.Text,{size:"small",fontWeight:"semi-bold",children:'Press "Connect" below to authenticate'}),e.jsxs(t.Typography.Text,{size:"small",color:"secondary",children:["An authentication window for ",n," will display,",e.jsx("br",{}),"please complete the necessary steps."]})]})})]})},Re=({fields:o,notices:a=[],onChange:u,error:c,onValidationChange:l,integrationName:d,connectorKey:h,editingSecrets:p,setEditingSecrets:f})=>{const g=o.filter((e=>!1!==e.display)),y=g.map((e=>"object"==typeof e.key?JSON.stringify(e.key):String(e.key))),{noticesBefore:v,noticesAfter:m}=function(e,t=[]){const n=t[0],i=t[t.length-1];return{noticesBefore:t=>e.filter((e=>fe(e)?e.anchor===t:(!e.position||"top"===e.position)&&t===n)),noticesAfter:t=>e.filter((e=>!fe(e)&&"bottom"===e.position&&t===i))}}(a,y),b=n.useMemo((()=>function(e){const t=new Set;return(n,i)=>{if("undefined"==typeof window||t.has(n.key))return;t.add(n.key);const r=be(i)?void 0:i.format;window.dispatchEvent(new CustomEvent("stackone-hub:field-validation-failed",{detail:Object.assign(Object.assign(Object.assign({},e?{connector:e}:{}),{field:n.key,ruleKind:be(i)?"legacy":r?"format":"pattern"}),r?{format:r}:{})}))}}(h)),[h]),x=n.useMemo((()=>je(o)),[o]),C=n.useMemo((()=>function(e,t=je(e)){const n={};for(const i of e)n[i.key]=we(i,t.get(i.key));return s.z.object(n)}(o,x)),[o,x]),j=n.useMemo((()=>{const e={};return o.forEach((t=>{void 0!==t.value?e[t.key]=t.value.toString():e[t.key]=""})),e}),[o]),{formState:S,watch:w,reset:O,setValue:k,getValues:F}=r.useForm({resolver:i.zodResolver(C),mode:"onTouched",defaultValues:j}),{errors:R,isValid:T}=S;pe((()=>{O(j)}),[j]);const q=w();pe((()=>{u(q)}),[q]),n.useEffect((()=>{null==l||l(T)}),[T,l]);const D=e=>{document.hasFocus()&&e.validation&&function(e,t,n){return Se(t.get(e.key),n)}(e,x,F(e.key))&&b(e,e.validation)};return 0===g.length?e.jsx(Fe,{integrationName:d,error:c,notices:a}):e.jsx(t.Padded,{vertical:"large",horizontal:"medium",overflow:"auto",children:e.jsxs(t.Spacer,{direction:"vertical",size:8,fullWidth:!0,children:[c&&e.jsx(t.Alert,{type:"error",message:c.message,hasMargin:!1,children:e.jsx(ke,{error:c})}),e.jsx(t.Form,{children:g.map((n=>{const i="object"==typeof n.key?JSON.stringify(n.key):String(n.key),r=v(i).length>0||m(i).length>0;return e.jsxs("div",{style:Object.assign(Object.assign({},r&&{display:"flex",flexDirection:"column",gap:"8px"}),{width:"100%"}),children:[v(i).map((n=>e.jsx(t.Alert,{type:n.type,message:n.description,hasMargin:!1},n.key))),e.jsx(Oe,{field:n,errors:R,setValue:k,onLeave:()=>D(n),editingSecrets:p,setEditingSecrets:f}),m(i).map((n=>e.jsx(t.Alert,{type:n.type,message:n.description,hasMargin:!1},n.key)))]},i)}))})]})})},Te=({fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:u,setEditingSecrets:c})=>e.jsx(Re,{fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:u,setEditingSecrets:c}),qe=e=>e.split(/[-_\s]+/).filter(Boolean),De=e=>qe(e).join(" ").toLowerCase(),Ee=e=>qe(e).join(" ").toUpperCase(),Pe=({src:t,alt:i,fallbackUrl:r="https://stackone-logos.com/api/stackone/filled/png",style:s,className:o})=>{const[a,u]=n.useState(t);return e.jsx("img",{src:a,alt:i,style:s,className:o,onError:()=>{u(r)}})},Ie=e=>Boolean(e.active&&e.name),Ae=({integration:n})=>{var i;return e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.SpaceBetween,width:"100%",children:[e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.Left,width:"100%",children:[e.jsx(Pe,{src:n.logo_url,alt:n.provider,style:{width:"24px",height:"24px"}}),e.jsx(t.Typography.Text,{textAlign:"left",children:null!==(i=n.name)&&void 0!==i?i:"N/A"})]}),e.jsx(t.Typography.SecondaryText,{size:"xsmall",style:{maxWidth:"45%",flexShrink:0},children:e.jsx(t.TruncatedTooltip,{text:Ee(n.type),children:Ee(n.type)})})]})},Qe=({integrations:i,selectedCategory:r,onCategoryChange:s,onSearchChange:o})=>{const a=n.useCallback((e=>{s(r===e?null:e)}),[r,s]),u=n.useMemo((()=>Array.from(new Set(i.filter(Ie).map((e=>De(e.type)))))),[i]);return e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{name:"search",placeholder:"Search Integrations",variant:"ghost",size:"large",onChange:o}),u.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(t.Divider,{}),e.jsx(t.Padded,{vertical:"small",horizontal:"none",fullHeight:!1,children:e.jsx("div",{style:{overflowX:"auto",overflowY:"hidden",backgroundColor:"var(--malachite-card-background)",scrollbarWidth:"none",msOverflowStyle:"none"},className:"hide-scrollbar",children:e.jsx("div",{style:{display:"flex",minWidth:"max-content"},children:u.map((n=>e.jsx(t.Padded,{vertical:"none",horizontal:"small",fullHeight:!1,children:e.jsx(t.PillButton,{size:"xsmall",label:Ee(n),selected:r===n,onClick:()=>a(n)})},n)))})})})]})]})},Me=({integrations:i,onSelect:r,selectedCategory:s,search:o})=>{const a=n.useMemo((()=>i.filter((e=>Ie(e)&&(!s||De(e.type)===s)&&(!o||e.name.toLowerCase().includes(o.toLowerCase()))))),[i,s,o]);return e.jsx(e.Fragment,{children:a.length>0?e.jsx(t.Padded,{vertical:"small",horizontal:"small",fullHeight:!1,children:e.jsx(t.Spacer,{direction:"vertical",size:10,align:"start",children:e.jsx(t.ButtonList,{buttons:a.map((t=>({key:`${t.provider}@${t.version}`,children:e.jsx(Ae,{integration:t}),onClick:()=>r(t)})))})})}):e.jsx(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,fullHeight:!0,children:e.jsx(t.Typography.SecondaryText,{children:"No integrations found"})})})},Le=({integrations:t,onSelect:n,selectedCategory:i,search:r})=>t.length?e.jsx(Me,{integrations:t,onSelect:n,selectedCategory:i,search:r}):e.jsx("div",{children:"No integrations found."}),ze=({title:i,description:r,onCancel:s})=>{const[o,a]=n.useState(!1),u=n.useRef(null);return n.useEffect((()=>{if(s)return u.current=setTimeout((()=>a(!0)),5e3),()=>{u.current&&clearTimeout(u.current)}}),[s]),e.jsxs(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:[e.jsx(t.Spinner,{size:"xxxsmall"}),e.jsx(t.Typography.Text,{fontWeight:"bold",size:"large",children:i}),e.jsx(t.Typography.SecondaryText,{children:r}),o&&s&&e.jsxs(t.Typography.SecondaryText,{children:["Having trouble?"," ",e.jsx("button",{type:"button",onClick:s,style:{background:"none",border:"none",padding:0,cursor:"pointer",textDecoration:"underline",font:"inherit",color:"inherit"},children:"Cancel and start over"})]})]})},Ue=({title:t,description:n,onCancel:i})=>e.jsx(ze,{title:t,description:n,onCancel:i}),_e=({integrationName:n})=>{const i=t.getCurrentTheme();return e.jsxs(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:[e.jsx(t.CustomIcons.CheckCircleFilled,{size:16,style:{color:i.colors.success.foreground}}),e.jsx(t.Typography.Text,{fontWeight:"bold",size:"large",children:"Connection Successful"}),e.jsxs(t.Typography.SecondaryText,{children:["Account successfully connected to ",n]})]})},$e=({integrationName:t})=>e.jsx(_e,{integrationName:t}),He=({isLoading:t,hasError:n,connectionState:i,selectedIntegration:r,connectorData:s,hubData:o,fields:a,notices:u,selectedCategory:c,search:l,errorHubData:d,errorConnectorData:h,onSelect:p,onChange:f,onValidationChange:g,onCancelOAuth:y,editingSecrets:v,setEditingSecrets:m})=>{var b,x;return t?e.jsx(Ue,{title:"Loading integration data",description:"Please wait, this may take a moment."}):i.loading&&r?e.jsx(Ue,{title:`Connecting to ${null!==(b=null==s?void 0:s.name)&&void 0!==b?b:r.name}`,description:"Please wait, this may take a moment.",onCancel:y}):n?e.jsx(ce,{message:(null==d?void 0:d.message)||(null==h?void 0:h.message)||"Unknown error"}):i.success&&r?e.jsx($e,{integrationName:null!==(x=null==s?void 0:s.name)&&void 0!==x?x:r.name}):r?s?e.jsx(Te,{fields:a,notices:u,error:i.error,onChange:f,onValidationChange:g,integrationName:s.name,connectorKey:s.key,editingSecrets:v,setEditingSecrets:m}):null:(null==o?void 0:o.integrations.length)?e.jsx(Le,{integrations:o.integrations,onSelect:p,selectedCategory:c,search:l}):e.jsx(ce,{message:"No configured integrations available."})},Ke=({connectorData:n,onBack:i,guide:r})=>{var s;return e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.SpaceBetween,children:[e.jsxs(t.Flex,{direction:t.FlexDirection.Horizontal,align:t.FlexAlign.Center,gapSize:t.FlexGapSize.Small,justify:t.FlexJustify.Left,children:[i&&e.jsx(t.Button,{variant:"ghost",onClick:i,icon:"←",size:"small"}),e.jsx(Pe,{src:null===(s=n.assets)||void 0===s?void 0:s.icon,alt:n.key,style:{width:"16px",height:"16px"}}),e.jsx(t.Typography.Text,{fontWeight:"semi-bold",size:"medium",children:n.name})]}),(null==r?void 0:r.supportLink)?e.jsx(t.Typography.LinkText,{href:r.supportLink,target:"_blank",children:e.jsx(t.Button,{variant:"outline",size:"small",children:"Connection guide"})}):null]})},Ne=({connectorData:t,accountData:n,onBack:i,guide:r,isLoading:s,hasError:o,hubData:a,selectedCategory:u,onCategoryChange:c,onSearchChange:l,hideBackButton:d})=>{if(t)return e.jsx(Ke,{connectorData:t,onBack:n||d?void 0:i,guide:r});return!s&&!o&&(null==a?void 0:a.integrations)?e.jsx(Qe,{integrations:a.integrations,selectedCategory:u,onCategoryChange:c,onSearchChange:l}):null},Be=({fullWidth:i=!0,selectedIntegration:r,showActions:s,onBack:o,onNext:a,isFormValid:u=!0,isLoading:c=!1,showFooterLinks:l=!0})=>{const d=n.useMemo((()=>{if(!r||!s)return[];const e=[];return o&&e.push({label:"Back",type:"outline",onClick:o,disabled:c,loading:!1}),e.push({label:"Connect",type:"filled",onClick:a,disabled:!u||c,loading:c}),e}),[r,o,a,s,u,c]);return 0===d.length?l?e.jsx(t.FooterLinks,{fullWidth:i}):null:e.jsxs(t.Spacer,{direction:"horizontal",size:4,justifyContent:"space-between",children:[l&&e.jsx(t.FooterLinks,{fullWidth:i}),e.jsx(t.Padded,{vertical:"none",horizontal:"small",fullHeight:!1,children:e.jsx(t.Flex,{direction:t.FlexDirection.Horizontal,justify:t.FlexJustify.Right,children:e.jsx(t.Spacer,{direction:"horizontal",size:10,children:d.map((n=>e.jsx(t.Button,{size:"small",variant:n.type,onClick:n.onClick,disabled:n.disabled,loading:n.loading,iconPosition:"end",children:n.label},n.label)))})})})]})},Ve=({showFooterLinks:n=!0,onClose:i,onCloseLabel:r})=>{const s=n,o=Boolean(i);return s||o?e.jsxs(t.Spacer,{direction:"horizontal",size:4,justifyContent:s&&o?"space-between":o?"end":void 0,children:[s&&e.jsx(t.FooterLinks,{fullWidth:!0}),o&&e.jsx(t.Padded,{vertical:"none",horizontal:"small",fullHeight:!1,children:e.jsx(t.Flex,{direction:t.FlexDirection.Horizontal,justify:t.FlexJustify.Right,children:e.jsx(t.Spacer,{direction:"horizontal",size:10,children:e.jsx(t.Button,{size:"small",variant:"filled",onClick:i,children:null!=r?r:"Close"})})})})]}):null};function Ge(e,t,n,i){return new(n||(n=Promise))((function(r,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}u((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const We="x-hub-version",Je=e=>{const t={};for(const[n,i]of Object.entries(null!=e?e:{}))n.toLowerCase()!==We.toLowerCase()&&(t[n]=i);return t[We]="1.12.1",t};function Ye(e){return Ge(this,arguments,void 0,(function*({url:e,body:t,headers:n,method:i,requestFn:r=fetch,logger:s=console}){try{const a=yield r(e,{method:i,headers:Je(n),body:JSON.stringify(t)});if((e=>401===(null==e?void 0:e.status)||403===(null==e?void 0:e.status))(a))return s.warn("Token expired"),null;{if(!a.ok){const e=yield a.json();if(e&&void 0!==(o=e).statusCode){const{statusCode:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["statusCode"]);throw new Error(JSON.stringify(Object.assign({status:t},n)))}}const e=yield a.text();return e?JSON.parse(e):null}}catch(o){throw s.error(`Error making request to ${e}`,o),o}var o}))}function Xe(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"POST"}))}))}function Ze(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"GET"}))}))}const et=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){const i={"Content-Type":"application/json","x-hub-session-token":e};let r=`${t}/hub/connectors`;return n&&(r+=`?provider=${encodeURIComponent(n)}`),yield Ze({url:r,headers:i})})),tt=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/connectors/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),nt=e=>Ge(void 0,[e],void 0,(function*({baseUrl:e,accountId:t,token:n,credentials:i,integrationId:r}){return yield function(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"PATCH"}))}))}({url:`${e}/hub/accounts/${t}`,headers:{"Content-Type":"application/json","x-hub-session-token":n},body:{integration_id:r,credentials:i}})})),it=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),rt=(e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield function(e){return Ge(this,void 0,void 0,(function*(){return Ye(Object.assign(Object.assign({},e),{method:"DELETE"}))}))}({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),st={retry:(e,t)=>{if(t&&"object"==typeof t&&"message"in t)try{const e=JSON.parse(t.message);if(401===e.status||403===e.status)return!1}catch(e){}return e<2},retryDelay:e=>Math.min(1e3*Math.pow(2,e),3e4)};var ot;!function(e){e.AccountConnected="AccountConnected"}(ot||(ot={}));const at=({token:e,baseUrl:t,accountId:i,onSuccess:r,dashboardUrl:s,debug:o})=>{const[a,u]=n.useState(null),[c,l]=n.useState({}),[d,h]=n.useState(new Set),p=n.useCallback((e=>{l(e)}),[]),f=n.useRef(null),g=n.useRef(null),y=n.useRef(null),v=n.useRef(null),m=n.useRef(!1),[b,x]=n.useState({loading:!1,success:!1}),C=n.useCallback((()=>{null!==y.current&&(clearTimeout(y.current),y.current=null),g.current=null}),[]),j=n.useCallback((e=>{x({loading:!1,success:!0}),null==r||r(e)}),[r]),S=n.useRef(o);S.current=o;const w=n.useCallback((()=>{null!==v.current&&(clearTimeout(v.current),v.current=null)}),[]),O=n.useCallback((()=>{C(),w(),f.current&&(f.current.close(),f.current=null)}),[C,w]);n.useEffect((()=>()=>{C(),w()}),[C,w]);const{data:k,isLoading:F,error:R}=ue(Object.assign({queryKey:["accountData",i],queryFn:()=>Ge(void 0,void 0,void 0,(function*(){return i?((e,t,n)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/accounts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,i):null})),enabled:!!i},st)),{data:T,isLoading:q,error:D}=ue(Object.assign({queryKey:["hubData",null==k?void 0:k.provider],queryFn:()=>(null==k?void 0:k.provider)?et(e,t,k.provider):et(e,t),enabled:!i||!!k},st));n.useEffect((()=>{if(k&&T){const e=T.integrations.find((e=>e.provider===k.provider));u(null!=e?e:null)}}),[k,T]),n.useEffect((()=>{if(T&&!a){const e=T.integrations.filter((e=>e.active));1===e.length&&u(e[0])}}),[T,a]);const{data:E,isLoading:P,error:I}=ue(Object.assign({queryKey:["connectorData",null==k?void 0:k.integrationId,null==a?void 0:a.integration_id],queryFn:()=>Ge(void 0,void 0,void 0,(function*(){return k?tt(t,e,k.integrationId):a?tt(t,e,a.integration_id):null})),enabled:Boolean(a)||Boolean(k)},st)),{fields:A,guide:Q,notices:M}=n.useMemo((()=>{var e,t,n,i,r,s,o,u,c;if(!E||!a){return{fields:[],notices:[]}}if(("configFields"in(c=E.config)||"configNotices"in c)&&!("authentication"in c)){const s=(null!==(e=E.config.configFields)&&void 0!==e?e:[]).map((e=>{var t,n;const i=null===(t=null==k?void 0:k.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==T?void 0:T.external_trigger_token});if(k&&(!1!==e.secret||"password"===e.type)){const t=null===(n=k.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:s,notices:null!==(t=E.config.configNotices)&&void 0!==t?t:[],guide:{supportLink:null===(n=E.config.support)||void 0===n?void 0:n.link,description:null!==(r=null===(i=E.config.support)||void 0===i?void 0:i.description)&&void 0!==r?r:""}}}let l=a.authentication_config_key,d=a.environment;k&&k.authConfigKey&&(null===(s=E.config.authentication)||void 0===s?void 0:s[k.authConfigKey])&&(l=k.authConfigKey,d=null!==(o=k.environment)&&void 0!==o?o:a.environment);const h=null===(u=E.config.authentication)||void 0===u?void 0:u[l],p=null==h?void 0:h[d],f=((null==p?void 0:p.fields)||[]).map((e=>{var t,n;const i=null===(t=null==k?void 0:k.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==T?void 0:T.external_trigger_token});if(k&&(!1!==e.secret||"password"===e.type)){const t=null===(n=k.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:f,notices:[],guide:null==p?void 0:p.guide}}),[E,a,k,T]),L=n.useMemo((()=>{var e,t,n,i,r;if(!E||!a)return null;if("authentication"in(r=E.config)&&!("configFields"in r)){let r=a.authentication_config_key,s=a.environment;return k&&k.authConfigKey&&(null===(e=E.config.authentication)||void 0===e?void 0:e[k.authConfigKey])&&(r=k.authConfigKey,s=null!==(t=k.environment)&&void 0!==t?t:a.environment),null===(i=null===(n=E.config.authentication)||void 0===n?void 0:n[r])||void 0===i?void 0:i[s]}return E.config}),[E,a,k]),[z,U]=n.useState(!0),_=n.useCallback(((n,i)=>{const r=Date.now(),s=()=>Ge(void 0,void 0,void 0,(function*(){var o,a,u,c;if(!y.current)return;if(Date.now()-r>3e5)return S.current&&console.debug("[hub] poll timed out",{attemptId:n}),O(),rt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})})),void x({loading:!1,success:!1,timedOut:!0});const l=yield it(t,e,n).catch((()=>null));if(y.current){if(!l)return S.current&&console.debug("[hub] poll failed (network error), retrying"),void(y.current=window.setTimeout(s,2e3));S.current&&"pending"!==l.status&&console.debug("[hub] poll result",Object.assign({attemptId:n},l)),"authenticated"===l.status&&l.account?(O(),j({id:l.account.id,provider:i}),parent.postMessage({type:ot.AccountConnected,account:{id:l.account.id,provider:i}},"*")):"error"===l.status?(O(),x({loading:!1,success:!1,error:{message:null!==(a=null===(o=l.error)||void 0===o?void 0:o.code)&&void 0!==a?a:"OAuth error",provider_response:null!==(c=null===(u=l.error)||void 0===u?void 0:u.description)&&void 0!==c?c:"No description"}})):"cancelled"===l.status||"expired"===l.status?(O(),x({loading:!1,success:!1})):y.current=window.setTimeout(s,2e3)}}));y.current=window.setTimeout(s,2e3)}),[t,e,O,j]),$=n.useCallback((n=>{let i=!0;const r=()=>Ge(void 0,void 0,void 0,(function*(){if(i&&(i=!1,!f.current||f.current.closed))return S.current&&console.debug("[hub] popup reads as closed on first tick, assuming COOP isolation — popup-close detection disabled"),m.current=!0,void(v.current=null);if(f.current&&!f.current.closed)return void(v.current=window.setTimeout(r,1e3));if(v.current=null,!y.current)return;if(m.current)return;const s=g.current;if(!s)return;const o=yield it(t,e,s).catch((e=>(S.current&&console.debug("[hub] final poll failed after popup closed",{attemptId:s,error:e}),null)));return y.current?"authenticated"===(null==o?void 0:o.status)&&o.account?(S.current&&console.debug("[hub] popup closed but auth completed",{attemptId:s}),O(),j({id:o.account.id,provider:n}),void parent.postMessage({type:ot.AccountConnected,account:{id:o.account.id,provider:n}},"*")):void(S.current&&console.debug("[hub] popup reported closed but attempt still pending — deferring to poll loop (likely cross-origin/COOP false-close)",{attemptId:s})):void 0}));v.current=window.setTimeout(r,1e3)}),[t,e,O,j]),H=n.useCallback((()=>Ge(void 0,void 0,void 0,(function*(){var n;if(a)if(z){x({loading:!0,success:!1});try{const r=Object.assign({},c);k&&A.forEach((e=>{if(!1!==e.secret||"password"===e.type){const t=r[e.key];ye(t)&&!d.has(e.key)&&delete r[e.key]}})),Object.keys(r).forEach((e=>{""===r[e]&&delete r[e]}));const o="oauth2"===(null==L?void 0:L.type)&&(!("grantType"in L)||"authorization_code"===L.grantType);if(S.current&&console.debug("[hub] handleConnect",{integration:a.integration_id,path:o?"oauth-redirect":"credential-form",updating:!!i}),o){const i=yield((e,t)=>Ge(void 0,void 0,void 0,(function*(){return yield Xe({url:`${e}/hub/connection_attempts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{token:t}})})))(t,e).catch((()=>null)),o=null!==(n=null==i?void 0:i.id)&&void 0!==n?n:null;if(g.current=o,!o)return S.current&&console.debug("[hub] connection attempt creation failed"),void x({loading:!1,success:!1,error:{message:"Failed to start OAuth flow",provider_response:"Could not create a connection attempt. Please try again."}});S.current&&console.debug("[hub] connection attempt created",{attemptId:o});const u=encodeURIComponent(`${s}/embedded/accounts/callback`);let c=`${t}/connect/oauth2/${a.integration_id}?redirect_uri=${u}&token=${e}&connection_attempt_id=${o}`;Object.keys(r).forEach((e=>{c+=`&${e}=${encodeURIComponent(r[e])}`}));const l=1024,d=800,h=void 0!==window.screenX?window.screenX:window.screenLeft,p=void 0!==window.screenY?window.screenY:window.screenTop,y=void 0!==window.outerWidth?window.outerWidth:document.body.clientWidth,v=void 0!==window.outerHeight?window.outerHeight:document.body.clientHeight-22,b=parseInt((h+(y-l)/2).toString(),10),C=`width=${l},height=${d},left=${b},top=${parseInt((p+(v-d)/2.5).toString(),10)},noopener=0`;return f.current=window.open(c,"Connect Account",C),f.current?(m.current=!1,"function"==typeof f.current.focus&&f.current.focus(),_(o,a.provider),void $(a.provider)):(S.current&&console.debug("[hub] popup was blocked by browser"),O(),rt(t,e,o).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:o,error:e})})),void x({loading:!1,success:!1,error:{message:"Popup blocked",provider_response:"Your browser blocked the login popup. Please allow popups for this site and try again."}}))}let u;if(i)yield nt({baseUrl:t,accountId:i,token:e,integrationId:a.integration_id,credentials:r}),u={id:i,provider:a.provider};else{const n=yield(e=>Ge(void 0,[e],void 0,(function*({baseUrl:e,token:t,credentials:n,integrationId:i}){return yield Xe({url:`${e}/hub/accounts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{integration_id:i,credentials:n}})})))({baseUrl:t,token:e,credentials:r,integrationId:a.integration_id});if(!n)throw new Error("Failed to create account");u={id:n.id,provider:a.provider}}j(u)}catch(e){let t="An unexpected error occurred",n="Please try again later";try{const i=JSON.parse(e.message);try{const e=JSON.parse(i.message);t=e.message||t,n=e.provider_response||n}catch(e){t=i.message||t,n=i.provider_response||n}}catch(n){t=e.message||t}x({loading:!1,success:!1,error:{message:t,provider_response:n}})}}else x({loading:!1,success:!1,error:{message:"Please fix the validation errors before continuing",provider_response:"Form validation failed"}})}))),[t,s,e,a,c,d,j,k,A,i,L,O,_,$,z]),K=n.useCallback((()=>{const n=g.current;S.current&&console.debug("[hub] OAuth cancelled by user",{attemptId:n}),O(),x({loading:!1,success:!1}),n&&rt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})}))}),[t,e,O]),N=q||P||F,B=!!(D||I||R);n.useEffect((()=>{h(new Set)}),[a]),n.useEffect((()=>{B&&b.loading&&x((e=>Object.assign(Object.assign({},e),{loading:!1})))}),[B,b.loading]);const V=n.useRef(b.loading);n.useEffect((()=>{o&&V.current&&!b.loading&&console.debug("[hub] connectionState.loading → false",b),V.current=b.loading}),[o,b]);const G=n.useCallback((()=>{x({loading:!1,success:!1}),h(new Set)}),[]),W=n.useCallback((()=>{x({loading:!1,success:!1}),h(new Set)}),[]);return{hubData:T,accountData:k,connectorData:E,selectedIntegration:a,fields:A,notices:M,guide:Q,formData:c,connectionState:b,isLoading:N,hasError:B,isFormValid:z,errorHubData:D,errorConnectorData:I,errorAccountData:R,setSelectedIntegration:u,setFormData:p,setIsFormValid:U,handleConnect:H,handleCancelOAuth:K,resetConnectionState:G,resetAllErrors:W,editingSecrets:d,setEditingSecrets:h}},ut=({token:i,baseUrl:r,height:s,accountId:o,onSuccess:a,onClose:u,dashboardUrl:c,showFooterLinks:l=!0,onCloseLabel:d,debug:h})=>{var p,f,g,y;const[v,m]=n.useState(null),[b,x]=n.useState(""),{hubData:C,accountData:j,connectorData:S,selectedIntegration:w,fields:O,notices:k,guide:F,connectionState:R,isLoading:T,hasError:q,isFormValid:D,errorHubData:E,errorConnectorData:P,setSelectedIntegration:I,setFormData:A,setIsFormValid:Q,handleConnect:M,handleCancelOAuth:L,resetConnectionState:z,editingSecrets:U,setEditingSecrets:_}=at({token:i,baseUrl:r,accountId:o,onSuccess:a,dashboardUrl:c,debug:h}),$=n.useCallback((e=>{Q(e)}),[Q]),H=n.useMemo((()=>{if(!C)return!1;return 1===C.integrations.filter((e=>e.active)).length}),[C]),K=()=>{I(null),z(),m(null),x("")};return e.jsxs(t.Card,{glassFooter:!0,footer:R.success?e.jsx(Ve,{onClose:u,showFooterLinks:l,onCloseLabel:d}):e.jsx(Be,{selectedIntegration:w,showActions:!R.loading&&!R.success,onBack:j||H?void 0:K,onNext:M,isFormValid:D,isLoading:T,showFooterLinks:l}),title:T||R.loading||R.success?null:e.jsx(Ne,{accountData:j,onBack:K,guide:F,isLoading:T,hasError:q,hubData:C,selectedCategory:v,onCategoryChange:m,onSearchChange:x,hideBackButton:R.loading||R.success||H,connectorData:null!==(p=null==S?void 0:S.config)&&void 0!==p?p:null}),height:s,padding:"0",headerConfig:w?void 0:{padding:"0"},children:[R.timedOut&&e.jsx(t.Alert,{type:"warning",message:"Connection timed out. Please try again.",hasMargin:!0}),e.jsx(He,{isLoading:T,hasError:q,connectionState:R,selectedIntegration:w,connectorData:null!==(f=null==S?void 0:S.config)&&void 0!==f?f:null,hubData:null!=C?C:null,fields:O,notices:k,errorHubData:null!==(g=E)&&void 0!==g?g:null,errorConnectorData:null!==(y=P)&&void 0!==y?y:null,onSelect:I,onChange:A,onValidationChange:$,onCancelOAuth:L,selectedCategory:v,search:b,editingSecrets:U,setEditingSecrets:_})]})},ct=n.createContext({featureFlags:[]}),lt=({featureFlags:t,children:i})=>{const r=n.useMemo((()=>({featureFlags:t})),[t]);return e.jsx(ct.Provider,{value:r,children:i})},dt=n.memo((({mode:t,token:n,apiUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,accountId:u,showFooterLinks:c,onCloseLabel:l,debug:d})=>{var h;const{data:p}=ue({queryKey:["settings"],queryFn:()=>((e,t)=>Ge(void 0,void 0,void 0,(function*(){return yield Ze({url:`${e}/hub/settings`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(i,n)});return e.jsx(lt,{featureFlags:null!==(h=null==p?void 0:p.enabled_features)&&void 0!==h?h:[],children:"integration-picker"===t&&e.jsx(ut,{token:n,baseUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,onCloseLabel:l,accountId:null!=u?u:null==p?void 0:p.existing_account_id,showFooterLinks:c,debug:d})})})),ht=()=>e.jsxs(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,direction:t.FlexDirection.Vertical,gapSize:t.FlexGapSize.Small,fullHeight:!0,children:[e.jsx(t.CustomIcons.RejectIcon,{style:{color:"red"}}),e.jsx(t.Typography.Text,{fontWeight:"bold",size:"large",children:"Error"}),e.jsx(t.Typography.SecondaryText,{children:"Something went wrong, our team has been notified."})]});class pt extends n.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?this.props.fallback:this.props.children}}exports.StackOneHub=({mode:i,token:r,baseUrl:s,appUrl:o,height:a="500px",theme:u="light",accountId:c,onSuccess:l,onClose:d,onCloseLabel:h,showFooterLinks:p,debug:f})=>{const g=null!=s?s:"https://api.stackone.com",y=null!=o?o:"https://app.stackone.com";n.useEffect((()=>{"dark"===u?t.applyDarkTheme():"light"===u?t.applyLightTheme():t.applyTheme(u)}),[u]);const[v]=n.useState((()=>new J({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,retryDelay:500,refetchOnMount:!1,retryOnMount:!1}}}))),m=n.useRef(r);return n.useEffect((()=>{m.current!==r&&(m.current=r,v.clear())}),[r,v]),r?e.jsx(t.MalachiteContext,{children:e.jsx(pt,{fallback:e.jsx(t.Card,{height:a,children:e.jsx(ht,{})}),children:e.jsx(ie,{client:v,children:e.jsx(dt,{mode:null!=i?i:"integration-picker",token:r,apiUrl:g,dashboardUrl:y,height:a,onSuccess:l,accountId:c,onClose:d,onCloseLabel:h,showFooterLinks:p,debug:f})})})}):e.jsx(t.MalachiteContext,{children:e.jsx(pt,{fallback:e.jsx(t.Card,{height:a,children:e.jsx(ht,{})}),children:e.jsx(t.Card,{height:a,footer:e.jsx(t.FooterLinks,{}),children:e.jsx(t.Flex,{justify:t.FlexJustify.Center,align:t.FlexAlign.Center,fullHeight:!0,children:e.jsx(t.Typography.PageTitle,{children:"No token provided"})})})})})};
|