@rabstack/rab-react-sdk
Advanced tools
| "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("react/jsx-runtime"),S=require("react");function ut(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,r.get?r:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const d=ut(S);class T extends Error{constructor(e){super(`API Error ${e.status}: ${e.message} [${e.method} ${e.url}]`),this.name="ApiDomainError",this.status=e.status,this.url=e.url,this.method=e.method,this.errorCode=e.errorCode,this.errors=e.errors,this.data=e.data,Error.captureStackTrace&&Error.captureStackTrace(this,T)}isNetworkError(){return this.status===0}isClientError(){return this.status>=400&&this.status<500}isServerError(){return this.status>=500}isUnauthorized(){return this.status===401}isForbidden(){return this.status===403}isNotFound(){return this.status===404}isValidationError(){return this.status===422||this.status===400}isConflict(){return this.status===409}getAllMessages(){const e=[this.message];return this.errors&&this.errors.length>0&&e.push(...this.errors),e}getDisplayMessage(){return this.errors&&this.errors.length>0?`${this.message}: ${this.errors.join(", ")}`:this.message}}function tt(t,e,s,r,i){return{status:t,url:s,method:r,message:i?.message||e,errorCode:i?.errorCode,errors:i?.errors,data:i}}function et(...t){if(t.length===0)return"";let e=[...t].filter(Boolean);const s=e[e.length-1];if(typeof s=="object"&&s!==null){const r=s;e=e.slice(0,-1).map(i=>{if(typeof i=="string"){let c=i;for(const n in r)c=c.replace(`:${n}`,String(r[n]));return c}return i})}return e.filter(r=>typeof r=="string"&&r.trim()!=="").map((r,i)=>r.startsWith("/")||i===0?r:"/"+r).join("")}function ct(t){return{url:t,method:"GET"}}function ht(t){return{url:t,method:"POST"}}function lt(t){return{url:t,method:"PUT"}}function ft(t){return{url:t,method:"PATCH"}}function dt(t){return{url:t,method:"DELETE"}}function st(t){return t?.data!==void 0?t.data:t}function pt(t){const{baseUrl:e,getAuthorization:s,extractApiError:r=tt,parseQuery:i,transformResponse:c=st}=t;return async(n,o={})=>{try{const{body:a,query:u,params:h,encodeQuery:f,headers:l}=o,y=et(n.url,h??{}),E=e.replace(/\/$/,""),O=y.startsWith("/")?y:"/"+y,R=new URL(E+O);if(u)if(i&&f!==!1){const b=i(u);if(b){const w=b.split("&");for(const m of w){const[p,C]=m.split("=");p&&C!==void 0&&R.searchParams.append(decodeURIComponent(p),decodeURIComponent(C))}}}else Object.entries(u).forEach(([b,w])=>{w!=null&&R.searchParams.append(b,String(w))});const P={"Content-Type":"application/json",...l},D=s?.();D&&Object.assign(P,D);const v=await fetch(R.toString(),{method:n.method,headers:P,body:a?JSON.stringify(a):void 0});if(!v.ok){let b;try{b=await v.clone().json()}catch{b=await v.text()}const w=r(v.status,v.statusText,R.toString(),n.method,b);throw new T(w)}const j=await v.json();return c(j,v)}catch(a){if(a instanceof T)throw a;const u={status:0,url:`${e}${n.url}`,method:n.method,message:a instanceof Error?a.message:"Network request failed",data:a};throw new T(u)}}}function rt(t){const{apiSpecs:e,baseUrl:s,getAuthorization:r,extractApiError:i,parseQuery:c,transformResponse:n}=t,o={},a=pt({baseUrl:s,getAuthorization:r,extractApiError:i,parseQuery:c,transformResponse:n});return Object.entries(e).forEach(([u,h])=>{o[u]=(f={})=>a(h,f)}),o}var K=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},yt={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},mt=class{#e=yt;#t=!1;setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&this.#t&&t!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:t}),this.#e=t,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},F=new mt;function vt(t){setTimeout(t,0)}var I=typeof window>"u"||"Deno"in globalThis;function k(){}function $(t){return typeof t=="number"&&t>=0&&t!==1/0}function bt(t,e){return Math.max(t+(e||0)-Date.now(),0)}function M(t,e){return typeof t=="function"?t(e):t}function g(t,e){return typeof t=="function"?t(e):t}function B(t){return JSON.stringify(t,(e,s)=>q(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}var gt=Object.prototype.hasOwnProperty;function U(t,e){if(t===e)return t;const s=V(t)&&V(e);if(!s&&!(q(t)&&q(e)))return e;const i=(s?t:Object.keys(t)).length,c=s?e:Object.keys(e),n=c.length,o=s?new Array(n):{};let a=0;for(let u=0;u<n;u++){const h=s?u:c[u],f=t[h],l=e[h];if(f===l){o[h]=f,(s?u<i:gt.call(t,h))&&a++;continue}if(f===null||l===null||typeof f!="object"||typeof l!="object"){o[h]=l;continue}const y=U(f,l);o[h]=y,y===f&&a++}return i===n&&a===i?t:o}function A(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const s in t)if(t[s]!==e[s])return!1;return!0}function V(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function q(t){if(!W(t))return!1;const e=t.constructor;if(e===void 0)return!0;const s=e.prototype;return!(!W(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function W(t){return Object.prototype.toString.call(t)==="[object Object]"}function J(t,e,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(t,e);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return U(t,e)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${s.queryHash}]: ${r}`),r}return U(t,e)}return e}function it(t,e){return typeof t=="function"?t(...e):!!t}var St=class extends K{#e;#t;#s;constructor(){super(),this.#s=t=>{if(!I&&window.addEventListener){const e=()=>t();return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Ot=new St;function G(){let t,e;const s=new Promise((i,c)=>{t=i,e=c});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}var Et=vt;function wt(){let t=[],e=0,s=o=>{o()},r=o=>{o()},i=Et;const c=o=>{e?t.push(o):i(()=>{s(o)})},n=()=>{const o=t;t=[],o.length&&i(()=>{r(()=>{o.forEach(a=>{s(a)})})})};return{batch:o=>{let a;e++;try{a=o()}finally{e--,e||n()}return a},batchCalls:o=>(...a)=>{c(()=>{o(...a)})},schedule:c,setNotifyFunction:o=>{s=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{i=o}}}var N=wt(),Rt=class extends K{#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(!I&&window.addEventListener){const e=()=>t(!0),s=()=>t(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},Ct=new Rt;function Pt(t){return(t??"online")==="online"?Ct.isOnline():!0}function Dt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Pt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}var xt=class extends K{constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=G(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#i;#n;#o;#a;#y;#f;#d;#c;#h;#u;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Z(this.#t,this.options)?this.#l():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#O(),this.#t.removeObserver(this)}setOptions(t){const e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof g(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#E(),this.#t.setOptions(this.options),e._defaulted&&!A(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&X(this.#t,s,this.options,e)&&this.#l(),this.updateResult(),r&&(this.#t!==s||g(this.options.enabled,this.#t)!==g(e.enabled,this.#t)||M(this.options.staleTime,this.#t)!==M(e.staleTime,this.#t))&&this.#m();const i=this.#v();r&&(this.#t!==s||g(this.options.enabled,this.#t)!==g(e.enabled,this.#t)||i!==this.#u)&&this.#b(i)}getOptimisticResult(t){const e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return Mt(this,s)&&(this.#r=s,this.#n=this.options,this.#i=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:(s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(t){this.#p.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#l({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#l(t){this.#E();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(k)),e}#m(){this.#S();const t=M(this.options.staleTime,this.#t);if(I||this.#r.isStale||!$(t))return;const s=bt(this.#r.dataUpdatedAt,t)+1;this.#c=F.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(t){this.#O(),this.#u=t,!(I||g(this.options.enabled,this.#t)===!1||!$(this.#u)||this.#u===0)&&(this.#h=F.setInterval(()=>{(this.options.refetchIntervalInBackground||Ot.isFocused())&&this.#l()},this.#u))}#g(){this.#m(),this.#b(this.#v())}#S(){this.#c&&(F.clearTimeout(this.#c),this.#c=void 0)}#O(){this.#h&&(F.clearInterval(this.#h),this.#h=void 0)}createResult(t,e){const s=this.#t,r=this.options,i=this.#r,c=this.#i,n=this.#n,a=t!==s?t.state:this.#s,{state:u}=t;let h={...u},f=!1,l;if(e._optimisticResults){const p=this.hasListeners(),C=!p&&Z(t,e),x=p&&X(t,s,e,r);(C||x)&&(h={...h,...Dt(u.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:E,status:O}=h;l=h.data;let R=!1;if(e.placeholderData!==void 0&&l===void 0&&O==="pending"){let p;i?.isPlaceholderData&&e.placeholderData===n?.placeholderData?(p=i.data,R=!0):p=typeof e.placeholderData=="function"?e.placeholderData(this.#d?.state.data,this.#d):e.placeholderData,p!==void 0&&(O="success",l=J(i?.data,p,e),f=!0)}if(e.select&&l!==void 0&&!R)if(i&&l===c?.data&&e.select===this.#y)l=this.#f;else try{this.#y=e.select,l=e.select(l),l=J(i?.data,l,e),this.#f=l,this.#a=null}catch(p){this.#a=p}this.#a&&(y=this.#a,l=this.#f,E=Date.now(),O="error");const P=h.fetchStatus==="fetching",D=O==="pending",v=O==="error",j=D&&P,b=l!==void 0,m={status:O,fetchStatus:h.fetchStatus,isPending:D,isSuccess:O==="success",isError:v,isInitialLoading:j,isLoading:j,data:l,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:E,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>a.dataUpdateCount||h.errorUpdateCount>a.errorUpdateCount,isFetching:P,isRefetching:P&&!D,isLoadingError:v&&!b,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:v&&b,isStale:z(t,e),refetch:this.refetch,promise:this.#o,isEnabled:g(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const p=Q=>{m.status==="error"?Q.reject(m.error):m.data!==void 0&&Q.resolve(m.data)},C=()=>{const Q=this.#o=m.promise=G();p(Q)},x=this.#o;switch(x.status){case"pending":t.queryHash===s.queryHash&&p(x);break;case"fulfilled":(m.status==="error"||m.data!==x.value)&&C();break;case"rejected":(m.status!=="error"||m.error!==x.reason)&&C();break}}return m}updateResult(){const t=this.#r,e=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#n=this.options,this.#i.data!==void 0&&(this.#d=this.#t),A(e,t))return;this.#r=e;const s=()=>{if(!t)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const c=new Set(i??this.#p);return this.options.throwOnError&&c.add("error"),Object.keys(this.#r).some(n=>{const o=n;return this.#r[o]!==t[o]&&c.has(o)})};this.#w({listeners:s()})}#E(){const t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;const e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#w(t){N.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Tt(t,e){return g(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Z(t,e){return Tt(t,e)||t.state.data!==void 0&&_(t,e,e.refetchOnMount)}function _(t,e,s){if(g(e.enabled,t)!==!1&&M(e.staleTime,t)!=="static"){const r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&z(t,e)}return!1}function X(t,e,s,r){return(t!==e||g(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&z(t,s)}function z(t,e){return g(e.enabled,t)!==!1&&t.isStaleByTime(M(e.staleTime,t))}function Mt(t,e){return!A(t.getCurrentResult(),e)}function It(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jt=class extends K{#e;#t=void 0;#s;#r;constructor(t,e){super(),this.#e=t,this.setOptions(e),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const e=this.options;this.options=this.#e.defaultMutationOptions(t),A(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&B(e.mutationKey)!==B(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(t){this.#i(),this.#n(t)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#i(),this.#n()}mutate(t,e){return this.#r=e,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(t)}#i(){const t=this.#s?.state??It();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#n(t){N.batch(()=>{if(this.#r&&this.hasListeners()){const e=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};t?.type==="success"?(this.#r.onSuccess?.(t.data,e,s,r),this.#r.onSettled?.(t.data,null,e,s,r)):t?.type==="error"&&(this.#r.onError?.(t.error,e,s,r),this.#r.onSettled?.(void 0,t.error,e,s,r))}this.listeners.forEach(e=>{e(this.#t)})})}},Qt=d.createContext(void 0),H=t=>{const e=d.useContext(Qt);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},nt=d.createContext(!1),Ft=()=>d.useContext(nt);nt.Provider;function kt(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var At=d.createContext(kt()),Kt=()=>d.useContext(At),Nt=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},Ut=t=>{d.useEffect(()=>{t.clearReset()},[t])},qt=({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||it(s,[t.error,r])),_t=t=>{if(t.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},Lt=(t,e)=>t.isLoading&&t.isFetching&&!e,zt=(t,e)=>t?.suspense&&e.isPending,Y=(t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()});function Ht(t,e,s){if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Ft(),i=Kt(),c=H(),n=c.defaultQueryOptions(t);c.getDefaultOptions().queries?._experimental_beforeQuery?.(n),process.env.NODE_ENV!=="production"&&(n.queryFn||console.error(`[${n.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),n._optimisticResults=r?"isRestoring":"optimistic",_t(n),Nt(n,i),Ut(i);const o=!c.getQueryCache().get(n.queryHash),[a]=d.useState(()=>new e(c,n)),u=a.getOptimisticResult(n),h=!r&&t.subscribed!==!1;if(d.useSyncExternalStore(d.useCallback(f=>{const l=h?a.subscribe(N.batchCalls(f)):k;return a.updateResult(),l},[a,h]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),d.useEffect(()=>{a.setOptions(n)},[n,a]),zt(n,u))throw Y(n,a,i);if(qt({result:u,errorResetBoundary:i,throwOnError:n.throwOnError,query:c.getQueryCache().get(n.queryHash),suspense:n.suspense}))throw u.error;return c.getDefaultOptions().queries?._experimental_afterQuery?.(n,u),n.experimental_prefetchInRender&&!I&&Lt(u,r)&&(o?Y(n,a,i):c.getQueryCache().get(n.queryHash)?.promise)?.catch(k).finally(()=>{a.updateResult()}),n.notifyOnChangeProps?u:a.trackResult(u)}function $t(t,e){return Ht(t,xt)}function Bt(t,e){const s=H(),[r]=d.useState(()=>new jt(s,t));d.useEffect(()=>{r.setOptions(t)},[r,t]);const i=d.useSyncExternalStore(d.useCallback(n=>r.subscribe(N.batchCalls(n)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),c=d.useCallback((n,o)=>{r.mutate(n,o).catch(k)},[r]);if(i.error&&it(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:c,mutateAsync:i.mutate}}function ot(t){return function(s,r){const i=t(),{body:c,query:n,params:o,headers:a,encodeQuery:u,...h}=r??{};return $t({queryKey:[s,{body:c,query:n,params:o}],queryFn:async()=>{const f=i[s],l={};return c!==void 0&&(l.body=c),n!==void 0&&(l.query=n),o!==void 0&&(l.params=o),a!==void 0&&(l.headers=a),u!==void 0&&(l.encodeQuery=u),await f(Object.keys(l).length>0?l:void 0)},...h})}}function at(t){return function(s,r){const i=t(),c=H(),{invalidateQueries:n,onSettled:o,...a}=r??{};return Bt({mutationFn:async u=>{const h=i[s],f={};return"body"in u&&u.body!==void 0&&(f.body=u.body),"query"in u&&u.query!==void 0&&(f.query=u.query),"params"in u&&u.params!==void 0&&(f.params=u.params),"headers"in u&&u.headers!==void 0&&(f.headers=u.headers),"encodeQuery"in u&&u.encodeQuery!==void 0&&(f.encodeQuery=u.encodeQuery),await h(Object.keys(f).length>0?f:void 0)},onSettled:async(u,h,f,l,y)=>{n&&n.length>0&&await Promise.all(n.map(E=>c.invalidateQueries({queryKey:[E]}))),o&&await o(u,h,f,l,y)},...a})}}function Vt(t){const{apiSpecs:e,getAuthorization:s,extractApiError:r,parseQuery:i,transformResponse:c}=t,n=S.createContext(null);function o({baseUrl:f,children:l,getAuthorization:y}){const E=S.useMemo(()=>rt({apiSpecs:e,baseUrl:f,getAuthorization:y||s,extractApiError:r,parseQuery:i,transformResponse:c}),[f,y]);return L.jsx(n.Provider,{value:{sdk:E},children:l})}function a(){const f=S.useContext(n);if(!f)throw new Error("useSDK must be used within SDKProvider");return f.sdk}const u=ot(a),h=at(a);return{SDKProvider:o,useSDK:a,useQuery:u,useMutation:h,SDKContext:n}}function Wt(){const t=S.createContext(null);function e({sdk:r,children:i}){const c=S.useMemo(()=>typeof r=="function"?r():r,[r]);return L.jsx(t.Provider,{value:{sdk:c},children:i})}function s(){const r=S.useContext(t);if(!r)throw new Error("useSDK must be used within SDKProvider");return r.sdk}return{SDKProvider:e,useSDK:s,SDKContext:t}}function Jt(t){const e=S.createContext(null);function s(i){const{children:c,...n}=i,o=S.useMemo(()=>t(n),[JSON.stringify(n)]);return L.jsx(e.Provider,{value:{sdk:o},children:c})}function r(){const i=S.useContext(e);if(!i)throw new Error("useSDK must be used within SDKProvider");return i.sdk}return{SDKProvider:s,useSDK:r,SDKContext:e}}exports.ApiDomainError=T;exports.DeleteApi=dt;exports.GetApi=ct;exports.PatchApi=ft;exports.PostApi=ht;exports.PutApi=lt;exports.buildUrlPath=et;exports.createSDK=rt;exports.createSDKContext=Wt;exports.createSDKMutationHook=at;exports.createSDKProvider=Vt;exports.createSDKProviderWithFactory=Jt;exports.createSDKQueryHook=ot;exports.defaultExtractApiError=tt;exports.defaultTransformResponse=st; |
@@ -1,2 +0,3 @@ | ||
| import { CreateRequestFunctionConfig, EndpointSpec, SdkRequestOptions } from './types'; | ||
| import { CreateRequestFunctionConfig, SdkRequestOptions } from './types'; | ||
| import { EndpointSpec } from './endpointSpec'; | ||
| /** | ||
@@ -3,0 +4,0 @@ * Default response transformer |
@@ -1,3 +0,4 @@ | ||
| import { EndpointSpec, SdkRequestOptions } from './types'; | ||
| import { SdkRequestOptions } from './types'; | ||
| import { ApiErrorDetails } from './ApiDomainError'; | ||
| import { EndpointSpec } from './endpointSpec'; | ||
| export { ApiDomainError, type ApiErrorDetails } from './ApiDomainError'; | ||
@@ -4,0 +5,0 @@ export interface CreateSDKConfig<TApiSpecs extends Record<string, EndpointSpec>> { |
| import { default as React } from 'react'; | ||
| import { ApiErrorDetails, SdkMethods } from './createSDK'; | ||
| import { EndpointSpec } from './types'; | ||
| import { EndpointSpec } from './endpointSpec'; | ||
| export interface CreateSDKProviderConfig<TApiSpecs extends Record<string, EndpointSpec>> { | ||
@@ -31,7 +31,7 @@ apiSpecs: TApiSpecs; | ||
| */ | ||
| readonly useQuery: <K extends keyof TApiSpecs>(endpoint: K, options?: import('./useSDKQuery').SDKQueryOptions<SdkMethods<TApiSpecs>, K> | undefined) => import('@tanstack/react-query').UseQueryResult<import('./types').EndpointResponse<SdkMethods<TApiSpecs>, K>, import('apps/rab-react-sdk/src/lib/ApiDomainError').ApiDomainError>; | ||
| readonly useQuery: <K extends keyof TApiSpecs>(endpoint: K, options?: import('./useSDKQuery').SDKQueryOptions<SdkMethods<TApiSpecs>, K> | undefined) => import('@tanstack/react-query').UseQueryResult<import('apps/rab-react-sdk/src').EndpointResponse<SdkMethods<TApiSpecs>, K>, import('apps/rab-react-sdk/src/lib/ApiDomainError').ApiDomainError>; | ||
| /** | ||
| * Hook for mutations (POST/PUT/DELETE requests) | ||
| */ | ||
| readonly useMutation: <K_1 extends keyof TApiSpecs>(endpoint: K_1, options?: import('./useSDKMutation').SDKMutationOptions<SdkMethods<TApiSpecs>, K_1> | undefined) => import('@tanstack/react-query').UseMutationResult<import('./types').EndpointResponse<SdkMethods<TApiSpecs>, K_1>, import('apps/rab-react-sdk/src/lib/ApiDomainError').ApiDomainError, import('./useSDKMutation').SDKMutationVariables<SdkMethods<TApiSpecs>, K_1>, unknown>; | ||
| readonly useMutation: <K_1 extends keyof TApiSpecs>(endpoint: K_1, options?: import('./useSDKMutation').SDKMutationOptions<SdkMethods<TApiSpecs>, K_1> | undefined) => import('@tanstack/react-query').UseMutationResult<import('apps/rab-react-sdk/src').EndpointResponse<SdkMethods<TApiSpecs>, K_1>, import('apps/rab-react-sdk/src/lib/ApiDomainError').ApiDomainError, import('./useSDKMutation').SDKMutationVariables<SdkMethods<TApiSpecs>, K_1>, unknown>; | ||
| /** | ||
@@ -38,0 +38,0 @@ * The React context (rarely needed directly) |
@@ -1,2 +0,1 @@ | ||
| import { EndpointSpec } from './types'; | ||
| /** | ||
@@ -9,33 +8,10 @@ * Create a GET endpoint specification | ||
| */ | ||
| export declare function GetApi<RESPONSE = any, QUERY = unknown, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, unknown, QUERY, PARAMS>; | ||
| /** | ||
| * Create a POST endpoint specification | ||
| * @param url - The endpoint URL path (supports :paramName placeholders) | ||
| * @template RESPONSE - The response type | ||
| * @template BODY - The request body type | ||
| * @template PARAMS - The URL path parameters type (optional) | ||
| */ | ||
| export declare function PostApi<RESPONSE = any, BODY = any, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, BODY, unknown, PARAMS>; | ||
| /** | ||
| * Create a PUT endpoint specification | ||
| * @param url - The endpoint URL path (supports :paramName placeholders) | ||
| * @template RESPONSE - The response type | ||
| * @template BODY - The request body type | ||
| * @template PARAMS - The URL path parameters type (optional) | ||
| */ | ||
| export declare function PutApi<RESPONSE = any, BODY = any, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, BODY, unknown, PARAMS>; | ||
| /** | ||
| * Create a PATCH endpoint specification | ||
| * @param url - The endpoint URL path (supports :paramName placeholders) | ||
| * @template RESPONSE - The response type | ||
| * @template BODY - The request body type | ||
| * @template PARAMS - The URL path parameters type (optional) | ||
| */ | ||
| export declare function PatchApi<RESPONSE = any, BODY = any, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, BODY, unknown, PARAMS>; | ||
| /** | ||
| * Create a DELETE endpoint specification | ||
| * @param url - The endpoint URL path (supports :paramName placeholders) | ||
| * @template RESPONSE - The response type | ||
| * @template PARAMS - The URL path parameters type (optional) | ||
| */ | ||
| export interface EndpointSpec<RESPONSE = unknown, BODY = unknown, QUERY = unknown, PARAMS = unknown> { | ||
| url: string; | ||
| method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; | ||
| } | ||
| export declare function GetApi<RESPONSE = unknown, QUERY = unknown, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, unknown, QUERY, PARAMS>; | ||
| export declare function PostApi<RESPONSE = unknown, BODY = unknown, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, BODY, unknown, PARAMS>; | ||
| export declare function PutApi<RESPONSE = unknown, BODY = unknown, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, BODY, unknown, PARAMS>; | ||
| export declare function PatchApi<RESPONSE = unknown, BODY = unknown, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, BODY, unknown, PARAMS>; | ||
| export declare function DeleteApi<RESPONSE = void, PARAMS = unknown>(url: string): EndpointSpec<RESPONSE, unknown, unknown, PARAMS>; |
+0
-7
@@ -104,9 +104,2 @@ import { ApiErrorDetails } from './ApiDomainError'; | ||
| } | ||
| /** | ||
| * Endpoint specification | ||
| */ | ||
| export interface EndpointSpec<RESPONSE = any, BODY = any, QUERY = any, PARAMS = any> { | ||
| url: string; | ||
| method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; | ||
| } | ||
| export {}; |
+6
-6
| { | ||
| "name": "@rabstack/rab-react-sdk", | ||
| "version": "0.1.1", | ||
| "version": "0.1.2", | ||
| "description": "React SDK for building applications with React Query and other utilities", | ||
@@ -24,4 +24,4 @@ "keywords": [ | ||
| "type": "module", | ||
| "main": "./index.js", | ||
| "module": "./index.mjs", | ||
| "main": "./index.cjs", | ||
| "module": "./index.js", | ||
| "types": "./index.d.ts", | ||
@@ -31,4 +31,4 @@ "exports": { | ||
| "types": "./index.d.ts", | ||
| "import": "./index.mjs", | ||
| "require": "./index.js" | ||
| "import": "./index.js", | ||
| "require": "./index.cjs" | ||
| } | ||
@@ -39,3 +39,3 @@ }, | ||
| "index.js", | ||
| "index.mjs", | ||
| "index.cjs", | ||
| "lib", | ||
@@ -42,0 +42,0 @@ "README.md" |
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
73815
41.53%15
7.14%1640
3.67%3
50%16
77.78%10
100%