@nizza/core 0.4.3 → 0.4.4

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.cjs CHANGED
@@ -20,7 +20,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
20
20
  account: env.account,
21
21
  ...
22
22
  });
23
- `)}}const Es=["account"];function Ke(){Es.forEach(e=>{if(e===void 0)throw new Da(e)})}class ws{constructor(){C(this,"_config",null);C(this,"_account");ss(this,{},{name:"NizzaConfigManager",autoBind:!0})}async configure(t){var i;if(this._config=t,((i=this.account)==null?void 0:i.account)!==t.account){const n=await Xa(t.account);this.setAccount(n)}}get config(){return Ke(),this._config}get account(){return Ke(),this._account}get ok(){var t;return Ke(),!!((t=this._account)!=null&&t.account)}get accountName(){var t;return Ke(),(t=this._account)==null?void 0:t.account}setAccount(t){this._account=t}}class As{constructor(){C(this,"channel");C(this,"listeners",new Map);C(this,"eventQueue",new Map);try{this.channel=new BroadcastChannel("nizza"),this.channel.onmessage=t=>this.handleMessage(t),this.channel.onmessageerror=t=>Ce.error("NizzaBroadcastChannel:",t)}catch(t){throw Ce.error("Failed to create NizzaBroadcastChannel:",t),t}}on(t,i){return this.subscribeToEvent(t,i),{off:()=>this.unsubscribeFromEvent(t,i)}}emit(t,i,n={}){this.emitEvent(t,i,n)}handleMessage(t){const i=t.data,{name:n}=i;for(const[a,r]of this.listeners.entries())this.matchWildcard(a,n)&&r.forEach(o=>o({...i,wildcard:a}))}subscribeToEvent(t,i){if(typeof t!="string"||typeof i!="function"){const n=new Error("Invalid arguments");throw Ce.error(n),n}for(const[n,a]of this.listeners.entries())if(this.matchWildcard(n,t)){a.add(i);const r=this.eventQueue.get(n);r&&(r.forEach(o=>{i({...o,wildcard:n})}),this.eventQueue.delete(n));return}this.listeners.set(t,new Set([i]))}emitEvent(t,i,n){if(typeof t!="string"){const o=new Error("Invalid arguments");throw Ce.error(o),o}const a={name:t,data:i,attrs:n},r=Array.from(this.getMatchingListeners(t));if(r.length)for(const[o,s]of r)s({...a,wildcard:o});else this.eventQueue.has(t)||this.eventQueue.set(t,[]),this.eventQueue.get(t).push(a);this.channel.postMessage(a)}*getMatchingListeners(t){for(const[i,n]of this.listeners.entries())if(this.matchWildcard(i,t))for(const a of n)yield[i,a]}unsubscribeFromEvent(t,i){if(this.listeners.has(t)){const n=this.listeners.get(t);n.delete(i),n.size===0&&this.listeners.delete(t)}}matchWildcard(t,i){const n=t.replace(/\*/g,"[^:]*").replace(/\*\*/g,".*");return new RegExp(`^${n}$`).test(i)}}const oe=class{constructor(){C(this,"_productDataSource",null);C(this,"_configManager",new ws);C(this,"_eventBus",new As);C(this,"instanceId",Ca());C(this,"log",Ir);os(this,{config:fe,account:fe,ok:fe,accountName:fe,configure:me},{name:"NizzaStore",autoBind:!0})}static instance(){return oe._instance||(oe._instance=new oe),window!=null&&window.nizza?oe._instance=window==null?void 0:window.nizza:(window.nizza=oe._instance,window.nz=oe._instance),oe._instance}async configure(t){return await this._configManager.configure(t),this}get config(){return this._configManager.config}get account(){return this._configManager.account}get ok(){return this._configManager.ok}get accountName(){return this._configManager.accountName}get productDataSource(){return Ke(),this._productDataSource}get eventBus(){return this._eventBus}setProductDataSource(t){this._productDataSource=t}};let Je=oe;C(Je,"_instance");const On=Je.instance(),ht=On.log,xa=ht.levels.INFO;ht.setDefaultLevel(xa);Fi.reg(ht);Fi.apply(ht,{template:"[%t] %l (%n)",nameFormatter:e=>{var t;return(t=e==null?void 0:e.toLowerCase())!=null?t:""},timestampFormatter:()=>new Date().toTimeString().slice(0,8)});const Pa={},Fs=En("main"),Ce=En("core");function La(e){const t=ht.getLogger(e);return t.setLevel(xa),t}function Ia(e,t){Pa[e]=t}function Va(e){return Pa[e]}function En(e){const t=La(e);return Ia(e,t),Va(e)}function Cs(){var n,a,r;let e=null,t=null,i=null;try{e=(r=(a=(n=Intl.DateTimeFormat())==null?void 0:n.resolvedOptions())==null?void 0:a.timeZone)!=null?r:null;const o=-new Date().getTimezoneOffset();i=o;const s=o>=0?"+":"-",u=String(Math.floor(Math.abs(o)/60)).padStart(2,"0"),l=String(Math.abs(o)%60).padStart(2,"0");t=`${s}${u}:${l}`}catch{Ce.error("Error obtaining time zone or offset")}return{offset:t,offsetValue:i,value:e,country:null,included:null,label:null}}class ja{constructor(t){C(this,"aggregate");C(this,"_numSetPropsApplied",0);this.aggregate=t}setProps(t){for(const[i,n]of Object.entries(t))i in this.aggregate&&(this.aggregate[i]=n);this._numSetPropsApplied++}get isFirstSetProps(){return this._numSetPropsApplied===1}}function Ua(e){return new ja(e)}class Rs{}class Ts{constructor(t){C(this,"_value");t!==void 0&&(this._value=t)}get value(){return this._value}}var wn=(e=>(e.VTEX="VTEX",e.VTEX_IO="VTEX-IO",e.VTEX_CMS="PORTAL-VTEX",e.PLATFORM="PLATFORM",e.UNKNOWN="UNKNOWN",e))(wn||{}),Ma=(e=>(e.PLATFORM="platform_module",e.ADENDA="subscription_module",e.APP_STORE="app_store",e))(Ma||{}),An=(e=>(e.ACTIVE="active_contract",e.INACTIVE="inactive_contract",e))(An||{}),Ba=(e=>(e.LITE="lite",e.STANDARD="standard",e.PRO="pro",e))(Ba||{}),za=(e=>(e.LITE="PLAN_LITE",e.STANDARD="PLAN_ESTANDAR",e.PRO="PLAN_PRO",e.NONE="NO_PLAN",e))(za||{}),Ga=(e=>(e.PAST="past",e.LIVE="live",e.FUTURE="future",e))(Ga||{});class Mt{constructor(t){C(this,"root",Ua(this));C(this,"id");C(this,"account");C(this,"accountType",wn.UNKNOWN);C(this,"username");C(this,"currencyConfig");C(this,"contractType");C(this,"nextDateMetricRecord");C(this,"spendedMinutes",0);C(this,"unlimitedService",!1);C(this,"hoursAvailable",0);C(this,"contractStatus",An.ACTIVE);C(this,"createdAt");C(this,"installationDateApp");C(this,"cxAccount");C(this,"freeService",!1);C(this,"subscriptionType",null);C(this,"minutesAvailable",0);C(this,"globalPage");C(this,"stripe");C(this,"descriptionPlan");C(this,"planType");C(this,"selectFreeTrial");C(this,"exceededFeatures");C(this,"host",null);this.root.setProps(t)}static toDomain(t){const{createdAt:i,...n}=t,a={...n,createdAt:new Date(Number(i))};return new Mt(a)}toPrimitives(){const{root:t,createdAt:i,...n}=this;return{...n,created:i.toISOString()}}}const Ds=`${Tr.apiUrls.restV1}/accounts/v2`;class $a{async get(t){const i=`${Ds}/${t}`,{data:n}=await mn({url:i});return n?Mt.toDomain(n):null}}class Ka{constructor(t){this.accountRepository=t}async get(t){try{const i=await this.accountRepository.get(t);if(!i)throw new Ra(t);return i}catch(i){throw new Ta(i)}}}const xs=new $a,Fn=new Ka(xs);class Cn{constructor(){this.listeners=[],this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.push(t),this.onSubscribe(),()=>{this.listeners=this.listeners.filter(i=>i!==t),this.onUnsubscribe()}}hasListeners(){return this.listeners.length>0}onSubscribe(){}onUnsubscribe(){}}const Tt=typeof window=="undefined"||"Deno"in window;function Ps(){}function ei(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ls(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Is(e,t,i){return Vs(e)?typeof t=="function"?{...i,queryKey:e,queryFn:t}:{...t,queryKey:e}:e}function Qa(e,t){if(e===t)return e;const i=ni(e)&&ni(t);if(i||ii(e)&&ii(t)){const n=i?e.length:Object.keys(e).length,a=i?t:Object.keys(t),r=a.length,o=i?[]:{};let s=0;for(let u=0;u<r;u++){const l=i?u:a[u];o[l]=Qa(e[l],t[l]),o[l]===e[l]&&s++}return n===r&&s===n?e:o}return t}function ti(e,t){if(e&&!t||t&&!e)return!1;for(const i in e)if(e[i]!==t[i])return!1;return!0}function ni(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ii(e){if(!ai(e))return!1;const t=e.constructor;if(typeof t=="undefined")return!0;const i=t.prototype;return!(!ai(i)||!i.hasOwnProperty("isPrototypeOf"))}function ai(e){return Object.prototype.toString.call(e)==="[object Object]"}function Vs(e){return Array.isArray(e)}function js(e){return new Promise(t=>{setTimeout(t,e)})}function ri(e){js(0).then(e)}function oi(e,t,i){return i.isDataEqual!=null&&i.isDataEqual(e,t)?e:typeof i.structuralSharing=="function"?i.structuralSharing(e,t):i.structuralSharing!==!1?Qa(e,t):t}class Us extends Cn{constructor(){super(),this.setup=t=>{if(!Tt&&window.addEventListener){const i=()=>t();return window.addEventListener("visibilitychange",i,!1),window.addEventListener("focus",i,!1),()=>{window.removeEventListener("visibilitychange",i),window.removeEventListener("focus",i)}}}}onSubscribe(){this.cleanup||this.setEventListener(this.setup)}onUnsubscribe(){if(!this.hasListeners()){var t;(t=this.cleanup)==null||t.call(this),this.cleanup=void 0}}setEventListener(t){var i;this.setup=t,(i=this.cleanup)==null||i.call(this),this.cleanup=t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()})}setFocused(t){this.focused=t,t&&this.onFocus()}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){return typeof this.focused=="boolean"?this.focused:typeof document=="undefined"?!0:[void 0,"visible","prerender"].includes(document.visibilityState)}}const Ms=new Us;class Bs extends Cn{constructor(){super(),this.setup=t=>{if(!Tt&&window.addEventListener){const i=()=>t();return window.addEventListener("online",i,!1),window.addEventListener("offline",i,!1),()=>{window.removeEventListener("online",i),window.removeEventListener("offline",i)}}}}onSubscribe(){this.cleanup||this.setEventListener(this.setup)}onUnsubscribe(){if(!this.hasListeners()){var t;(t=this.cleanup)==null||t.call(this),this.cleanup=void 0}}setEventListener(t){var i;this.setup=t,(i=this.cleanup)==null||i.call(this),this.cleanup=t(n=>{typeof n=="boolean"?this.setOnline(n):this.onOnline()})}setOnline(t){this.online=t,t&&this.onOnline()}onOnline(){this.listeners.forEach(t=>{t()})}isOnline(){return typeof this.online=="boolean"?this.online:typeof navigator=="undefined"||typeof navigator.onLine=="undefined"?!0:navigator.onLine}}const zs=new Bs;function Gs(e){return(e!=null?e:"online")==="online"?zs.isOnline():!0}class $s{constructor(t){this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}}function Ks(e){return e instanceof $s}function Qs(){let e=[],t=0,i=d=>{d()},n=d=>{d()};const a=d=>{let c;t++;try{c=d()}finally{t--,t||s()}return c},r=d=>{t?e.push(d):ri(()=>{i(d)})},o=d=>(...c)=>{r(()=>{d(...c)})},s=()=>{const d=e;e=[],d.length&&ri(()=>{n(()=>{d.forEach(c=>{i(c)})})})};return{batch:a,batchCalls:o,schedule:r,setNotifyFunction:d=>{i=d},setBatchNotifyFunction:d=>{n=d}}}const Qe=Qs();class Ws extends Cn{constructor(t,i){super(),this.client=t,this.options=i,this.trackedProps=new Set,this.selectError=null,this.bindMethods(),this.setOptions(i)}bindMethods(){this.remove=this.remove.bind(this),this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.length===1&&(this.currentQuery.addObserver(this),si(this.currentQuery,this.options)&&this.executeFetch(),this.updateTimers())}onUnsubscribe(){this.listeners.length||this.destroy()}shouldFetchOnReconnect(){return dn(this.currentQuery,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dn(this.currentQuery,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=[],this.clearStaleTimeout(),this.clearRefetchInterval(),this.currentQuery.removeObserver(this)}setOptions(t,i){const n=this.options,a=this.currentQuery;if(this.options=this.client.defaultQueryOptions(t),ti(n,this.options)||this.client.getQueryCache().notify({type:"observerOptionsUpdated",query:this.currentQuery,observer:this}),typeof this.options.enabled!="undefined"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=n.queryKey),this.updateQuery();const r=this.hasListeners();r&&ui(this.currentQuery,a,this.options,n)&&this.executeFetch(),this.updateResult(i),r&&(this.currentQuery!==a||this.options.enabled!==n.enabled||this.options.staleTime!==n.staleTime)&&this.updateStaleTimeout();const o=this.computeRefetchInterval();r&&(this.currentQuery!==a||this.options.enabled!==n.enabled||o!==this.currentRefetchInterval)&&this.updateRefetchInterval(o)}getOptimisticResult(t){const i=this.client.getQueryCache().build(this.client,t);return this.createResult(i,t)}getCurrentResult(){return this.currentResult}trackResult(t){const i={};return Object.keys(t).forEach(n=>{Object.defineProperty(i,n,{configurable:!1,enumerable:!0,get:()=>(this.trackedProps.add(n),t[n])})}),i}getCurrentQuery(){return this.currentQuery}remove(){this.client.getQueryCache().remove(this.currentQuery)}refetch({refetchPage:t,...i}={}){return this.fetch({...i,meta:{refetchPage:t}})}fetchOptimistic(t){const i=this.client.defaultQueryOptions(t),n=this.client.getQueryCache().build(this.client,i);return n.isFetchingOptimistic=!0,n.fetch().then(()=>this.createResult(n,i))}fetch(t){var i;return this.executeFetch({...t,cancelRefetch:(i=t.cancelRefetch)!=null?i:!0}).then(()=>(this.updateResult(),this.currentResult))}executeFetch(t){this.updateQuery();let i=this.currentQuery.fetch(this.options,t);return t!=null&&t.throwOnError||(i=i.catch(Ps)),i}updateStaleTimeout(){if(this.clearStaleTimeout(),Tt||this.currentResult.isStale||!ei(this.options.staleTime))return;const i=Ls(this.currentResult.dataUpdatedAt,this.options.staleTime)+1;this.staleTimeoutId=setTimeout(()=>{this.currentResult.isStale||this.updateResult()},i)}computeRefetchInterval(){var t;return typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.currentResult.data,this.currentQuery):(t=this.options.refetchInterval)!=null?t:!1}updateRefetchInterval(t){this.clearRefetchInterval(),this.currentRefetchInterval=t,!(Tt||this.options.enabled===!1||!ei(this.currentRefetchInterval)||this.currentRefetchInterval===0)&&(this.refetchIntervalId=setInterval(()=>{(this.options.refetchIntervalInBackground||Ms.isFocused())&&this.executeFetch()},this.currentRefetchInterval))}updateTimers(){this.updateStaleTimeout(),this.updateRefetchInterval(this.computeRefetchInterval())}clearStaleTimeout(){this.staleTimeoutId&&(clearTimeout(this.staleTimeoutId),this.staleTimeoutId=void 0)}clearRefetchInterval(){this.refetchIntervalId&&(clearInterval(this.refetchIntervalId),this.refetchIntervalId=void 0)}createResult(t,i){const n=this.currentQuery,a=this.options,r=this.currentResult,o=this.currentResultState,s=this.currentResultOptions,u=t!==n,l=u?t.state:this.currentQueryInitialState,d=u?this.currentResult:this.previousQueryResult,{state:c}=t;let{dataUpdatedAt:p,error:g,errorUpdatedAt:S,fetchStatus:v,status:m}=c,y=!1,N=!1,A;if(i._optimisticResults){const f=this.hasListeners(),h=!f&&si(t,i),k=f&&ui(t,n,i,a);(h||k)&&(v=Gs(t.options.networkMode)?"fetching":"paused",p||(m="loading")),i._optimisticResults==="isRestoring"&&(v="idle")}if(i.keepPreviousData&&!c.dataUpdatedAt&&d!=null&&d.isSuccess&&m!=="error")A=d.data,p=d.dataUpdatedAt,m=d.status,y=!0;else if(i.select&&typeof c.data!="undefined")if(r&&c.data===(o==null?void 0:o.data)&&i.select===this.selectFn)A=this.selectResult;else try{this.selectFn=i.select,A=i.select(c.data),A=oi(r==null?void 0:r.data,A,i),this.selectResult=A,this.selectError=null}catch(f){this.selectError=f}else A=c.data;if(typeof i.placeholderData!="undefined"&&typeof A=="undefined"&&m==="loading"){let f;if(r!=null&&r.isPlaceholderData&&i.placeholderData===(s==null?void 0:s.placeholderData))f=r.data;else if(f=typeof i.placeholderData=="function"?i.placeholderData():i.placeholderData,i.select&&typeof f!="undefined")try{f=i.select(f),this.selectError=null}catch(h){this.selectError=h}typeof f!="undefined"&&(m="success",A=oi(r==null?void 0:r.data,f,i),N=!0)}this.selectError&&(g=this.selectError,A=this.selectResult,S=Date.now(),m="error");const O=v==="fetching",T=m==="loading",L=m==="error";return{status:m,fetchStatus:v,isLoading:T,isSuccess:m==="success",isError:L,isInitialLoading:T&&O,data:A,dataUpdatedAt:p,error:g,errorUpdatedAt:S,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>l.dataUpdateCount||c.errorUpdateCount>l.errorUpdateCount,isFetching:O,isRefetching:O&&!T,isLoadingError:L&&c.dataUpdatedAt===0,isPaused:v==="paused",isPlaceholderData:N,isPreviousData:y,isRefetchError:L&&c.dataUpdatedAt!==0,isStale:Rn(t,i),refetch:this.refetch,remove:this.remove}}updateResult(t){const i=this.currentResult,n=this.createResult(this.currentQuery,this.options);if(this.currentResultState=this.currentQuery.state,this.currentResultOptions=this.options,ti(n,i))return;this.currentResult=n;const a={cache:!0},r=()=>{if(!i)return!0;const{notifyOnChangeProps:o}=this.options;if(o==="all"||!o&&!this.trackedProps.size)return!0;const s=new Set(o!=null?o:this.trackedProps);return this.options.useErrorBoundary&&s.add("error"),Object.keys(this.currentResult).some(u=>{const l=u;return this.currentResult[l]!==i[l]&&s.has(l)})};(t==null?void 0:t.listeners)!==!1&&r()&&(a.listeners=!0),this.notify({...a,...t})}updateQuery(){const t=this.client.getQueryCache().build(this.client,this.options);if(t===this.currentQuery)return;const i=this.currentQuery;this.currentQuery=t,this.currentQueryInitialState=t.state,this.previousQueryResult=this.currentResult,this.hasListeners()&&(i==null||i.removeObserver(this),t.addObserver(this))}onQueryUpdate(t){const i={};t.type==="success"?i.onSuccess=!t.manual:t.type==="error"&&!Ks(t.error)&&(i.onError=!0),this.updateResult(i),this.hasListeners()&&this.updateTimers()}notify(t){Qe.batch(()=>{if(t.onSuccess){var i,n,a,r;(i=(n=this.options).onSuccess)==null||i.call(n,this.currentResult.data),(a=(r=this.options).onSettled)==null||a.call(r,this.currentResult.data,null)}else if(t.onError){var o,s,u,l;(o=(s=this.options).onError)==null||o.call(s,this.currentResult.error),(u=(l=this.options).onSettled)==null||u.call(l,void 0,this.currentResult.error)}t.listeners&&this.listeners.forEach(d=>{d(this.currentResult)}),t.cache&&this.client.getQueryCache().notify({query:this.currentQuery,type:"observerResultsUpdated"})})}}function qs(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function si(e,t){return qs(e,t)||e.state.dataUpdatedAt>0&&dn(e,t,t.refetchOnMount)}function dn(e,t,i){if(t.enabled!==!1){const n=typeof i=="function"?i(e):i;return n==="always"||n!==!1&&Rn(e,t)}return!1}function ui(e,t,i,n){return i.enabled!==!1&&(e!==t||n.enabled===!1)&&(!i.suspense||e.state.status!=="error")&&Rn(e,i)}function Rn(e,t){return e.isStaleByTime(t.staleTime)}var Wa={exports:{}},qa={};/**
23
+ `)}}const Es=["account"];function Ke(){Es.forEach(e=>{if(e===void 0)throw new Da(e)})}class ws{constructor(){C(this,"_config",null);C(this,"_account");ss(this,{},{name:"NizzaConfigManager",autoBind:!0})}async configure(t){var i;if(this._config=t,((i=this.account)==null?void 0:i.account)!==t.account){const n=await Xa(t.account);this.setAccount(n)}}get config(){return Ke(),this._config}get account(){return Ke(),this._account}get ok(){var t;return Ke(),!!((t=this._account)!=null&&t.account)}get accountName(){var t;return Ke(),(t=this._account)==null?void 0:t.account}setAccount(t){this._account=t}}class As{constructor(){C(this,"channel");C(this,"listeners",new Map);C(this,"eventQueue",new Map);try{this.channel=new BroadcastChannel("nizza"),this.channel.onmessage=t=>this.handleMessage(t),this.channel.onmessageerror=t=>Ce.error("NizzaBroadcastChannel:",t)}catch(t){throw Ce.error("Failed to create NizzaBroadcastChannel:",t),t}}on(t,i){return this.subscribeToEvent(t,i),{off:()=>this.unsubscribeFromEvent(t,i)}}emit(t,i,n={}){this.emitEvent(t,i,n)}handleMessage(t){const i=t.data,{name:n}=i;for(const[a,r]of this.listeners.entries())this.matchWildcard(a,n)&&r.forEach(o=>o({...i,wildcard:a}))}subscribeToEvent(t,i){if(typeof t!="string"||typeof i!="function"){const n=new Error("Invalid arguments");throw Ce.error(n),n}for(const[n,a]of this.listeners.entries())if(this.matchWildcard(n,t)){a.add(i);const r=this.eventQueue.get(n);r&&(r.forEach(o=>{i({...o,wildcard:n})}),this.eventQueue.delete(n));return}this.listeners.set(t,new Set([i]))}emitEvent(t,i,n){if(typeof t!="string"){const o=new Error("Invalid arguments");throw Ce.error(o),o}const a={name:t,data:i,attrs:n},r=Array.from(this.getMatchingListeners(t));if(r.length)for(const[o,s]of r)s({...a,wildcard:o});else this.eventQueue.has(t)||this.eventQueue.set(t,[]),this.eventQueue.get(t).push(a);this.channel.postMessage(a)}*getMatchingListeners(t){for(const[i,n]of this.listeners.entries())if(this.matchWildcard(i,t))for(const a of n)yield[i,a]}unsubscribeFromEvent(t,i){if(this.listeners.has(t)){const n=this.listeners.get(t);n.delete(i),n.size===0&&this.listeners.delete(t)}}matchWildcard(t,i){const n=t.replace(/\*/g,"[^:]*").replace(/\*\*/g,".*");return new RegExp(`^${n}$`).test(i)}}const oe=class{constructor(){C(this,"_productDataSource",null);C(this,"_configManager",new ws);C(this,"_eventBus",new As);C(this,"instanceId",Ca());C(this,"log",Ir);os(this,{config:fe,account:fe,ok:fe,accountName:fe,configure:me},{name:"NizzaStore",autoBind:!0})}static instance(){return oe._instance||(oe._instance=new oe),window!=null&&window.nizza?oe._instance=window==null?void 0:window.nizza:(window.nizza=oe._instance,window.nz=oe._instance),oe._instance}async configure(t){return await this._configManager.configure(t),this}get config(){return this._configManager.config}get account(){return this._configManager.account}get ok(){return this._configManager.ok}get accountName(){return this._configManager.accountName}get productDataSource(){return Ke(),this._productDataSource}get eventBus(){return this._eventBus}setProductDataSource(t){this._productDataSource=t}};let Je=oe;C(Je,"_instance");const On=Je.instance(),ht=On.log,xa=ht.levels.INFO;ht.setDefaultLevel(xa);Fi.reg(ht);Fi.apply(ht,{template:"[%t] %l (%n)",nameFormatter:e=>{var t;return(t=e==null?void 0:e.toLowerCase())!=null?t:""},timestampFormatter:()=>new Date().toTimeString().slice(0,8)});const Pa={},Fs=En("main"),Ce=En("core");function La(e){const t=ht.getLogger(e);return t.setLevel(xa),t}function Ia(e,t){Pa[e]=t}function Va(e){return Pa[e]}function En(e){const t=La(e);return Ia(e,t),Va(e)}function Cs(){var n,a,r;let e=null,t=null,i=null;try{e=(r=(a=(n=Intl.DateTimeFormat())==null?void 0:n.resolvedOptions())==null?void 0:a.timeZone)!=null?r:null;const o=-new Date().getTimezoneOffset();i=o;const s=o>=0?"+":"-",u=String(Math.floor(Math.abs(o)/60)).padStart(2,"0"),l=String(Math.abs(o)%60).padStart(2,"0");t=`${s}${u}:${l}`}catch{Ce.error("Error obtaining time zone or offset")}return{offset:t,offsetValue:i,value:e,country:null,included:null,label:null}}class ja{constructor(t){C(this,"aggregate");C(this,"_numSetPropsApplied",0);this.aggregate=t}setProps(t){for(const[i,n]of Object.entries(t))i in this.aggregate&&(this.aggregate[i]=n);this._numSetPropsApplied++}get isFirstSetProps(){return this._numSetPropsApplied===1}}function Ua(e){return new ja(e)}class Rs{}class Ts{constructor(t){C(this,"_value");t!==void 0&&(this._value=t)}get value(){return this._value}}var wn=(e=>(e.VTEX="VTEX",e.VTEX_IO="VTEX-IO",e.VTEX_CMS="PORTAL-VTEX",e.PLATFORM="PLATFORM",e.UNKNOWN="UNKNOWN",e))(wn||{}),Ma=(e=>(e.PLATFORM="platform_module",e.ADENDA="subscription_module",e.APP_STORE="app_store",e))(Ma||{}),An=(e=>(e.ACTIVE="active_contract",e.INACTIVE="inactive_contract",e))(An||{}),Ba=(e=>(e.LITE="lite",e.STANDARD="standard",e.PRO="pro",e))(Ba||{}),za=(e=>(e.LITE="PLAN_LITE",e.STANDARD="PLAN_ESTANDAR",e.PRO="PLAN_PRO",e.NONE="NO_PLAN",e))(za||{}),Ga=(e=>(e.PAST="past",e.LIVE="live",e.FUTURE="future",e))(Ga||{});class Mt{constructor(t){C(this,"root",Ua(this));C(this,"id");C(this,"account");C(this,"accountType",wn.UNKNOWN);C(this,"username");C(this,"currencyConfig");C(this,"contractType");C(this,"nextDateMetricRecord");C(this,"spendedMinutes",0);C(this,"unlimitedService",!1);C(this,"hoursAvailable",0);C(this,"contractStatus",An.ACTIVE);C(this,"createdAt");C(this,"installationDateApp");C(this,"cxAccount");C(this,"freeService",!1);C(this,"subscriptionType",null);C(this,"minutesAvailable",0);C(this,"globalPage");C(this,"stripe");C(this,"descriptionPlan");C(this,"planType");C(this,"selectFreeTrial");C(this,"exceededFeatures");C(this,"host",null);this.root.setProps(t)}static toDomain(t){const{createdAt:i,username:n,...a}=t,r={...a,username:n!=null?n:a.account,createdAt:new Date(Number(i))};return new Mt(r)}toPrimitives(){const{root:t,createdAt:i,...n}=this;return{...n,created:i.toISOString()}}}const Ds=`${Tr.apiUrls.restV1}/accounts/v2`;class $a{async get(t){const i=`${Ds}/${t}`,{data:n}=await mn({url:i});return n?Mt.toDomain(n):null}}class Ka{constructor(t){this.accountRepository=t}async get(t){try{const i=await this.accountRepository.get(t);if(!i)throw new Ra(t);return i}catch(i){throw new Ta(i)}}}const xs=new $a,Fn=new Ka(xs);class Cn{constructor(){this.listeners=[],this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.push(t),this.onSubscribe(),()=>{this.listeners=this.listeners.filter(i=>i!==t),this.onUnsubscribe()}}hasListeners(){return this.listeners.length>0}onSubscribe(){}onUnsubscribe(){}}const Tt=typeof window=="undefined"||"Deno"in window;function Ps(){}function ei(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ls(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Is(e,t,i){return Vs(e)?typeof t=="function"?{...i,queryKey:e,queryFn:t}:{...t,queryKey:e}:e}function Qa(e,t){if(e===t)return e;const i=ni(e)&&ni(t);if(i||ii(e)&&ii(t)){const n=i?e.length:Object.keys(e).length,a=i?t:Object.keys(t),r=a.length,o=i?[]:{};let s=0;for(let u=0;u<r;u++){const l=i?u:a[u];o[l]=Qa(e[l],t[l]),o[l]===e[l]&&s++}return n===r&&s===n?e:o}return t}function ti(e,t){if(e&&!t||t&&!e)return!1;for(const i in e)if(e[i]!==t[i])return!1;return!0}function ni(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ii(e){if(!ai(e))return!1;const t=e.constructor;if(typeof t=="undefined")return!0;const i=t.prototype;return!(!ai(i)||!i.hasOwnProperty("isPrototypeOf"))}function ai(e){return Object.prototype.toString.call(e)==="[object Object]"}function Vs(e){return Array.isArray(e)}function js(e){return new Promise(t=>{setTimeout(t,e)})}function ri(e){js(0).then(e)}function oi(e,t,i){return i.isDataEqual!=null&&i.isDataEqual(e,t)?e:typeof i.structuralSharing=="function"?i.structuralSharing(e,t):i.structuralSharing!==!1?Qa(e,t):t}class Us extends Cn{constructor(){super(),this.setup=t=>{if(!Tt&&window.addEventListener){const i=()=>t();return window.addEventListener("visibilitychange",i,!1),window.addEventListener("focus",i,!1),()=>{window.removeEventListener("visibilitychange",i),window.removeEventListener("focus",i)}}}}onSubscribe(){this.cleanup||this.setEventListener(this.setup)}onUnsubscribe(){if(!this.hasListeners()){var t;(t=this.cleanup)==null||t.call(this),this.cleanup=void 0}}setEventListener(t){var i;this.setup=t,(i=this.cleanup)==null||i.call(this),this.cleanup=t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()})}setFocused(t){this.focused=t,t&&this.onFocus()}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){return typeof this.focused=="boolean"?this.focused:typeof document=="undefined"?!0:[void 0,"visible","prerender"].includes(document.visibilityState)}}const Ms=new Us;class Bs extends Cn{constructor(){super(),this.setup=t=>{if(!Tt&&window.addEventListener){const i=()=>t();return window.addEventListener("online",i,!1),window.addEventListener("offline",i,!1),()=>{window.removeEventListener("online",i),window.removeEventListener("offline",i)}}}}onSubscribe(){this.cleanup||this.setEventListener(this.setup)}onUnsubscribe(){if(!this.hasListeners()){var t;(t=this.cleanup)==null||t.call(this),this.cleanup=void 0}}setEventListener(t){var i;this.setup=t,(i=this.cleanup)==null||i.call(this),this.cleanup=t(n=>{typeof n=="boolean"?this.setOnline(n):this.onOnline()})}setOnline(t){this.online=t,t&&this.onOnline()}onOnline(){this.listeners.forEach(t=>{t()})}isOnline(){return typeof this.online=="boolean"?this.online:typeof navigator=="undefined"||typeof navigator.onLine=="undefined"?!0:navigator.onLine}}const zs=new Bs;function Gs(e){return(e!=null?e:"online")==="online"?zs.isOnline():!0}class $s{constructor(t){this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}}function Ks(e){return e instanceof $s}function Qs(){let e=[],t=0,i=d=>{d()},n=d=>{d()};const a=d=>{let c;t++;try{c=d()}finally{t--,t||s()}return c},r=d=>{t?e.push(d):ri(()=>{i(d)})},o=d=>(...c)=>{r(()=>{d(...c)})},s=()=>{const d=e;e=[],d.length&&ri(()=>{n(()=>{d.forEach(c=>{i(c)})})})};return{batch:a,batchCalls:o,schedule:r,setNotifyFunction:d=>{i=d},setBatchNotifyFunction:d=>{n=d}}}const Qe=Qs();class Ws extends Cn{constructor(t,i){super(),this.client=t,this.options=i,this.trackedProps=new Set,this.selectError=null,this.bindMethods(),this.setOptions(i)}bindMethods(){this.remove=this.remove.bind(this),this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.length===1&&(this.currentQuery.addObserver(this),si(this.currentQuery,this.options)&&this.executeFetch(),this.updateTimers())}onUnsubscribe(){this.listeners.length||this.destroy()}shouldFetchOnReconnect(){return dn(this.currentQuery,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dn(this.currentQuery,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=[],this.clearStaleTimeout(),this.clearRefetchInterval(),this.currentQuery.removeObserver(this)}setOptions(t,i){const n=this.options,a=this.currentQuery;if(this.options=this.client.defaultQueryOptions(t),ti(n,this.options)||this.client.getQueryCache().notify({type:"observerOptionsUpdated",query:this.currentQuery,observer:this}),typeof this.options.enabled!="undefined"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=n.queryKey),this.updateQuery();const r=this.hasListeners();r&&ui(this.currentQuery,a,this.options,n)&&this.executeFetch(),this.updateResult(i),r&&(this.currentQuery!==a||this.options.enabled!==n.enabled||this.options.staleTime!==n.staleTime)&&this.updateStaleTimeout();const o=this.computeRefetchInterval();r&&(this.currentQuery!==a||this.options.enabled!==n.enabled||o!==this.currentRefetchInterval)&&this.updateRefetchInterval(o)}getOptimisticResult(t){const i=this.client.getQueryCache().build(this.client,t);return this.createResult(i,t)}getCurrentResult(){return this.currentResult}trackResult(t){const i={};return Object.keys(t).forEach(n=>{Object.defineProperty(i,n,{configurable:!1,enumerable:!0,get:()=>(this.trackedProps.add(n),t[n])})}),i}getCurrentQuery(){return this.currentQuery}remove(){this.client.getQueryCache().remove(this.currentQuery)}refetch({refetchPage:t,...i}={}){return this.fetch({...i,meta:{refetchPage:t}})}fetchOptimistic(t){const i=this.client.defaultQueryOptions(t),n=this.client.getQueryCache().build(this.client,i);return n.isFetchingOptimistic=!0,n.fetch().then(()=>this.createResult(n,i))}fetch(t){var i;return this.executeFetch({...t,cancelRefetch:(i=t.cancelRefetch)!=null?i:!0}).then(()=>(this.updateResult(),this.currentResult))}executeFetch(t){this.updateQuery();let i=this.currentQuery.fetch(this.options,t);return t!=null&&t.throwOnError||(i=i.catch(Ps)),i}updateStaleTimeout(){if(this.clearStaleTimeout(),Tt||this.currentResult.isStale||!ei(this.options.staleTime))return;const i=Ls(this.currentResult.dataUpdatedAt,this.options.staleTime)+1;this.staleTimeoutId=setTimeout(()=>{this.currentResult.isStale||this.updateResult()},i)}computeRefetchInterval(){var t;return typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.currentResult.data,this.currentQuery):(t=this.options.refetchInterval)!=null?t:!1}updateRefetchInterval(t){this.clearRefetchInterval(),this.currentRefetchInterval=t,!(Tt||this.options.enabled===!1||!ei(this.currentRefetchInterval)||this.currentRefetchInterval===0)&&(this.refetchIntervalId=setInterval(()=>{(this.options.refetchIntervalInBackground||Ms.isFocused())&&this.executeFetch()},this.currentRefetchInterval))}updateTimers(){this.updateStaleTimeout(),this.updateRefetchInterval(this.computeRefetchInterval())}clearStaleTimeout(){this.staleTimeoutId&&(clearTimeout(this.staleTimeoutId),this.staleTimeoutId=void 0)}clearRefetchInterval(){this.refetchIntervalId&&(clearInterval(this.refetchIntervalId),this.refetchIntervalId=void 0)}createResult(t,i){const n=this.currentQuery,a=this.options,r=this.currentResult,o=this.currentResultState,s=this.currentResultOptions,u=t!==n,l=u?t.state:this.currentQueryInitialState,d=u?this.currentResult:this.previousQueryResult,{state:c}=t;let{dataUpdatedAt:p,error:g,errorUpdatedAt:S,fetchStatus:v,status:m}=c,y=!1,N=!1,A;if(i._optimisticResults){const f=this.hasListeners(),h=!f&&si(t,i),k=f&&ui(t,n,i,a);(h||k)&&(v=Gs(t.options.networkMode)?"fetching":"paused",p||(m="loading")),i._optimisticResults==="isRestoring"&&(v="idle")}if(i.keepPreviousData&&!c.dataUpdatedAt&&d!=null&&d.isSuccess&&m!=="error")A=d.data,p=d.dataUpdatedAt,m=d.status,y=!0;else if(i.select&&typeof c.data!="undefined")if(r&&c.data===(o==null?void 0:o.data)&&i.select===this.selectFn)A=this.selectResult;else try{this.selectFn=i.select,A=i.select(c.data),A=oi(r==null?void 0:r.data,A,i),this.selectResult=A,this.selectError=null}catch(f){this.selectError=f}else A=c.data;if(typeof i.placeholderData!="undefined"&&typeof A=="undefined"&&m==="loading"){let f;if(r!=null&&r.isPlaceholderData&&i.placeholderData===(s==null?void 0:s.placeholderData))f=r.data;else if(f=typeof i.placeholderData=="function"?i.placeholderData():i.placeholderData,i.select&&typeof f!="undefined")try{f=i.select(f),this.selectError=null}catch(h){this.selectError=h}typeof f!="undefined"&&(m="success",A=oi(r==null?void 0:r.data,f,i),N=!0)}this.selectError&&(g=this.selectError,A=this.selectResult,S=Date.now(),m="error");const O=v==="fetching",T=m==="loading",L=m==="error";return{status:m,fetchStatus:v,isLoading:T,isSuccess:m==="success",isError:L,isInitialLoading:T&&O,data:A,dataUpdatedAt:p,error:g,errorUpdatedAt:S,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>l.dataUpdateCount||c.errorUpdateCount>l.errorUpdateCount,isFetching:O,isRefetching:O&&!T,isLoadingError:L&&c.dataUpdatedAt===0,isPaused:v==="paused",isPlaceholderData:N,isPreviousData:y,isRefetchError:L&&c.dataUpdatedAt!==0,isStale:Rn(t,i),refetch:this.refetch,remove:this.remove}}updateResult(t){const i=this.currentResult,n=this.createResult(this.currentQuery,this.options);if(this.currentResultState=this.currentQuery.state,this.currentResultOptions=this.options,ti(n,i))return;this.currentResult=n;const a={cache:!0},r=()=>{if(!i)return!0;const{notifyOnChangeProps:o}=this.options;if(o==="all"||!o&&!this.trackedProps.size)return!0;const s=new Set(o!=null?o:this.trackedProps);return this.options.useErrorBoundary&&s.add("error"),Object.keys(this.currentResult).some(u=>{const l=u;return this.currentResult[l]!==i[l]&&s.has(l)})};(t==null?void 0:t.listeners)!==!1&&r()&&(a.listeners=!0),this.notify({...a,...t})}updateQuery(){const t=this.client.getQueryCache().build(this.client,this.options);if(t===this.currentQuery)return;const i=this.currentQuery;this.currentQuery=t,this.currentQueryInitialState=t.state,this.previousQueryResult=this.currentResult,this.hasListeners()&&(i==null||i.removeObserver(this),t.addObserver(this))}onQueryUpdate(t){const i={};t.type==="success"?i.onSuccess=!t.manual:t.type==="error"&&!Ks(t.error)&&(i.onError=!0),this.updateResult(i),this.hasListeners()&&this.updateTimers()}notify(t){Qe.batch(()=>{if(t.onSuccess){var i,n,a,r;(i=(n=this.options).onSuccess)==null||i.call(n,this.currentResult.data),(a=(r=this.options).onSettled)==null||a.call(r,this.currentResult.data,null)}else if(t.onError){var o,s,u,l;(o=(s=this.options).onError)==null||o.call(s,this.currentResult.error),(u=(l=this.options).onSettled)==null||u.call(l,void 0,this.currentResult.error)}t.listeners&&this.listeners.forEach(d=>{d(this.currentResult)}),t.cache&&this.client.getQueryCache().notify({query:this.currentQuery,type:"observerResultsUpdated"})})}}function qs(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function si(e,t){return qs(e,t)||e.state.dataUpdatedAt>0&&dn(e,t,t.refetchOnMount)}function dn(e,t,i){if(t.enabled!==!1){const n=typeof i=="function"?i(e):i;return n==="always"||n!==!1&&Rn(e,t)}return!1}function ui(e,t,i,n){return i.enabled!==!1&&(e!==t||n.enabled===!1)&&(!i.suspense||e.state.status!=="error")&&Rn(e,i)}function Rn(e,t){return e.isStaleByTime(t.staleTime)}var Wa={exports:{}},qa={};/**
24
24
  * @license React
25
25
  * use-sync-external-store-shim.production.min.js
26
26
  *
package/dist/index.mjs CHANGED
@@ -3465,11 +3465,12 @@ class Nn {
3465
3465
  this.root.setProps(t);
3466
3466
  }
3467
3467
  static toDomain(t) {
3468
- const { createdAt: i, ...n } = t, a = {
3469
- ...n,
3468
+ const { createdAt: i, username: n, ...a } = t, r = {
3469
+ ...a,
3470
+ username: n != null ? n : a.account,
3470
3471
  createdAt: new Date(Number(i))
3471
3472
  };
3472
- return new Nn(a);
3473
+ return new Nn(r);
3473
3474
  }
3474
3475
  toPrimitives() {
3475
3476
  const { root: t, createdAt: i, ...n } = this;
@@ -3,7 +3,6 @@ export interface BaseProps {
3
3
  id: string;
4
4
  account: string;
5
5
  accountType: AccountTypes;
6
- username: string;
7
6
  currencyConfig: AccountCurrencyConfig;
8
7
  contractType: AccountContractTypes;
9
8
  nextDateMetricRecord: string;
@@ -26,9 +25,11 @@ export interface BaseProps {
26
25
  }
27
26
  export type AccountProps = BaseProps & {
28
27
  createdAt: Date;
28
+ username: string;
29
29
  };
30
30
  export type RawAccount = BaseProps & {
31
31
  createdAt: string;
32
+ username?: string;
32
33
  };
33
34
  type StripeSubscriptionStatus = 'active' | 'canceled' | 'incomplete' | 'incomplete_expired' | 'past_due' | 'trialing' | 'unpaid';
34
35
  export interface AccountStripe {
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nizza/core",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/index.cjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nizza/core",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/index.cjs",