>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a>3,a-=k,c-=k<<3,f&=(1<{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg=\"\",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavexe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg=\"incorrect header check\",a.mode=me;break}if((15&h)!==we){t.msg=\"unknown compression method\",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg=\"invalid window size\",a.mode=me;break}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=N(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=N(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg=\"invalid block type\",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg=\"invalid stored block lengths\",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg=\"too many length or distance symbols\",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid code lengths set\",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg=\"invalid bit length repeat\",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg=\"invalid bit length repeat\",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg=\"invalid code -- missing end-of-block\",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid literal/lengths set\",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg=\"invalid distances set\",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg=\"invalid literal/length code\",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg=\"invalid distance code\",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg=\"invalid distance too far back\",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg=\"invalid distance too far back\",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=F(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var Se=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Te,Z_FINISH:Oe,Z_OK:Fe,Z_STREAM_END:Le,Z_NEED_DICT:Ne,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Tt({chunkSize:65536,windowBits:15,to:\"\"},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ue.inflateInit2(this.strm,e.windowBits);if(a!==Fe)throw new Error(I[a]);if(this.header=new Se,Ue.inflateGetHeader(this.strm,this.header),e.dictionary&&(\"string\"==typeof e.dictionary?e.dictionary=Nt(e.dictionary):\"[object ArrayBuffer]\"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Ue.inflateSetDictionary(this.strm,e.dictionary),a!==Fe)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Oe:Te,\"[object ArrayBuffer]\"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Ue.inflate(a,r),s===Ne&&n&&(s=Ue.inflateSetDictionary(a,n),s===Fe?s=Ue.inflate(a,r):s===Be&&(s=Ne));a.avail_in>0&&s===Le&&a.state.wrap>0&&0!==t[a.next_in];)Ue.inflateReset(a),s=Ue.inflate(a,r);switch(s){case Ie:case Be:case Ne:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Le))if(\"string\"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Fe||0!==o){if(s===Le)return s=Ue.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Fe&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=je,Xe=B;const We=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const e=this._hasEvents?\",\":\"\";this.deflate.push(e+t,Xe.Z_SYNC_FLUSH),this._hasEvents=!0}finish(){if(this.deflate.push(\"]\",Xe.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this._init(),t}_init(){this._hasEvents=!1,this.deflate=new Ye,this.deflate.push(\"[\",Xe.Z_NO_FLUSH)}},qe={clear:()=>{We.clear()},addEvent:t=>We.addEvent(t),finish:()=>We.finish(),compress:t=>function(t){return Ge(t)}(t)};addEventListener(\"message\",(function(t){const e=t.data.method,a=t.data.id,i=t.data.arg;if(e in qe&&\"function\"==typeof qe[e])try{const t=qe[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n\nfunction e(){const e=new Blob([r]);return URL.createObjectURL(e)}\n\n/**\n * Log a message in debug mode, and add a breadcrumb when _experiment.traceInternals is enabled.\n */\nfunction logInfo(message, shouldAddBreadcrumb) {\n if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n addBreadcrumb(message);\n }\n}\n\n/**\n * Log a message, and add a breadcrumb in the next tick.\n * This is necessary when the breadcrumb may be added before the replay is initialized.\n */\nfunction logInfoNextTick(message, shouldAddBreadcrumb) {\n if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => {\n addBreadcrumb(message);\n }, 0);\n }\n}\n\nfunction addBreadcrumb(message) {\n const hub = getCurrentHub();\n hub.addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level: 'info',\n message,\n },\n { level: 'info' },\n );\n}\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nclass EventBufferSizeExceededError extends Error {\n constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nclass EventBufferArray {\n /** All the events that are buffered to be sent. */\n\n /** @inheritdoc */\n\n constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n get type() {\n return 'sync';\n }\n\n /** @inheritdoc */\n destroy() {\n this.events = [];\n }\n\n /** @inheritdoc */\n async addEvent(event) {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n finish() {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n clear() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass WorkerHandler {\n\n constructor(worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n ensureReady() {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }) => {\n if ((data ).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n destroy() {\n logInfo('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n postMessage(method, arg) {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }) => {\n const response = data ;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response );\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n _getAndIncrementId() {\n return this._id++;\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass EventBufferCompressionWorker {\n /** @inheritdoc */\n\n constructor(worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n get type() {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n ensureReady() {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n destroy() {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n addEvent(event) {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n finish() {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n clear() {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n void this._worker.postMessage('clear');\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n _sendEventToWorker(data) {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n async _finishRequest() {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nclass EventBufferProxy {\n\n constructor(worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n get type() {\n return this._used.type;\n }\n\n /** @inheritDoc */\n get hasEvents() {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n get hasCheckout() {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n set hasCheckout(value) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritDoc */\n destroy() {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n clear() {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n addEvent(event) {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n async finish() {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n ensureWorkerIsLoaded() {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n async _ensureWorkerIsLoaded() {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n logInfo('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n async _switchToCompressionWorker() {\n const { events, hasCheckout } = this._fallback;\n\n const addEventPromises = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n\n/**\n * Create an event buffer for replays.\n */\nfunction createEventBuffer({ useCompression }) {\n // eslint-disable-next-line no-restricted-globals\n if (useCompression && window.Worker) {\n try {\n const workerUrl = e();\n\n logInfo('[Replay] Using compression worker');\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n logInfo('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n }\n\n logInfo('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\n/** If sessionStorage is available. */\nfunction hasSessionStorage() {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nfunction clearSession(replay) {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession() {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch (e) {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nfunction isExpired(\n initialTime,\n expiry,\n targetTime = +new Date(),\n) {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n\n/**\n * Checks to see if session is expired\n */\nfunction isSessionExpired(session, timeouts, targetTime = +new Date()) {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, timeouts.maxSessionLife, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)\n );\n}\n\n/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nfunction isSampled(sampleRate) {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n\n/**\n * Save a session to session storage.\n */\nfunction saveSession(session) {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch (e) {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Get a session with defaults & applied sampling.\n */\nfunction makeSession(session) {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const shouldRefresh = typeof session.shouldRefresh === 'boolean' ? session.shouldRefresh : true;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n shouldRefresh,\n };\n}\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nfunction getSessionSampleType(sessionSampleRate, allowBuffering) {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nfunction createSession({ sessionSampleRate, allowBuffering, stickySession = false }) {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n\n/**\n * Fetches a session from storage\n */\nfunction fetchSession(traceInternals) {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) ;\n\n logInfoNextTick('[Replay] Loading existing session', traceInternals);\n\n return makeSession(sessionObj);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Get or create a session\n */\nfunction getSession({\n timeouts,\n currentSession,\n stickySession,\n sessionSampleRate,\n allowBuffering,\n traceInternals,\n}) {\n // If session exists and is passed, use it instead of always hitting session storage\n const session = currentSession || (stickySession && fetchSession(traceInternals));\n\n if (session) {\n // If there is a session, check if it is valid (e.g. \"last activity\" time\n // should be within the \"session idle time\", and \"session started\" time is\n // within \"max session time\").\n const isExpired = isSessionExpired(session, timeouts);\n\n if (!isExpired || (allowBuffering && session.shouldRefresh)) {\n return { type: 'saved', session };\n } else if (!session.shouldRefresh) {\n // This is the case if we have an error session that is completed\n // (=triggered an error). Session will continue as session-based replay,\n // and when this session is expired, it will not be renewed until user\n // reloads.\n const discardedSession = makeSession({ sampled: false });\n logInfoNextTick('[Replay] Session should not be refreshed', traceInternals);\n return { type: 'new', session: discardedSession };\n } else {\n logInfoNextTick('[Replay] Session has expired', traceInternals);\n }\n // Otherwise continue to create a new session\n }\n\n const newSession = createSession({\n stickySession,\n sessionSampleRate,\n allowBuffering,\n });\n logInfoNextTick('[Replay] Created new session', traceInternals);\n\n return { type: 'new', session: newSession };\n}\n\nfunction isCustomEvent(event) {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nasync function addEvent(\n replay,\n event,\n isCheckout,\n) {\n if (!replay.eventBuffer) {\n // This implies that `_isEnabled` is false\n return null;\n }\n\n if (replay.isPaused()) {\n // Do not add to event buffer when recording is paused\n return null;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return null;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.timeouts.maxSessionLife) {\n logInfo(\n `[Replay] Skipping event with timestamp ${timestampInMs} because it is after maxSessionLife`,\n replay.getOptions()._experiments.traceInternals,\n );\n return null;\n }\n\n try {\n if (isCheckout && replay.recordingMode === 'buffer') {\n replay.eventBuffer.clear();\n }\n\n if (isCheckout) {\n replay.eventBuffer.hasCheckout = true;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(error);\n await replay.stop({ reason });\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\nfunction maybeApplyCallback(\n event,\n callback,\n) {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error('[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...', error);\n return null;\n }\n\n return event;\n}\n\n/** If the event is an error event */\nfunction isErrorEvent(event) {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nfunction isReplayEvent(event) {\n return event.type === 'replay_event';\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleAfterSendEvent(replay) {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event, sendResponse) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay, event) {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id );\n }\n}\n\nfunction handleErrorEvent(replay, event) {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode === 'buffer' && event.tags && event.tags.replayId) {\n setTimeout(() => {\n // Capture current event buffer as new replay\n void replay.sendBufferedReplayOrFlush();\n });\n }\n}\n\nfunction isBaseTransportSend() {\n const client = getCurrentHub().getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send ).__sentry__baseTransport__ || false\n );\n}\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nfunction isRrwebError(event, hint) {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-ignore this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n // Check if any exception originates from rrweb\n return event.exception.values.some(exception => {\n if (!exception.stacktrace || !exception.stacktrace.frames || !exception.stacktrace.frames.length) {\n return false;\n }\n\n return exception.stacktrace.frames.some(frame => frame.filename && frame.filename.includes('/rrweb/src/'));\n });\n}\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nfunction shouldSampleForBufferEvent(replay, event) {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n\n/**\n * Returns a listener to be added to `addGlobalEventProcessor(listener)`.\n */\nfunction handleGlobalEventListener(\n replay,\n includeAfterSendEventHandling = false,\n) {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return (event, hint) => {\n // Do nothing if replay has been disabled\n if (!replay.isEnabled()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors & transactions, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n };\n}\n\n/**\n * Create a \"span\" for each performance entry.\n */\nfunction createPerformanceSpans(\n replay,\n entries,\n) {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n\nfunction handleHistory(handlerData) {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.\n */\nfunction handleHistorySpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nfunction shouldFilterRequest(replay, url) {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return _isSentryRequest(url);\n}\n\n/**\n * Checks wether a given URL belongs to the configured Sentry DSN.\n */\nfunction _isSentryRequest(url) {\n const client = getCurrentHub().getClient();\n const dsn = client && client.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n}\n\n/** Add a performance entry breadcrumb */\nfunction addNetworkBreadcrumb(\n replay,\n result,\n) {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n\n/** only exported for tests */\nfunction handleFetch(handlerData) {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response ? (response ).status : undefined,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.\n */\nfunction handleFetchSpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n\n/** only exported for tests */\nfunction handleXhr(handlerData) {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('xhr', listener)`.\n */\nfunction handleXhrSpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n\nconst OBJ = 10;\nconst OBJ_KEY = 11;\nconst OBJ_KEY_STR = 12;\nconst OBJ_VAL = 13;\nconst OBJ_VAL_STR = 14;\nconst OBJ_VAL_COMPLETED = 15;\n\nconst ARR = 20;\nconst ARR_VAL = 21;\nconst ARR_VAL_STR = 22;\nconst ARR_VAL_COMPLETED = 23;\n\nconst ALLOWED_PRIMITIVES = ['true', 'false', 'null'];\n\n/**\n * Complete an incomplete JSON string.\n * This will ensure that the last element always has a `\"~~\"` to indicate it was truncated.\n * For example, `[1,2,` will be completed to `[1,2,\"~~\"]`\n * and `{\"aa\":\"b` will be completed to `{\"aa\":\"b~~\"}`\n */\nfunction completeJson(incompleteJson, stack) {\n if (!stack.length) {\n return incompleteJson;\n }\n\n let json = incompleteJson;\n\n // Most checks are only needed for the last step in the stack\n const lastPos = stack.length - 1;\n const lastStep = stack[lastPos];\n\n json = _fixLastStep(json, lastStep);\n\n // Complete remaining steps - just add closing brackets\n for (let i = lastPos; i >= 0; i--) {\n const step = stack[i];\n\n switch (step) {\n case OBJ:\n json = `${json}}`;\n break;\n case ARR:\n json = `${json}]`;\n break;\n }\n }\n\n return json;\n}\n\nfunction _fixLastStep(json, lastStep) {\n switch (lastStep) {\n // Object cases\n case OBJ:\n return `${json}\"~~\":\"~~\"`;\n case OBJ_KEY:\n return `${json}:\"~~\"`;\n case OBJ_KEY_STR:\n return `${json}~~\":\"~~\"`;\n case OBJ_VAL:\n return _maybeFixIncompleteObjValue(json);\n case OBJ_VAL_STR:\n return `${json}~~\"`;\n case OBJ_VAL_COMPLETED:\n return `${json},\"~~\":\"~~\"`;\n\n // Array cases\n case ARR:\n return `${json}\"~~\"`;\n case ARR_VAL:\n return _maybeFixIncompleteArrValue(json);\n case ARR_VAL_STR:\n return `${json}~~\"`;\n case ARR_VAL_COMPLETED:\n return `${json},\"~~\"`;\n }\n\n return json;\n}\n\nfunction _maybeFixIncompleteArrValue(json) {\n const pos = _findLastArrayDelimiter(json);\n\n if (pos > -1) {\n const part = json.slice(pos + 1);\n\n if (ALLOWED_PRIMITIVES.includes(part.trim())) {\n return `${json},\"~~\"`;\n }\n\n // Everything else is replaced with `\"~~\"`\n return `${json.slice(0, pos + 1)}\"~~\"`;\n }\n\n // fallback, this shouldn't happen, to be save\n return json;\n}\n\nfunction _findLastArrayDelimiter(json) {\n for (let i = json.length - 1; i >= 0; i--) {\n const char = json[i];\n\n if (char === ',' || char === '[') {\n return i;\n }\n }\n\n return -1;\n}\n\nfunction _maybeFixIncompleteObjValue(json) {\n const startPos = json.lastIndexOf(':');\n\n const part = json.slice(startPos + 1);\n\n if (ALLOWED_PRIMITIVES.includes(part.trim())) {\n return `${json},\"~~\":\"~~\"`;\n }\n\n // Everything else is replaced with `\"~~\"`\n // This also means we do not have incomplete numbers, e.g `[1` is replaced with `[\"~~\"]`\n return `${json.slice(0, startPos + 1)}\"~~\"`;\n}\n\n/**\n * Evaluate an (incomplete) JSON string.\n */\nfunction evaluateJson(json) {\n const stack = [];\n\n for (let pos = 0; pos < json.length; pos++) {\n _evaluateJsonPos(stack, json, pos);\n }\n\n return stack;\n}\n\nfunction _evaluateJsonPos(stack, json, pos) {\n const curStep = stack[stack.length - 1];\n\n const char = json[pos];\n\n const whitespaceRegex = /\\s/;\n\n if (whitespaceRegex.test(char)) {\n return;\n }\n\n if (char === '\"' && !_isEscaped(json, pos)) {\n _handleQuote(stack, curStep);\n return;\n }\n\n switch (char) {\n case '{':\n _handleObj(stack, curStep);\n break;\n case '[':\n _handleArr(stack, curStep);\n break;\n case ':':\n _handleColon(stack, curStep);\n break;\n case ',':\n _handleComma(stack, curStep);\n break;\n case '}':\n _handleObjClose(stack, curStep);\n break;\n case ']':\n _handleArrClose(stack, curStep);\n break;\n }\n}\n\nfunction _handleQuote(stack, curStep) {\n // End of obj value\n if (curStep === OBJ_VAL_STR) {\n stack.pop();\n stack.push(OBJ_VAL_COMPLETED);\n return;\n }\n\n // End of arr value\n if (curStep === ARR_VAL_STR) {\n stack.pop();\n stack.push(ARR_VAL_COMPLETED);\n return;\n }\n\n // Start of obj value\n if (curStep === OBJ_VAL) {\n stack.push(OBJ_VAL_STR);\n return;\n }\n\n // Start of arr value\n if (curStep === ARR_VAL) {\n stack.push(ARR_VAL_STR);\n return;\n }\n\n // Start of obj key\n if (curStep === OBJ) {\n stack.push(OBJ_KEY_STR);\n return;\n }\n\n // End of obj key\n if (curStep === OBJ_KEY_STR) {\n stack.pop();\n stack.push(OBJ_KEY);\n return;\n }\n}\n\nfunction _handleObj(stack, curStep) {\n // Initial object\n if (!curStep) {\n stack.push(OBJ);\n return;\n }\n\n // New object as obj value\n if (curStep === OBJ_VAL) {\n stack.push(OBJ);\n return;\n }\n\n // New object as array element\n if (curStep === ARR_VAL) {\n stack.push(OBJ);\n }\n\n // New object as first array element\n if (curStep === ARR) {\n stack.push(OBJ);\n return;\n }\n}\n\nfunction _handleArr(stack, curStep) {\n // Initial array\n if (!curStep) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n\n // New array as obj value\n if (curStep === OBJ_VAL) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n\n // New array as array element\n if (curStep === ARR_VAL) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n }\n\n // New array as first array element\n if (curStep === ARR) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n}\n\nfunction _handleColon(stack, curStep) {\n if (curStep === OBJ_KEY) {\n stack.pop();\n stack.push(OBJ_VAL);\n }\n}\n\nfunction _handleComma(stack, curStep) {\n // Comma after obj value\n if (curStep === OBJ_VAL) {\n stack.pop();\n return;\n }\n if (curStep === OBJ_VAL_COMPLETED) {\n // Pop OBJ_VAL_COMPLETED & OBJ_VAL\n stack.pop();\n stack.pop();\n return;\n }\n\n // Comma after arr value\n if (curStep === ARR_VAL) {\n // do nothing - basically we'd pop ARR_VAL but add it right back\n return;\n }\n\n if (curStep === ARR_VAL_COMPLETED) {\n // Pop ARR_VAL_COMPLETED\n stack.pop();\n\n // basically we'd pop ARR_VAL but add it right back\n return;\n }\n}\n\nfunction _handleObjClose(stack, curStep) {\n // Empty object {}\n if (curStep === OBJ) {\n stack.pop();\n }\n\n // Object with element\n if (curStep === OBJ_VAL) {\n // Pop OBJ_VAL, OBJ\n stack.pop();\n stack.pop();\n }\n\n // Obj with element\n if (curStep === OBJ_VAL_COMPLETED) {\n // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ\n stack.pop();\n stack.pop();\n stack.pop();\n }\n\n // if was obj value, complete it\n if (stack[stack.length - 1] === OBJ_VAL) {\n stack.push(OBJ_VAL_COMPLETED);\n }\n\n // if was arr value, complete it\n if (stack[stack.length - 1] === ARR_VAL) {\n stack.push(ARR_VAL_COMPLETED);\n }\n}\n\nfunction _handleArrClose(stack, curStep) {\n // Empty array []\n if (curStep === ARR) {\n stack.pop();\n }\n\n // Array with element\n if (curStep === ARR_VAL) {\n // Pop ARR_VAL, ARR\n stack.pop();\n stack.pop();\n }\n\n // Array with element\n if (curStep === ARR_VAL_COMPLETED) {\n // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR\n stack.pop();\n stack.pop();\n stack.pop();\n }\n\n // if was obj value, complete it\n if (stack[stack.length - 1] === OBJ_VAL) {\n stack.push(OBJ_VAL_COMPLETED);\n }\n\n // if was arr value, complete it\n if (stack[stack.length - 1] === ARR_VAL) {\n stack.push(ARR_VAL_COMPLETED);\n }\n}\n\nfunction _isEscaped(str, pos) {\n const previousChar = str[pos - 1];\n\n return previousChar === '\\\\' && !_isEscaped(str, pos - 1);\n}\n\n/* eslint-disable max-lines */\n\n/**\n * Takes an incomplete JSON string, and returns a hopefully valid JSON string.\n * Note that this _can_ fail, so you should check the return value is valid JSON.\n */\nfunction fixJson(incompleteJson) {\n const stack = evaluateJson(incompleteJson);\n\n return completeJson(incompleteJson, stack);\n}\n\n/** Get the size of a body. */\nfunction getBodySize(\n body,\n textEncoder,\n) {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch (e) {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nfunction parseContentLengthHeader(header) {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nfunction getBodyString(body) {\n if (typeof body === 'string') {\n return body;\n }\n\n if (body instanceof URLSearchParams) {\n return body.toString();\n }\n\n if (body instanceof FormData) {\n return _serializeFormData(body);\n }\n\n return undefined;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nfunction makeNetworkReplayBreadcrumb(\n type,\n data,\n) {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nfunction buildSkippedNetworkRequestOrResponse(bodySize) {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nfunction buildNetworkRequestOrResponse(\n headers,\n bodySize,\n body,\n) {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nfunction getAllowedHeaders(headers, allowedHeaders) {\n return Object.keys(headers).reduce((filteredHeaders, key) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData) {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-ignore passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body)\n\n {\n if (!body || typeof body !== 'string') {\n return {\n body,\n warnings: [],\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n\n if (_strIsProbablyJson(body)) {\n try {\n const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;\n const normalizedBody = JSON.parse(json);\n return {\n body: normalizedBody,\n warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],\n };\n } catch (e3) {\n return {\n body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,\n warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],\n };\n }\n }\n\n return {\n body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,\n warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],\n };\n}\n\nfunction _strIsProbablyJson(str) {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nfunction urlMatches(url, urls) {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nfunction getFullUrl(url, baseURI = WINDOW.document.baseURI) {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nasync function captureFetchBreadcrumbToReplay(\n breadcrumb,\n hint,\n options\n\n,\n) {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichFetchBreadcrumb(\n breadcrumb,\n hint,\n options,\n) {\n const { input, response } = hint;\n\n const body = _getFetchRequestArgBody(input);\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb,\n hint,\n options\n\n,\n) {\n const { startTimestamp, endTimestamp } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders },\n input,\n requestBodySize,\n) {\n const headers = getRequestHeaders(input, networkRequestHeaders);\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const bodyStr = getBodyString(requestBody);\n return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n}\n\nasync function _getResponseInfo(\n captureDetails,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }\n\n,\n response,\n responseBodySize,\n) {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = getAllHeaders(response.headers, networkResponseHeaders);\n\n if (!networkCaptureBodies && responseBodySize !== undefined) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n // Only clone the response if we need to\n try {\n // We have to clone this, as the body can only be read once\n const res = response.clone();\n const bodyText = await _parseFetchBody(res);\n\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (e) {\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchBody(response) {\n try {\n return await response.text();\n } catch (e2) {\n return undefined;\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs = []) {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] ).body;\n}\n\nfunction getAllHeaders(headers, allowedHeaders) {\n const allHeaders = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) ;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs, allowedHeaders) {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input,\n allowedHeaders,\n) {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nasync function captureXhrBreadcrumbToReplay(\n breadcrumb,\n hint,\n options,\n) {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichXhrBreadcrumb(\n breadcrumb,\n hint,\n options,\n) {\n const { xhr, input } = hint;\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : getBodySize(xhr.response, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb,\n hint,\n options,\n) {\n const { startTimestamp, endTimestamp, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const request = buildNetworkRequestOrResponse(\n networkRequestHeaders,\n requestBodySize,\n options.networkCaptureBodies ? getBodyString(input) : undefined,\n );\n const response = buildNetworkRequestOrResponse(\n networkResponseHeaders,\n responseBodySize,\n options.networkCaptureBodies ? hint.xhr.responseText : undefined,\n );\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction getResponseHeaders(xhr) {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc, line) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nfunction handleNetworkBreadcrumbs(replay) {\n const client = getCurrentHub().getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addInstrumentationHandler('fetch', handleFetchSpanListener(replay));\n addInstrumentationHandler('xhr', handleXhrSpanListener(replay));\n }\n } catch (e2) {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nfunction beforeAddNetworkBreadcrumb(\n options,\n breadcrumb,\n hint,\n) {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n void captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n void captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint) {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint) {\n return hint && hint.response;\n}\n\nlet _LAST_BREADCRUMB = null;\n\nfunction isBreadcrumbWithCategory(breadcrumb) {\n return !!breadcrumb.category;\n}\n\nconst handleScopeListener =\n (replay) =>\n (scope) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nfunction handleScope(scope) {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nfunction normalizeConsoleBreadcrumb(\n breadcrumb,\n) {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));\n const json = JSON.parse(fixedJson);\n // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`\n isTruncated = true;\n return json;\n }\n return normalizedArg;\n } catch (e) {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n\n/**\n * Add global listeners that cannot be removed.\n */\nfunction addGlobalListeners(replay) {\n // Listeners from core SDK //\n const scope = getCurrentHub().getScope();\n const client = getCurrentHub().getClient();\n\n if (scope) {\n scope.addScopeListener(handleScopeListener(replay));\n }\n addInstrumentationHandler('dom', handleDomListener(replay));\n addInstrumentationHandler('history', handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks(client)));\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n dsc.replay_id = replayId;\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client) {\n return !!(client && client.on);\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nasync function addMemoryEntry(replay) {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-ignore memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry) {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n\n// Map entryType -> function to normalize data for event\n// @ts-ignore TODO: entry type does not fit the create* functions entry type\nconst ENTRY_TYPES\n\n = {\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n ['largest-contentful-paint']: createLargestContentfulPaint,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nfunction createPerformanceEntries(\n entries,\n) {\n return entries.map(createPerformanceEntry).filter(Boolean) ;\n}\n\nfunction createPerformanceEntry(entry) {\n if (ENTRY_TYPES[entry.entryType] === undefined) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time) {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry) {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry) {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry,\n) {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\nfunction createLargestContentfulPaint(\n entry,\n) {\n const { entryType, startTime, size } = entry;\n\n let startTimeOrNavigationActivation = 0;\n\n if (WINDOW.performance) {\n const navEntry = WINDOW.performance.getEntriesByType('navigation')[0]\n\n;\n\n // See https://github.com/GoogleChrome/web-vitals/blob/9f11c4c6578fb4c5ee6fa4e32b9d1d756475f135/src/lib/getActivationStart.ts#L21\n startTimeOrNavigationActivation = (navEntry && navEntry.activationStart) || 0;\n }\n\n // value is in ms\n const value = Math.max(startTime - startTimeOrNavigationActivation, 0);\n // LCP doesn't have a \"duration\", it just happens at a single point in time.\n // But the UI expects both, so use end (in seconds) for both timestamps.\n const end = getAbsoluteTime(startTimeOrNavigationActivation) + value / 1000;\n\n return {\n type: entryType,\n name: entryType,\n start: end,\n end,\n data: {\n value, // LCP \"duration\" in ms\n size,\n // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nodeId: record.mirror.getId(entry.element ),\n },\n };\n}\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nfunction debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nfunction getHandleRecordingEmit(replay) {\n let hadFirstEvent = false;\n\n return (event, _isCheckout) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // We need to clear existing events on a checkout, otherwise they are\n // incremental event updates and should be appended\n void addEvent(replay, event, isCheckout);\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n void addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n logInfo(\n `[Replay] Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`,\n replay.getOptions()._experiments.traceInternals,\n );\n\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nfunction createOptionsEvent(replay) {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay, isCheckout) {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return Promise.resolve(null);\n }\n\n return addEvent(replay, createOptionsEvent(replay), false);\n}\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nfunction createReplayEnvelope(\n replayEvent,\n recordingData,\n dsn,\n tunnel,\n) {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n\n/**\n * Prepare the recording data ready to be sent.\n */\nfunction prepareRecordingData({\n recordingData,\n headers,\n}\n\n) {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nasync function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}\n\n) {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n { event_id, integrations },\n scope,\n )) ;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n\n/**\n * Send replay attachment using `fetch()`\n */\nasync function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}) {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const hub = getCurrentHub();\n const client = hub.getClient();\n const scope = hub.getScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n logInfo('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch (e) {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nclass TransportStatusCodeError extends Error {\n constructor(statusCode) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nasync function sendReplay(\n replayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n) {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch (e) {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n\nconst THROTTLED = '__THROTTLED';\nconst SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction throttle(\n fn,\n maxCount,\n durationSeconds,\n) {\n const counter = new Map();\n\n const _cleanup = (now) => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = () => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest) => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n\n/* eslint-disable max-lines */ // TODO: We might want to split this file up\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nclass ReplayContainer {\n\n /**\n * List of PerformanceEntry from PerformanceObserver\n */\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n\n /**\n * Is the integration currently active?\n */\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n\n /**\n * Function to stop recording\n */\n\n constructor({\n options,\n recordingOptions,\n }\n\n) {ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);\n this.eventBuffer = null;\n this.performanceEvents = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n maxSessionLife: MAX_SESSION_LIFE,\n } ;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event, isCheckout) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n getContext() {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n isEnabled() {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n isPaused() {\n return this._isPaused;\n }\n\n /** Get the replay integration options. */\n getOptions() {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n initializeSampling() {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n const isSessionSampled = this._loadAndCheckSession();\n\n if (!isSessionSampled) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled && this.session.sampled !== 'session') {\n // If not sampled as session-based, then recording mode will be `buffer`\n // Note that we don't explicitly check if `sampled === 'buffer'` because we\n // could have sessions from Session storage that are still `error` from\n // prior SDK version.\n this.recordingMode = 'buffer';\n }\n\n logInfoNextTick(\n `[Replay] Starting replay in ${this.recordingMode} mode`,\n this._options._experiments.traceInternals,\n );\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n logInfoNextTick('[Replay] Starting replay in session mode', this._options._experiments.traceInternals);\n\n const previousSessionId = this.session && this.session.id;\n\n const { session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n traceInternals: this._options._experiments.traceInternals,\n });\n\n session.previousSessionId = previousSessionId;\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n startBuffering() {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n logInfoNextTick('[Replay] Starting replay in buffer mode', this._options._experiments.traceInternals);\n\n const previousSessionId = this.session && this.session.id;\n\n const { session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: 0,\n allowBuffering: true,\n traceInternals: this._options._experiments.traceInternals,\n });\n\n session.previousSessionId = previousSessionId;\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n startRecording() {\n try {\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n stopRecording() {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n async stop({ forceFlush = false, reason } = {}) {\n if (!this._isEnabled) {\n return;\n }\n\n try {\n logInfo(\n `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`,\n this._options._experiments.traceInternals,\n );\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n pause() {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n logInfo('[Replay] Pausing replay', this._options._experiments.traceInternals);\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n resume() {\n if (!this._isPaused || !this._loadAndCheckSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n logInfo('[Replay] Resuming replay', this._options._experiments.traceInternals);\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n logInfo('[Replay] Converting buffer to session', this._options._experiments.traceInternals);\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode ) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this.session.shouldRefresh = false;\n\n // It's possible that the session lifespan is > max session lifespan\n // because we have been buffering beyond max session lifespan (we ignore\n // expiration given that `shouldRefresh` is true). Since we flip\n // `shouldRefresh`, the session could be considered expired due to\n // lifespan, which is not what we want. Update session start date to be\n // the current timestamp, so that session is not considered to be\n // expired. This means that max replay duration can be MAX_SESSION_LIFE +\n // (length of buffer), which we are ok with.\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n addUpdate(cb) {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n triggerUserActivity() {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n updateUserActivity() {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n conditionalFlush() {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n flush() {\n return this._debouncedFlush() ;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n flushImmediate() {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() ;\n }\n\n /**\n * Cancels queued up flushes.\n */\n cancelFlush() {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n getSessionId() {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n checkAndHandleExpiredSession() {\n const oldSessionId = this.getSessionId();\n\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Session was expired if session ids do not match\n const expired = oldSessionId !== this.getSessionId();\n\n if (!expired) {\n return true;\n }\n\n // Session is expired, trigger a full snapshot (which will create a new session)\n this._triggerFullSnapshot();\n\n return false;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n setInitialState() {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEvents = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n throttledAddEvent(\n event,\n isCheckout,\n ) {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n void addEvent(this, {\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n getCurrentRoute() {\n const lastTransaction = this.lastTransaction || getCurrentHub().getScope().getTransaction();\n if (!lastTransaction || !['route', 'custom'].includes(lastTransaction.metadata.source)) {\n return undefined;\n }\n\n return lastTransaction.name;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n _initializeRecording() {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n _handleException(error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', error);\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n * Returns false if session is not recorded.\n */\n _loadAndCheckSession() {\n const { type, session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering: this._options.errorSampleRate > 0 || this.recordingMode === 'buffer',\n traceInternals: this._options._experiments.traceInternals,\n });\n\n // If session was newly created (i.e. was not loaded from storage), then\n // enable flag to create the root replay\n if (type === 'new') {\n this.setInitialState();\n }\n\n const currentSessionId = this.getSessionId();\n if (session.id !== currentSessionId) {\n session.previousSessionId = currentSessionId;\n }\n\n this.session = session;\n\n if (!this.session.sampled) {\n void this.stop({ reason: 'session not refreshed' });\n return false;\n }\n\n return true;\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n _addListeners() {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n // PerformanceObserver //\n if (!('PerformanceObserver' in WINDOW)) {\n return;\n }\n\n this._performanceObserver = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n _removeListeners() {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceObserver) {\n this._performanceObserver.disconnect();\n this._performanceObserver = undefined;\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n __init() {this._handleVisibilityChange = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };}\n\n /**\n * Handle when page is blurred\n */\n __init2() {this._handleWindowBlur = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };}\n\n /**\n * Handle when page is focused\n */\n __init3() {this._handleWindowFocus = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };}\n\n /** Ensure page remains active when a key is pressed. */\n __init4() {this._handleKeyboardEvent = (event) => {\n handleKeyboardEvent(this, event);\n };}\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n _doChangeToBackgroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, this.timeouts);\n\n if (breadcrumb && !expired) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n _doChangeToForegroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n logInfo('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Trigger rrweb to take a full snapshot which will cause this plugin to\n * create a new Replay event.\n */\n _triggerFullSnapshot(checkout = true) {\n try {\n logInfo('[Replay] Taking full rrweb snapshot');\n record.takeFullSnapshot(checkout);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n _updateUserActivity(_lastActivity = Date.now()) {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n _updateSessionActivity(_lastActivity = Date.now()) {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n _createCustomBreadcrumb(breadcrumb) {\n this.addUpdate(() => {\n void this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEvents`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n _addPerformanceEntries() {\n // Copy and reset entries before processing\n const entries = [...this.performanceEvents];\n this.performanceEvents = [];\n\n return Promise.all(createPerformanceSpans(this, createPerformanceEntries(entries)));\n }\n\n /**\n * Clear _context\n */\n _clearContext() {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n _updateInitialTimestampFromEventBuffer() {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n _popEventContext() {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n async _runFlush() {\n if (!this.session || !this.eventBuffer) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accomodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this.timeouts.maxSessionLife + 30000) {\n throw new Error('Session is too long, not sending replay');\n }\n\n // NOTE: Copy values from instance members, as it's possible they could\n // change before the flush finishes.\n const replayId = this.session.id;\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp,\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n void this.stop({ reason: 'sendReplay' });\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n __init5() {this._flush = async ({\n force = false,\n }\n\n = {}) => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] No session found to flush.');\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxSessionLife), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this.timeouts.maxSessionLife + 5000;\n if (tooShort || tooLong) {\n logInfo(\n `[Replay] Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n this._options._experiments.traceInternals,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n logInfo('[Replay] Flushing initial segment without checkout.', this._options._experiments.traceInternals);\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = undefined;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };}\n\n /** Save the session, if it is sticky */\n _maybeSaveSession() {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n __init6() {this._onMutationHandler = (mutations) => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n void this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };}\n}\n\nfunction getOption(\n selectors,\n defaultSelectors,\n deprecatedClassOption,\n deprecatedSelectorOption,\n) {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nfunction getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}) {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n maskInputSelector: maskSelector,\n unmaskInputSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n\n/**\n * Returns true if we are in the browser.\n */\nfunction isBrowser() {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer() {\n return typeof process !== 'undefined' && (process ).type === 'renderer';\n}\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n */\nclass Replay {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Replay';}\n\n /**\n * @inheritDoc\n */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n\n constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10000,\n\n slowClickTimeout = 7000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n } = {}) {\n this.name = Replay.id;\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n\n ...getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n }),\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n get _isInitialized() {\n return _initialized;\n }\n\n /** Update _isInitialized */\n set _isInitialized(value) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n setupOnce() {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n startBuffering() {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n stop() {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n flush(options) {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n getReplayId() {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n /**\n * Initializes replay.\n */\n _initialize() {\n if (!this._replay) {\n return;\n }\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n _setup() {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n} Replay.__initStatic();\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions) {\n const client = getCurrentHub().getClient();\n const opt = client && (client.getOptions() );\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers) {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n\nexport { Replay };\n//# sourceMappingURL=index.js.map\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\n","import { getActiveTransaction } from '@sentry/core';\nimport { logger } from '@sentry/utils';\nimport { WINDOW } from './types.js';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nfunction registerBackgroundTabDetection() {\n if (WINDOW && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() ;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType = 'cancelled';\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexport { registerBackgroundTabDetection };\n//# sourceMappingURL=backgroundtab.js.map\n","const bindReporter = (\n callback,\n metric,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n\nexport { bindReporter };\n//# sourceMappingURL=bindReporter.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nconst generateUniqueID = () => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\n//# sourceMappingURL=generateUniqueID.js.map\n","import { WINDOW } from '../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getNavigationEntryFromPerformanceTiming = () => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0);\n }\n }\n return navigationEntry ;\n};\n\nconst getNavigationEntry = () => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n\nexport { getNavigationEntry };\n//# sourceMappingURL=getNavigationEntry.js.map\n","import { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n\nexport { getActivationStart };\n//# sourceMappingURL=getActivationStart.js.map\n","import { WINDOW } from '../../types.js';\nimport { generateUniqueID } from './generateUniqueID.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst initMetric = (name, value) => {\n const navEntry = getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n\nexport { initMetric };\n//# sourceMappingURL=initMetric.js.map\n","/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nconst observe = (\n type,\n callback,\n opts,\n) => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() );\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) ,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n\nexport { observe };\n//# sourceMappingURL=observe.js.map\n","import { WINDOW } from '../../types.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst onHidden = (cb, once) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n\nexport { onHidden };\n//# sourceMappingURL=onHidden.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onCLS = (onReport) => {\n const metric = initMetric('CLS', 0);\n let report;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\n handleEntries(po.takeRecords() );\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n\nexport { onCLS };\n//# sourceMappingURL=getCLS.js.map\n","import { WINDOW } from '../../types.js';\nimport { onHidden } from './onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = () => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = () => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nconst getVisibilityWatcher = (\n\n) => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexport { getVisibilityWatcher };\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nconst onFID = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntry = (entry) => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries) => {\n (entries ).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }, true);\n }\n};\n\nexport { onFID };\n//# sourceMappingURL=getFID.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst reportedMetricIDs = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nconst onLCP = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const handleEntries = (entries) => {\n const lastEntry = entries[entries.length - 1] ;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() );\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n\nexport { onLCP };\n//# sourceMappingURL=getLCP.js.map\n","/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nfunction _startChild(transaction, { startTimestamp, ...ctx }) {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\nexport { _startChild, isMeasurementValue };\n//# sourceMappingURL=utils.js.map\n","import { getActiveTransaction } from '@sentry/core';\nimport { browserPerformanceTimeOrigin, logger, htmlTreeAsString } from '@sentry/utils';\nimport { WINDOW } from '../types.js';\nimport { onCLS } from '../web-vitals/getCLS.js';\nimport { onFID } from '../web-vitals/getFID.js';\nimport { onLCP } from '../web-vitals/getLCP.js';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher.js';\nimport { observe } from '../web-vitals/lib/observe.js';\nimport { _startChild, isMeasurementValue } from './utils.js';\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI() {\n // @ts-ignore we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\n\n/**\n * Start tracking web vitals\n *\n * @returns A function that forces web vitals collection\n */\nfunction startTrackingWebVitals() {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-ignore we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n\n return () => {\n if (clsCallback) {\n clsCallback();\n }\n if (lcpCallback) {\n lcpCallback();\n }\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\n const entryHandler = (entries) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe('longtask', entryHandler);\n}\n\n/**\n * Start tracking interaction events.\n */\nfunction startTrackingInteractions() {\n const entryHandler = (entries) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n }\n };\n\n observe('event', entryHandler, { durationThreshold: 0 });\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS() {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n return onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry ;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP() {\n return onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry ;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin );\n const startTime = msToSec(entry.startTime);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(transaction) {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp;\n let requestStartTimestamp;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name ).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nfunction _addMeasureSpans(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name ,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType ,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction, entry, timeOrigin) {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n event,\n timeOrigin,\n description,\n eventEnd,\n) {\n const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] );\n const start = entry[`${event}Start`] ;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction, entry, timeOrigin) {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n}\n\n/** Create resource-related spans */\nfunction _addResourceSpans(\n transaction,\n entry,\n resourceName,\n startTime,\n duration,\n timeOrigin,\n) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data = {};\n if ('transferSize' in entry) {\n data['http.response_transfer_size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['http.response_content_length'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['http.decoded_response_content_length'] = entry.decodedBodySize;\n }\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction) {\n const navigator = WINDOW.navigator ;\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction) {\n if (_lcpEntry) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nexport { _addMeasureSpans, _addResourceSpans, addPerformanceEntries, startTrackingInteractions, startTrackingLongTasks, startTrackingWebVitals };\n//# sourceMappingURL=index.js.map\n","import { hasTracingEnabled, getCurrentHub, getDynamicSamplingContextFromClient } from '@sentry/core';\nimport { addInstrumentationHandler, browserPerformanceTimeOrigin, generateSentryTraceHeader, dynamicSamplingContextToSentryBaggageHeader, isInstanceOf, BAGGAGE_HEADER_NAME, SENTRY_XHR_DATA_KEY, stringMatchesSomePattern } from '@sentry/utils';\n\n/* eslint-disable max-lines */\n\nconst DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(_options) {\n const {\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url) =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData) => {\n const createdSpan = fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (handlerData) => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span) {\n const url = span.data.url;\n const observer = new PerformanceObserver(list => {\n const entries = list.getEntries() ;\n entries.forEach(entry => {\n if ((entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest') && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setData(...data));\n observer.disconnect();\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nfunction extractNetworkProtocol(nextHopProtocol) {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time) {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming) {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nfunction shouldAttachHeaders(url, tracePropagationTargets) {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\nfunction fetchCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n\n const contentLength =\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setData('http.response_content_length', contentLengthNum);\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n const client = hub.getClient();\n const parentSpan = scope.getSpan();\n\n const { method, url } = handlerData.fetchData;\n\n const span =\n shouldCreateSpanResult && parentSpan\n ? parentSpan.startChild({\n data: {\n url,\n type: 'fetch',\n 'http.method': method,\n },\n description: `${method} ${url}`,\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nfunction addTracingHeadersToFetchRequest(\n request, // unknown is actually type Request but we can't export DOM types from this package,\n client,\n scope,\n options\n\n,\n requestSpan,\n) {\n const span = requestSpan || scope.getSpan();\n\n const transaction = span && span.transaction;\n\n const { traceId, sampled, dsc } = scope.getPropagationContext();\n\n const sentryTraceHeader = span ? span.toTraceparent() : generateSentryTraceHeader(traceId, undefined, sampled);\n const dynamicSamplingContext = transaction\n ? transaction.getDynamicSamplingContext()\n : dsc\n ? dsc\n : getDynamicSamplingContextFromClient(traceId, client, scope);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request ).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers );\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders ;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders ;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nfunction xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || (xhr && xhr.__sentry_own_request__) || !xhr || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(sentryXhrData.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n const parentSpan = scope.getSpan();\n\n const span =\n shouldCreateSpanResult && parentSpan\n ? parentSpan.startChild({\n data: {\n ...sentryXhrData.data,\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n url: sentryXhrData.url,\n },\n description: `${sentryXhrData.method} ${sentryXhrData.url}`,\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {\n if (span) {\n const transaction = span && span.transaction;\n const dynamicSamplingContext = transaction && transaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n setHeaderOnXhr(xhr, span.toTraceparent(), sentryBaggageHeader);\n } else {\n const client = hub.getClient();\n const { traceId, sampled, dsc } = scope.getPropagationContext();\n const sentryTraceHeader = generateSentryTraceHeader(traceId, undefined, sampled);\n const dynamicSamplingContext =\n dsc || (client ? getDynamicSamplingContextFromClient(traceId, client, scope) : undefined);\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr,\n sentryTraceHeader,\n sentryBaggageHeader,\n) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nexport { DEFAULT_TRACE_PROPAGATION_TARGETS, addTracingHeadersToFetchRequest, defaultRequestInstrumentationOptions, extractNetworkProtocol, fetchCallback, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback };\n//# sourceMappingURL=request.js.map\n","import { logger, browserPerformanceTimeOrigin, addInstrumentationHandler } from '@sentry/utils';\nimport { WINDOW } from './types.js';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nfunction instrumentRoutingWithDefaults(\n customStartTransaction,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n) {\n if (!WINDOW || !WINDOW.location) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl = WINDOW.location.href;\n\n let activeTransaction;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n\nexport { instrumentRoutingWithDefaults };\n//# sourceMappingURL=router.js.map\n","import { TRACING_DEFAULTS, addTracingExtensions, startIdleTransaction, getActiveTransaction } from '@sentry/core';\nimport { logger, tracingContextFromHeaders, getDomElement } from '@sentry/utils';\nimport { registerBackgroundTabDetection } from './backgroundtab.js';\nimport { startTrackingWebVitals, startTrackingLongTasks, startTrackingInteractions, addPerformanceEntries } from './metrics/index.js';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request.js';\nimport { instrumentRoutingWithDefaults } from './router.js';\nimport { WINDOW } from './types.js';\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nclass BrowserTracing {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n\n /**\n * @inheritDoc\n */\n\n constructor(_options) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n _createRouteTransaction(context) {\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : '';\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n const expandedContext = {\n ...context,\n ...traceparentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n\n const scope = hub.getScope();\n\n // If it's a pageload and there is a meta tag set\n // use the traceparentData as the propagation context\n if (isPageloadTransaction && traceparentData) {\n scope.setPropagationContext(propagationContext);\n } else {\n // Navigation transactions should set a new propagation context based on the\n // created idle transaction.\n scope.setPropagationContext({\n traceId: idleTransaction.traceId,\n spanId: idleTransaction.spanId,\n parentSpanId: idleTransaction.parentSpanId,\n sampled: !!idleTransaction.sampled,\n });\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction ;\n }\n\n /** Start listener for interaction transactions */\n _registerInteractionListener() {\n let inflightInteractionTransaction;\n const registerInteractionTransaction = () => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\nexport { BROWSER_TRACING_INTEGRATION_ID, BrowserTracing, getMetaContent };\n//# sourceMappingURL=browsertracing.js.map\n","import { SDK_VERSION, init as init$1 } from '@sentry/browser';\n\n/**\n * Inits the React SDK\n */\nfunction init(options) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.react',\n packages: [\n {\n name: 'npm:@sentry/react',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n init$1(options);\n}\n\nexport { init };\n//# sourceMappingURL=sdk.js.map\n","/**\n * @license React\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3 0 && index + match.length !== title.length && match.search(smallWords) > -1 && title.charAt(index - 2) !== \":\" && (title.charAt(index + match.length) !== \"-\" || title.charAt(index - 1) === \"-\") && title.charAt(index - 1).search(/[^\\s-]/) < 0) {\n return match.toLowerCase();\n }\n if (match.substr(1).search(/[A-Z]|\\../) > -1) {\n return match;\n }\n return match.charAt(0).toUpperCase() + match.substr(1);\n });\n}\n\n// See if s could be an email address. We don't want to send personal data like email.\n// https://support.google.com/analytics/answer/2795983?hl=en\nfunction mightBeEmail(s) {\n // There's no point trying to validate rfc822 fully, just look for ...@...\n return typeof s === \"string\" && s.indexOf(\"@\") !== -1;\n}\nvar redacted = \"REDACTED (Potential Email Address)\";\nfunction redactEmail(string) {\n if (mightBeEmail(string)) {\n console.warn(\"This arg looks like an email address, redacting.\");\n return redacted;\n }\n return string;\n}\nfunction format() {\n var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : \"\";\n var titleCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var redactingEmail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var _str = s || \"\";\n if (titleCase) {\n _str = toTitleCase(s);\n }\n if (redactingEmail) {\n _str = redactEmail(_str);\n }\n return _str;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = exports.GA4 = void 0;\nvar _gtag = _interopRequireDefault(require(\"./gtag\"));\nvar _format = _interopRequireDefault(require(\"./format\"));\nvar _excluded = [\"eventCategory\", \"eventAction\", \"eventLabel\", \"eventValue\", \"hitType\"],\n _excluded2 = [\"title\", \"location\"],\n _excluded3 = [\"page\", \"hitType\"];\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/*\nLinks\nhttps://developers.google.com/gtagjs/reference/api\nhttps://developers.google.com/tag-platform/gtagjs/reference\n*/\n/**\n * @typedef GaOptions\n * @type {Object}\n * @property {boolean} [cookieUpdate=true]\n * @property {number} [cookieExpires=63072000] Default two years\n * @property {string} [cookieDomain=\"auto\"]\n * @property {string} [cookieFlags]\n * @property {string} [userId]\n * @property {string} [clientId]\n * @property {boolean} [anonymizeIp]\n * @property {string} [contentGroup1]\n * @property {string} [contentGroup2]\n * @property {string} [contentGroup3]\n * @property {string} [contentGroup4]\n * @property {string} [contentGroup5]\n * @property {boolean} [allowAdFeatures=true]\n * @property {boolean} [allowAdPersonalizationSignals]\n * @property {boolean} [nonInteraction]\n * @property {string} [page]\n */\n/**\n * @typedef UaEventOptions\n * @type {Object}\n * @property {string} action\n * @property {string} category\n * @property {string} [label]\n * @property {number} [value]\n * @property {boolean} [nonInteraction]\n * @property {('beacon'|'xhr'|'image')} [transport]\n */\n/**\n * @typedef InitOptions\n * @type {Object}\n * @property {string} trackingId\n * @property {GaOptions|any} [gaOptions]\n * @property {Object} [gtagOptions] New parameter\n */\nvar GA4 = /*#__PURE__*/function () {\n function GA4() {\n var _this = this;\n _classCallCheck(this, GA4);\n _defineProperty(this, \"reset\", function () {\n _this.isInitialized = false;\n _this._testMode = false;\n _this._currentMeasurementId;\n _this._hasLoadedGA = false;\n _this._isQueuing = false;\n _this._queueGtag = [];\n });\n _defineProperty(this, \"_gtag\", function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n if (!_this._testMode) {\n if (_this._isQueuing) {\n _this._queueGtag.push(args);\n } else {\n _gtag[\"default\"].apply(void 0, args);\n }\n } else {\n _this._queueGtag.push(args);\n }\n });\n _defineProperty(this, \"_loadGA\", function (GA_MEASUREMENT_ID, nonce) {\n var gtagUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : \"https://www.googletagmanager.com/gtag/js\";\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return;\n }\n if (!_this._hasLoadedGA) {\n // Global Site Tag (gtag.js) - Google Analytics\n var script = document.createElement(\"script\");\n script.async = true;\n script.src = \"\".concat(gtagUrl, \"?id=\").concat(GA_MEASUREMENT_ID);\n if (nonce) {\n script.setAttribute(\"nonce\", nonce);\n }\n document.body.appendChild(script);\n window.dataLayer = window.dataLayer || [];\n window.gtag = function gtag() {\n window.dataLayer.push(arguments);\n };\n _this._hasLoadedGA = true;\n }\n });\n _defineProperty(this, \"_toGtagOptions\", function (gaOptions) {\n if (!gaOptions) {\n return;\n }\n var mapFields = {\n // Old https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#cookieUpdate\n // New https://developers.google.com/analytics/devguides/collection/gtagjs/cookies-user-id#cookie_update\n cookieUpdate: \"cookie_update\",\n cookieExpires: \"cookie_expires\",\n cookieDomain: \"cookie_domain\",\n cookieFlags: \"cookie_flags\",\n // must be in set method?\n userId: \"user_id\",\n clientId: \"client_id\",\n anonymizeIp: \"anonymize_ip\",\n // https://support.google.com/analytics/answer/2853546?hl=en#zippy=%2Cin-this-article\n contentGroup1: \"content_group1\",\n contentGroup2: \"content_group2\",\n contentGroup3: \"content_group3\",\n contentGroup4: \"content_group4\",\n contentGroup5: \"content_group5\",\n // https://support.google.com/analytics/answer/9050852?hl=en\n allowAdFeatures: \"allow_google_signals\",\n allowAdPersonalizationSignals: \"allow_ad_personalization_signals\",\n nonInteraction: \"non_interaction\",\n page: \"page_path\",\n hitCallback: \"event_callback\"\n };\n var gtagOptions = Object.entries(gaOptions).reduce(function (prev, _ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n key = _ref2[0],\n value = _ref2[1];\n if (mapFields[key]) {\n prev[mapFields[key]] = value;\n } else {\n prev[key] = value;\n }\n return prev;\n }, {});\n return gtagOptions;\n });\n _defineProperty(this, \"initialize\", function (GA_MEASUREMENT_ID) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (!GA_MEASUREMENT_ID) {\n throw new Error(\"Require GA_MEASUREMENT_ID\");\n }\n var initConfigs = typeof GA_MEASUREMENT_ID === \"string\" ? [{\n trackingId: GA_MEASUREMENT_ID\n }] : GA_MEASUREMENT_ID;\n _this._currentMeasurementId = initConfigs[0].trackingId;\n var gaOptions = options.gaOptions,\n gtagOptions = options.gtagOptions,\n nonce = options.nonce,\n _options$testMode = options.testMode,\n testMode = _options$testMode === void 0 ? false : _options$testMode,\n gtagUrl = options.gtagUrl;\n _this._testMode = testMode;\n if (!testMode) {\n _this._loadGA(_this._currentMeasurementId, nonce, gtagUrl);\n }\n if (!_this.isInitialized) {\n _this._gtag(\"js\", new Date());\n initConfigs.forEach(function (config) {\n var mergedGtagOptions = _objectSpread(_objectSpread(_objectSpread({}, _this._toGtagOptions(_objectSpread(_objectSpread({}, gaOptions), config.gaOptions))), gtagOptions), config.gtagOptions);\n if (Object.keys(mergedGtagOptions).length) {\n _this._gtag(\"config\", config.trackingId, mergedGtagOptions);\n } else {\n _this._gtag(\"config\", config.trackingId);\n }\n });\n }\n _this.isInitialized = true;\n if (!testMode) {\n var queues = _toConsumableArray(_this._queueGtag);\n _this._queueGtag = [];\n _this._isQueuing = false;\n while (queues.length) {\n var queue = queues.shift();\n _this._gtag.apply(_this, _toConsumableArray(queue));\n if (queue[0] === \"get\") {\n _this._isQueuing = true;\n }\n }\n }\n });\n _defineProperty(this, \"set\", function (fieldsObject) {\n if (!fieldsObject) {\n console.warn(\"`fieldsObject` is required in .set()\");\n return;\n }\n if (_typeof(fieldsObject) !== \"object\") {\n console.warn(\"Expected `fieldsObject` arg to be an Object\");\n return;\n }\n if (Object.keys(fieldsObject).length === 0) {\n console.warn(\"empty `fieldsObject` given to .set()\");\n }\n _this._gaCommand(\"set\", fieldsObject);\n });\n _defineProperty(this, \"_gaCommandSendEvent\", function (eventCategory, eventAction, eventLabel, eventValue, fieldsObject) {\n _this._gtag(\"event\", eventAction, _objectSpread(_objectSpread({\n event_category: eventCategory,\n event_label: eventLabel,\n value: eventValue\n }, fieldsObject && {\n non_interaction: fieldsObject.nonInteraction\n }), _this._toGtagOptions(fieldsObject)));\n });\n _defineProperty(this, \"_gaCommandSendEventParameters\", function () {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n if (typeof args[0] === \"string\") {\n _this._gaCommandSendEvent.apply(_this, _toConsumableArray(args.slice(1)));\n } else {\n var _args$ = args[0],\n eventCategory = _args$.eventCategory,\n eventAction = _args$.eventAction,\n eventLabel = _args$.eventLabel,\n eventValue = _args$.eventValue,\n hitType = _args$.hitType,\n rest = _objectWithoutProperties(_args$, _excluded);\n _this._gaCommandSendEvent(eventCategory, eventAction, eventLabel, eventValue, rest);\n }\n });\n _defineProperty(this, \"_gaCommandSendTiming\", function (timingCategory, timingVar, timingValue, timingLabel) {\n _this._gtag(\"event\", \"timing_complete\", {\n name: timingVar,\n value: timingValue,\n event_category: timingCategory,\n event_label: timingLabel\n });\n });\n _defineProperty(this, \"_gaCommandSendPageview\", function (page, fieldsObject) {\n if (fieldsObject && Object.keys(fieldsObject).length) {\n var _this$_toGtagOptions = _this._toGtagOptions(fieldsObject),\n title = _this$_toGtagOptions.title,\n location = _this$_toGtagOptions.location,\n rest = _objectWithoutProperties(_this$_toGtagOptions, _excluded2);\n _this._gtag(\"event\", \"page_view\", _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, page && {\n page_path: page\n }), title && {\n page_title: title\n }), location && {\n page_location: location\n }), rest));\n } else if (page) {\n _this._gtag(\"event\", \"page_view\", {\n page_path: page\n });\n } else {\n _this._gtag(\"event\", \"page_view\");\n }\n });\n _defineProperty(this, \"_gaCommandSendPageviewParameters\", function () {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n if (typeof args[0] === \"string\") {\n _this._gaCommandSendPageview.apply(_this, _toConsumableArray(args.slice(1)));\n } else {\n var _args$2 = args[0],\n page = _args$2.page,\n hitType = _args$2.hitType,\n rest = _objectWithoutProperties(_args$2, _excluded3);\n _this._gaCommandSendPageview(page, rest);\n }\n });\n _defineProperty(this, \"_gaCommandSend\", function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n var hitType = typeof args[0] === \"string\" ? args[0] : args[0].hitType;\n switch (hitType) {\n case \"event\":\n _this._gaCommandSendEventParameters.apply(_this, args);\n break;\n case \"pageview\":\n _this._gaCommandSendPageviewParameters.apply(_this, args);\n break;\n case \"timing\":\n _this._gaCommandSendTiming.apply(_this, _toConsumableArray(args.slice(1)));\n break;\n case \"screenview\":\n case \"transaction\":\n case \"item\":\n case \"social\":\n case \"exception\":\n console.warn(\"Unsupported send command: \".concat(hitType));\n break;\n default:\n console.warn(\"Send command doesn't exist: \".concat(hitType));\n }\n });\n _defineProperty(this, \"_gaCommandSet\", function () {\n for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n args[_key5] = arguments[_key5];\n }\n if (typeof args[0] === \"string\") {\n args[0] = _defineProperty({}, args[0], args[1]);\n }\n _this._gtag(\"set\", _this._toGtagOptions(args[0]));\n });\n _defineProperty(this, \"_gaCommand\", function (command) {\n for (var _len6 = arguments.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {\n args[_key6 - 1] = arguments[_key6];\n }\n switch (command) {\n case \"send\":\n _this._gaCommandSend.apply(_this, args);\n break;\n case \"set\":\n _this._gaCommandSet.apply(_this, args);\n break;\n default:\n console.warn(\"Command doesn't exist: \".concat(command));\n }\n });\n _defineProperty(this, \"ga\", function () {\n for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {\n args[_key7] = arguments[_key7];\n }\n if (typeof args[0] === \"string\") {\n _this._gaCommand.apply(_this, args);\n } else {\n var readyCallback = args[0];\n _this._gtag(\"get\", _this._currentMeasurementId, \"client_id\", function (clientId) {\n _this._isQueuing = false;\n var queues = _this._queueGtag;\n readyCallback({\n get: function get(property) {\n return property === \"clientId\" ? clientId : property === \"trackingId\" ? _this._currentMeasurementId : property === \"apiVersion\" ? \"1\" : undefined;\n }\n });\n while (queues.length) {\n var queue = queues.shift();\n _this._gtag.apply(_this, _toConsumableArray(queue));\n }\n });\n _this._isQueuing = true;\n }\n return _this.ga;\n });\n _defineProperty(this, \"event\", function (optionsOrName, params) {\n if (typeof optionsOrName === \"string\") {\n _this._gtag(\"event\", optionsOrName, _this._toGtagOptions(params));\n } else {\n var action = optionsOrName.action,\n category = optionsOrName.category,\n label = optionsOrName.label,\n value = optionsOrName.value,\n nonInteraction = optionsOrName.nonInteraction,\n transport = optionsOrName.transport;\n if (!category || !action) {\n console.warn(\"args.category AND args.action are required in event()\");\n return;\n }\n\n // Required Fields\n var fieldObject = {\n hitType: \"event\",\n eventCategory: (0, _format[\"default\"])(category),\n eventAction: (0, _format[\"default\"])(action)\n };\n\n // Optional Fields\n if (label) {\n fieldObject.eventLabel = (0, _format[\"default\"])(label);\n }\n if (typeof value !== \"undefined\") {\n if (typeof value !== \"number\") {\n console.warn(\"Expected `args.value` arg to be a Number.\");\n } else {\n fieldObject.eventValue = value;\n }\n }\n if (typeof nonInteraction !== \"undefined\") {\n if (typeof nonInteraction !== \"boolean\") {\n console.warn(\"`args.nonInteraction` must be a boolean.\");\n } else {\n fieldObject.nonInteraction = nonInteraction;\n }\n }\n if (typeof transport !== \"undefined\") {\n if (typeof transport !== \"string\") {\n console.warn(\"`args.transport` must be a string.\");\n } else {\n if ([\"beacon\", \"xhr\", \"image\"].indexOf(transport) === -1) {\n console.warn(\"`args.transport` must be either one of these values: `beacon`, `xhr` or `image`\");\n }\n fieldObject.transport = transport;\n }\n }\n _this._gaCommand(\"send\", fieldObject);\n }\n });\n _defineProperty(this, \"send\", function (fieldObject) {\n _this._gaCommand(\"send\", fieldObject);\n });\n this.reset();\n }\n _createClass(GA4, [{\n key: \"gtag\",\n value: function gtag() {\n this._gtag.apply(this, arguments);\n }\n }]);\n return GA4;\n}();\nexports.GA4 = GA4;\nvar _default = new GA4();\nexports[\"default\"] = _default;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = exports.ReactGAImplementation = void 0;\nvar _ga = _interopRequireWildcard(require(\"./ga4\"));\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { \"default\": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj[\"default\"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\nvar ReactGAImplementation = _ga.GA4;\nexports.ReactGAImplementation = ReactGAImplementation;\nvar _default = _ga[\"default\"];\nexports[\"default\"] = _default;","function _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nvar _controllers = new WeakMap();\nexport class FetcherAbortManager {\n get(requestId) {\n return _class_private_field_get(this, _controllers).get(requestId);\n }\n set(requestId) {\n const controller = new AbortController();\n _class_private_field_get(this, _controllers).set(requestId, controller);\n return controller;\n }\n setSafe(requestId) {\n if (!requestId) return null;\n return this.set(requestId).signal;\n }\n has(requestId) {\n return _class_private_field_get(this, _controllers).has(requestId);\n }\n clear(requestId) {\n return _class_private_field_get(this, _controllers).delete(requestId !== null && requestId !== void 0 ? requestId : '');\n }\n abort(requestId) {\n const id = requestId !== null && requestId !== void 0 ? requestId : '';\n if (!id || !this.has(id)) return false;\n const controller = this.get(id);\n controller.abort();\n return this.clear(id);\n }\n constructor(){\n _class_private_field_init(this, _controllers, {\n writable: true,\n value: void 0\n });\n _class_private_field_set(this, _controllers, new Map());\n }\n} /*#__PURE__*/ \n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9hYm9ydC1tYW5hZ2VyLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjbGFzcyBGZXRjaGVyQWJvcnRNYW5hZ2VyIHtcbiAgcmVhZG9ubHkgI2NvbnRyb2xsZXJzOiBNYXA8c3RyaW5nLCBBYm9ydENvbnRyb2xsZXI+XG5cbiAgY29uc3RydWN0b3IoKSB7XG4gICAgdGhpcy4jY29udHJvbGxlcnMgPSBuZXcgTWFwKClcbiAgfVxuXG4gIHB1YmxpYyBnZXQocmVxdWVzdElkOiBzdHJpbmcpOiBBYm9ydENvbnRyb2xsZXIgfCB1bmRlZmluZWQge1xuICAgIHJldHVybiB0aGlzLiNjb250cm9sbGVycy5nZXQocmVxdWVzdElkKVxuICB9XG5cbiAgcHVibGljIHNldChyZXF1ZXN0SWQ6IHN0cmluZyk6IEFib3J0Q29udHJvbGxlciB7XG4gICAgY29uc3QgY29udHJvbGxlciA9IG5ldyBBYm9ydENvbnRyb2xsZXIoKVxuICAgIHRoaXMuI2NvbnRyb2xsZXJzLnNldChyZXF1ZXN0SWQsIGNvbnRyb2xsZXIpXG4gICAgcmV0dXJuIGNvbnRyb2xsZXJcbiAgfVxuXG4gIHB1YmxpYyBzZXRTYWZlKHJlcXVlc3RJZD86IHN0cmluZyk6IEFib3J0U2lnbmFsIHwgbnVsbCB7XG4gICAgaWYgKCFyZXF1ZXN0SWQpIHJldHVybiBudWxsXG4gICAgcmV0dXJuIHRoaXMuc2V0KHJlcXVlc3RJZCkuc2lnbmFsXG4gIH1cblxuICBwdWJsaWMgaGFzKHJlcXVlc3RJZDogc3RyaW5nKTogYm9vbGVhbiB7XG4gICAgcmV0dXJuI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QUFDQztJQUMvQjtJQUVPRSxJQUFJRixTQUFpQixFQUFtQjtRQUM3QyxNQUFNRyxhQUFhLElBQUlDO1FBQ3ZCLHlCQUFBLElBQUksRUFBRUgsY0FBWUMsR0FBRyxDQUFDRixXQUFXRztRQUNqQyxPQUFPQTtJQUNUO0lBRU9FLFFBQVFMLFNBQWtCLEVBQXNCO1FBQ3JELElBQUksQ0FBQ0EsV0FBVyxPQUFPO1FBQ3ZCLE9BQU8sSUFBSSxDQUFDRSxHQUFHLENBQUNGLFdBQVdNLE1BQU07SUFDbkM7SUFFT0MsSUFBSVAsU0FBaUIsRUFBVztRQUNyQyxPQUFPLHlCQUFBLElBQUksRUFBRUMsY0FBWU0sR0FBRyxDQUFDUDtJQUMvQjtJQUVPUSxNQUFNUixTQUFrQixFQUFXO1FBQ3hDLE9BQU8seUJBQUEsSUFBSSxFQUFFQyxjQUFZUSxNQUFNLENBQUNULHNCQUFBQSx1QkFBQUEsWUFBYTtJQUMvQztJQUVPVSxNQUFNVixTQUFrQixFQUFXO1FBQ3hDLE1BQU1XLEtBQUtYLHNCQUFBQSx1QkFBQUEsWUFBYTtRQUV4QixJQUFJLENBQUNXLE1BQU0sQ0FBQyxJQUFJLENBQUNKLEdBQUcsQ0FBQ0ksS0FBSyxPQUFPO1FBRWpDLE1BQU1SLGFBQWEsSUFBSSxDQUFDSixHQUFHLENBQUNZO1FBQzVCUixXQUFXTyxLQUFLO1FBQ2hCLE9BQU8sSUFBSSxDQUFDRixLQUFLLENBQUNHO0lBQ3BCO0lBbkNBQyxhQUFjO1FBRmQsZ0NBQVM7O21CQUFULEtBQUE7O3VDQUdRWCxjQUFjLElBQUlZO0lBQzFCO0FBa0NGIn0=","export const DEFAULT_CONFIG = {\n credentials: 'omit',\n cache: 'no-store',\n referrerPolicy: 'no-referrer',\n mode: 'cors',\n timeout: 60000\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9jb25zdC9jb25maWcudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHR5cGUgeyBGZXRjaGVyQ29uZmlnIH0gZnJvbSAnQC90eXBlcydcblxuZXhwb3J0IGNvbnN0IERFRkFVTFRfQ09ORklHOiBPbWl0PEZldGNoZXJDb25maWcsICdiYXNlVXJsJz4gPSB7XG4gIGNyZWRlbnRpYWxzOiAnb21pdCcsXG4gIGNhY2hlOiAnbm8tc3RvcmUnLFxuICByZWZlcnJlclBvbGljeTogJ25vLXJlZmVycmVyJyxcbiAgbW9kZTogJ2NvcnMnLFxuICB0aW1lb3V0OiA2MDAwMCxcbn1cbiJdLCJuYW1lcyI6WyJERUZBVUxUX0NPTkZJRyIsImNyZWRlbnRpYWxzIiwiY2FjaGUiLCJyZWZlcnJlclBvbGljeSIsIm1vZGUiLCJ0aW1lb3V0Il0sInJhbmdlTWFwcGluZ3MiOiI7Ozs7OzsiLCJtYXBwaW5ncyI6IkFBRUEsT0FBTyxNQUFNQSxpQkFBaUQ7SUFDNURDLGFBQWE7SUFDYkMsT0FBTztJQUNQQyxnQkFBZ0I7SUFDaEJDLE1BQU07SUFDTkMsU0FBUztBQUNYLEVBQUMifQ==","export const HEADERS_NORMALIZE_EXCEPTIONS = {\n 'content-md5': 'Content-MD5',\n dnt: 'DNT',\n etag: 'ETag',\n 'last-event-id': 'Last-Event-ID',\n tcn: 'TCN',\n te: 'TE',\n 'www-authenticate': 'WWW-Authenticate',\n 'x-dnsprefetch-control': 'X-DNSPrefetch-Control'\n};\nexport const HEADER_CONTENT_TYPE = 'Content-Type';\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9jb25zdC9oZWFkZXJzLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjb25zdCBIRUFERVJTX05PUk1BTElaRV9FWENFUFRJT05TOiBSZWNvcmQ8c3RyaW5nLCBzdHJpbmc+ID0ge1xuICAnY29udGVudC1tZDUnOiAnQ29udGVudC1NRDUnLFxuICBkbnQ6ICdETlQnLFxuICBldGFnOiAnRVRhZycsXG4gICdsYXN0LWV2ZW50LWlkJzogJ0xhc3QtRXZlbnQtSUQnLFxuICB0Y246ICdUQ04nLFxuICB0ZTogJ1RFJyxcbiAgJ3d3dy1hdXRoZW50aWNhdGUnOiAnV1dXLUF1dGhlbnRpY2F0ZScsXG4gICd4LWRuc3ByZWZldGNoLWNvbnRyb2wnOiAnWC1ETlNQcmVmZXRjaC1Db250cm9sJyxcbn1cblxuZXhwb3J0IGNvbnN0IEhFQURFUl9DT05URU5UX1RZUEUgPSAnQ29udGVudC1UeXBlJ1xuIl0sIm5hbWVzIjpbIkhFQURFUlNfTk9STUFMSVpFX0VYQ0VQVElPTlMiLCJkbnQiLCJldGFnIiwidGNuIiwidGUiLCJIRUFERVJfQ09OVEVOVF9UWVBFIl0sInJhbmdlTWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7IiwibWFwcGluZ3MiOiJBQUFBLE9BQU8sTUFBTUEsK0JBQXVEO0lBQ2xFLGVBQWU7SUFDZkMsS0FBSztJQUNMQyxNQUFNO0lBQ04saUJBQWlCO0lBQ2pCQyxLQUFLO0lBQ0xDLElBQUk7SUFDSixvQkFBb0I7SUFDcEIseUJBQXlCO0FBQzNCLEVBQUM7QUFFRCxPQUFPLE1BQU1DLHNCQUFzQixlQUFjIn0=","export var HTTP_METHODS;\n(function(HTTP_METHODS) {\n HTTP_METHODS[\"GET\"] = \"GET\";\n HTTP_METHODS[\"POST\"] = \"POST\";\n HTTP_METHODS[\"PUT\"] = \"PUT\";\n HTTP_METHODS[\"DELETE\"] = \"DELETE\";\n HTTP_METHODS[\"PATCH\"] = \"PATCH\";\n})(HTTP_METHODS || (HTTP_METHODS = {}));\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9lbnVtcy9odHRwX21ldGhvZHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGVudW0gSFRUUF9NRVRIT0RTIHtcbiAgR0VUID0gJ0dFVCcsXG4gIFBPU1QgPSAnUE9TVCcsXG4gIFBVVCA9ICdQVVQnLFxuICBERUxFVEUgPSAnREVMRVRFJyxcbiAgUEFUQ0ggPSAnUEFUQ0gnLFxufVxuIl0sIm5hbWVzIjpbIkhUVFBfTUVUSE9EUyJdLCJyYW5nZU1hcHBpbmdzIjoiOzs7Ozs7OyIsIm1hcHBpbmdzIjoiO1VBQVlBOzs7Ozs7R0FBQUEsaUJBQUFBIn0=","export var HTTP_STATUS_CODES;\n(function(HTTP_STATUS_CODES) {\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"CONTINUE\"] = 100] = \"CONTINUE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"SWITCHING_PROTOCOLS\"] = 101] = \"SWITCHING_PROTOCOLS\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PROCESSING\"] = 102] = \"PROCESSING\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"OK\"] = 200] = \"OK\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"CREATED\"] = 201] = \"CREATED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"ACCEPTED\"] = 202] = \"ACCEPTED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NON_AUTHORITATIVE_INFORMATION\"] = 203] = \"NON_AUTHORITATIVE_INFORMATION\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NO_CONTENT\"] = 204] = \"NO_CONTENT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"RESET_CONTENT\"] = 205] = \"RESET_CONTENT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PARTIAL_CONTENT\"] = 206] = \"PARTIAL_CONTENT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"MULTI_STATUS\"] = 207] = \"MULTI_STATUS\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"MULTIPLE_CHOICES\"] = 300] = \"MULTIPLE_CHOICES\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"MOVED_PERMANENTLY\"] = 301] = \"MOVED_PERMANENTLY\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"MOVED_TEMPORARILY\"] = 302] = \"MOVED_TEMPORARILY\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"SEE_OTHER\"] = 303] = \"SEE_OTHER\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NOT_MODIFIED\"] = 304] = \"NOT_MODIFIED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"USE_PROXY\"] = 305] = \"USE_PROXY\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"TEMPORARY_REDIRECT\"] = 307] = \"TEMPORARY_REDIRECT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PERMANENT_REDIRECT\"] = 308] = \"PERMANENT_REDIRECT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"BAD_REQUEST\"] = 400] = \"BAD_REQUEST\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"UNAUTHORIZED\"] = 401] = \"UNAUTHORIZED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PAYMENT_REQUIRED\"] = 402] = \"PAYMENT_REQUIRED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"FORBIDDEN\"] = 403] = \"FORBIDDEN\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NOT_FOUND\"] = 404] = \"NOT_FOUND\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"METHOD_NOT_ALLOWED\"] = 405] = \"METHOD_NOT_ALLOWED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NOT_ACCEPTABLE\"] = 406] = \"NOT_ACCEPTABLE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PROXY_AUTHENTICATION_REQUIRED\"] = 407] = \"PROXY_AUTHENTICATION_REQUIRED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"REQUEST_TIMEOUT\"] = 408] = \"REQUEST_TIMEOUT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"CONFLICT\"] = 409] = \"CONFLICT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"GONE\"] = 410] = \"GONE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"LENGTH_REQUIRED\"] = 411] = \"LENGTH_REQUIRED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PRECONDITION_FAILED\"] = 412] = \"PRECONDITION_FAILED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"REQUEST_TOO_LONG\"] = 413] = \"REQUEST_TOO_LONG\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"REQUEST_URI_TOO_LONG\"] = 414] = \"REQUEST_URI_TOO_LONG\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"UNSUPPORTED_MEDIA_TYPE\"] = 415] = \"UNSUPPORTED_MEDIA_TYPE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"REQUESTED_RANGE_NOT_SATISFIABLE\"] = 416] = \"REQUESTED_RANGE_NOT_SATISFIABLE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"EXPECTATION_FAILED\"] = 417] = \"EXPECTATION_FAILED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"IM_A_TEAPOT\"] = 418] = \"IM_A_TEAPOT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"INSUFFICIENT_SPACE_ON_RESOURCE\"] = 419] = \"INSUFFICIENT_SPACE_ON_RESOURCE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"METHOD_FAILURE\"] = 420] = \"METHOD_FAILURE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"MISDIRECTED_REQUEST\"] = 421] = \"MISDIRECTED_REQUEST\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"UNPROCESSABLE_ENTITY\"] = 422] = \"UNPROCESSABLE_ENTITY\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"LOCKED\"] = 423] = \"LOCKED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"FAILED_DEPENDENCY\"] = 424] = \"FAILED_DEPENDENCY\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"PRECONDITION_REQUIRED\"] = 428] = \"PRECONDITION_REQUIRED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"TOO_MANY_REQUESTS\"] = 429] = \"TOO_MANY_REQUESTS\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"REQUEST_HEADER_FIELDS_TOO_LARGE\"] = 431] = \"REQUEST_HEADER_FIELDS_TOO_LARGE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"UNAVAILABLE_FOR_LEGAL_REASONS\"] = 451] = \"UNAVAILABLE_FOR_LEGAL_REASONS\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"INTERNAL_SERVER_ERROR\"] = 500] = \"INTERNAL_SERVER_ERROR\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NOT_IMPLEMENTED\"] = 501] = \"NOT_IMPLEMENTED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"BAD_GATEWAY\"] = 502] = \"BAD_GATEWAY\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"SERVICE_UNAVAILABLE\"] = 503] = \"SERVICE_UNAVAILABLE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"GATEWAY_TIMEOUT\"] = 504] = \"GATEWAY_TIMEOUT\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"HTTP_VERSION_NOT_SUPPORTED\"] = 505] = \"HTTP_VERSION_NOT_SUPPORTED\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"INSUFFICIENT_STORAGE\"] = 507] = \"INSUFFICIENT_STORAGE\";\n HTTP_STATUS_CODES[HTTP_STATUS_CODES[\"NETWORK_AUTHENTICATION_REQUIRED\"] = 511] = \"NETWORK_AUTHENTICATION_REQUIRED\";\n})(HTTP_STATUS_CODES || (HTTP_STATUS_CODES = {}));\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9lbnVtcy9odHRwX3N0YXR1c19jb2Rlcy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZW51bSBIVFRQX1NUQVRVU19DT0RFUyB7XG4gIENPTlRJTlVFID0gMTAwLFxuICBTV0lUQ0hJTkdfUFJPVE9DT0xTID0gMTAxLFxuICBQUk9DRVNTSU5HID0gMTAyLFxuICBPSyA9IDIwMCxcbiAgQ1JFQVRFRCA9IDIwMSxcbiAgQUNDRVBURUQgPSAyMDIsXG4gIE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OID0gMjAzLFxuICBOT19DT05URU5UID0gMjA0LFxuICBSRVNFVF9DT05URU5UID0gMjA1LFxuICBQQVJUSUFMX0NPTlRFTlQgPSAyMDYsXG4gIE1VTFRJX1NUQVRVUyA9IDIwNyxcbiAgTVVMVElQTEVfQ0hPSUNFUyA9IDMwMCxcbiAgTU9WRURfUEVSTUFORU5UTFkgPSAzMDEsXG4gIE1PVkVEX1RFTVBPUkFSSUxZID0gMzAyLFxuICBTRUVfT1RIRVIgPSAzMDMsXG4gIE5PVF9NT0RJRklFRCA9IDMwNCxcbiAgVVNFX1BST1hZID0gMzA1LFxuICBURU1QT1JBUllfUkVESVJFQ1QgPSAzMDcsXG4gIFBFUk1BTkVOVF9SRURJUkVDVCA9IDMwOCxcbiAgQkFEX1JFUVVFU1QgPSA0MDAsXG4gIFVOQVVUSE9SSVpFRCA9IDQwMSxcbiAgUEFZTUVOV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0lNUExFTUVOVEVEID0gNTAxLFxuICBCQURfR0FURVdBWSA9IDUwMixcbiAgU0VSVklDRV9VTkFWQUlMQUJMRSA9IDUwMyxcbiAgR0FURVdBWV9USU1FT1VUID0gNTA0LFxuICBIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRCA9IDUwNSxcbiAgSU5TVUZGSUNJRU5UX1NUT1JBR0UgPSA1MDcsXG4gIE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQgPSA1MTEsXG59XG4iXSwibmFtZXMiOlsiSFRUUF9TVEFUVVNfQ09ERVMiXSwicmFuZ2VNYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OzsiLCJtYXBwaW5ncyI6IjtVQUFZQTs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBQUFBLHNCQUFBQSJ9","function _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nexport class FetcherError extends Error {\n constructor(resp){\n super(resp.statusText);\n _define_property(this, \"name\", 'FetcherError');\n _define_property(this, \"response\", void 0);\n _define_property(this, \"request\", void 0);\n this.response = resp;\n this.request = resp.request;\n }\n}\nexport class FetcherURLParseError extends Error {\n constructor(e = new TypeError('Failed to parse URL')){\n super(e.toString());\n _define_property(this, \"name\", 'FetcherURLParseError');\n }\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9lcnJvci50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSB7IEZldGNoZXJSZXF1ZXN0LCBGZX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O1FBQ3BDLEtBQUssQ0FBQ0EsS0FBS0MsVUFBVTtRQUx2Qix1QkFBT0MsUUFBTztRQUNkLHVCQUFPQyxZQUFQLEtBQUE7UUFDQSx1QkFBT0MsV0FBUCxLQUFBO1FBSUUsSUFBSSxDQUFDRCxRQUFRLEdBQUdIO1FBQ2hCLElBQUksQ0FBQ0ksT0FBTyxHQUFHSixLQUFLSSxPQUFPO0lBQzdCO0FBQ0Y7QUFFQSxPQUFPLE1BQU1DLDZCQUE2QlA7SUFHeENDLFlBQVlPLElBQUksSUFBSUMsVUFBVSxzQkFBc0IsQ0FBRTtRQUNwRCxLQUFLLENBQUNELEVBQUVFLFFBQVE7UUFIbEIsdUJBQU9OLFFBQU87SUFJZDtBQUNGIn0=","import { HTTP_STATUS_CODES } from \"../enums\";\nconst EMPTY_BODY_STATUS_CODES = {\n [HTTP_STATUS_CODES.NO_CONTENT]: true,\n [HTTP_STATUS_CODES.RESET_CONTENT]: true\n};\nexport const isEmptyBodyStatusCode = (code)=>{\n return Boolean(EMPTY_BODY_STATUS_CODES[code]);\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL2VtcHR5LWJvZHkudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgSFRUUF9TVEFUVVNfQ09ERVMgfSBmcm9tICdAL2VudW1zJ1xuXG5jb25zdCBFTVBUWV9CT0RZX1NUQVRVU19DT0RFUzogeyBba2V5IGluIEhUVFBfU1RBVFVTX0NPREVTXT86IGJvb2xlYW4gfSA9IHtcbiAgW0hUVFBfU1RBVFVTX0NPREVTLk5PX0NPTlRFTlRdOiB0cnVlLFxuICBbSFRUUF9TVEFUVVNfQ09ERVMuUkVTRVRfQ09OVEVOVF06IHRydWUsXG59XG5cbmV4cG9ydCBjb25zdCBpc0VtcHR5Qm9keVN0YXR1c0NvZGUgPSAoY29kZTogbnVtYmVyKTogYm9vbGVhbiA9PiB7XG4gIHJldHVybiBCb29sZWFuKEVNUFRZX0JPRFlfU1RBVFVTX0NPREVTW2NvZGUgYXMgSFRUUF9TVEFUVVNfQ09ERVNdKVxufVxuIl0sIm5hbWVzIjpbIkhUVFBfU1RBVFVTX0NPREVTIiwiRU1QVFlfQk9EWV9TVEFUVVNfQ09ERVMiLCJOT19DT05URU5UIiwiUkVTRVRfQ09OVEVOVCIsImlzRW1wdHlCb2R5U3RhdHVzQ29kZSIsImNvZGUiLCJCb29sZWFuIl0sInJhbmdlTWFwcGluZ3MiOiI7Ozs7Ozs7IiwibWFwcGluZ3MiOiJBQUFBLFNBQVNBLGlCQUFpQixRQUFRLFdBQVM7QUFFM0MsTUFBTUMsMEJBQW9FO0lBQ3hFLENBQUNELGtCQUFrQkUsVUFBVSxDQUFDLEVBQUU7SUFDaEMsQ0FBQ0Ysa0JBQWtCRyxhQUFhLENBQUMsRUFBRTtBQUNyQztBQUVBLE9BQU8sTUFBTUMsd0JBQXdCLENBQUNDO0lBQ3BDLE9BQU9DLFFBQVFMLHVCQUF1QixDQUFDSSxLQUEwQjtBQUNuRSxFQUFDIn0=","const isObjectLike = (value)=>{\n return typeof value === 'object' && value !== null;\n};\nconst getTag = (value)=>{\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return toString.call(value);\n};\nexport const isObject = (value)=>{\n if (!isObjectLike(value) || getTag(value) != '[object Object]') return false;\n if (Object.getPrototypeOf(value) === null) return true;\n let proto = value;\n while(Object.getPrototypeOf(proto) !== null){\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(value) === proto;\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL2lzLW9iamVjdC50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJjb25zdCBpc09iamVjdExpa2UgPSAodmFsdWU6IHVua25vd24pOiBib29sZWFuID0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QixPQUFPLE9BQU9BLFVBQVUsWUFBWUEsVUFBVTtBQUNoRDtBQUVBLE1BQU1DLFNBQVMsQ0FBQ0Q7SUFDZCxJQUFJQSxTQUFTLE1BQU07UUFDakIsT0FBT0EsVUFBVUUsWUFBWSx1QkFBdUI7SUFDdEQ7SUFDQSxPQUFPQyxTQUFTQyxJQUFJLENBQUNKO0FBQ3ZCO0FBRUEsT0FBTyxNQUFNSyxXQUFXLENBQUNMO0lBQ3ZCLElBQUksQ0FBQ0QsYUFBYUMsVUFBVUMsT0FBT0QsVUFBVSxtQkFBbUIsT0FBTztJQUN2RSxJQUFJTSxPQUFPQyxjQUFjLENBQUNQLFdBQVcsTUFBTSxPQUFPO0lBRWxELElBQUlRLFFBQVFSO0lBRVosTUFBT00sT0FBT0MsY0FBYyxDQUFDQyxXQUFXLEtBQU07UUFDNUNBLFFBQVFGLE9BQU9DLGNBQWMsQ0FBQ0M7SUFDaEM7SUFDQSxPQUFPRixPQUFPQyxjQUFjLENBQUNQLFdBQVdRO0FBQzFDLEVBQUMifQ==","import { HEADERS_NORMALIZE_EXCEPTIONS } from \"../const\";\nexport const normalizeHeadersCase = (headers)=>{\n return Object.entries(headers).reduce((acc, [key, value])=>{\n acc[normalizeHeaderCase(key)] = value;\n return acc;\n }, {});\n};\nconst normalizeHeaderCase = (header)=>{\n const exceptionHeader = HEADERS_NORMALIZE_EXCEPTIONS[header.toLowerCase()];\n if (exceptionHeader) return exceptionHeader;\n return header.split('-').map(function(text) {\n return text.charAt(0).toUpperCase() + text.substring(1).toLowerCase();\n }).join('-');\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL25vcm1hbGl6ZS1oZWFkZXItY2FzZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBIRUFERVJTX05PUk1BTElaRV9FWENFUFRJT05TIH0gZnJvbSAnQC9jb25zdCdcblx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GFyQXQiLCJ0b1VwcGVyQ2FzZSIsInN1YnN0cmluZyIsImpvaW4iXSwicmFuZ2VNYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7OzsiLCJtYXBwaW5ncyI6IkFBQUEsU0FBU0EsNEJBQTRCLFFBQVEsV0FBUztBQUV0RCxPQUFPLE1BQU1DLHVCQUF1QixDQUFDQztJQUNuQyxPQUFPQyxPQUFPQyxPQUFPLENBQUNGLFNBQVNHLE1BQU0sQ0FBQyxDQUFDQyxLQUFLLENBQUNDLEtBQUtDLE1BQU07UUFDdERGLEdBQUcsQ0FBQ0csb0JBQW9CRixLQUFLLEdBQUdDO1FBRWhDLE9BQU9GO0lBQ1QsR0FBRyxDQUFDO0FBQ04sRUFBQztBQUVELE1BQU1HLHNCQUFzQixDQUFDQztJQUMzQixNQUFNQyxrQkFBa0JYLDRCQUE0QixDQUFDVSxPQUFPRSxXQUFXLEdBQUc7SUFFMUUsSUFBSUQsaUJBQWlCLE9BQU9BO0lBRTVCLE9BQU9ELE9BQ0pHLEtBQUssQ0FBQyxLQUNOQyxHQUFHLENBQUMsU0FBVUMsSUFBSTtRQUNqQixPQUFPQSxLQUFLQyxNQUFNLENBQUMsR0FBR0MsV0FBVyxLQUFLRixLQUFLRyxTQUFTLENBQUMsR0FBR04sV0FBVztJQUNyRSxHQUNDTyxJQUFJLENBQUM7QUFDViJ9","function _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _object_spread(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n _define_property(target, key, source[key]);\n });\n }\n return target;\n}\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) {\n symbols = symbols.filter(function(sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n keys.push.apply(keys, symbols);\n }\n return keys;\n}\nfunction _object_spread_props(target, source) {\n source = source != null ? source : {};\n if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function(key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n}\nimport { HEADER_CONTENT_TYPE } from \"../const\";\nimport { isObject } from \"./is-object\";\nimport { normalizeHeadersCase } from \"./normalize-header-case\";\nexport const buildRequest = (cfg, requestCfg, abortManager)=>{\n const url = buildRequestURL(cfg.baseUrl, requestCfg.endpoint, requestCfg.query);\n const config = buildRequestConfig(cfg, requestCfg, abortManager);\n return _object_spread_props(_object_spread({}, config), {\n url\n });\n};\nexport const buildRequestURL = (baseUrl, endpoint, query)=>{\n const parsedUrl = new URL(baseUrl);\n // To parse query params from endpoint correctly, we need to reparse it\n // otherwise query params could be serialized incorrectly\n // (ex. \"?\" symbol will be encoded to \"%3F\")\n const url = new URL([\n parsedUrl.origin,\n parsedUrl.pathname,\n endpoint\n ].join('/').replace(/\\/\\/+/g, '/').// replace doubled slashes\n replace(/\\/+$/, ''));\n // remove slash in the end\n if (!query) return url.toString();\n Object.entries(query).forEach(([key, value])=>{\n validateQueryValue(value);\n url.searchParams.append(key, value.toString());\n });\n return url.toString();\n};\nconst validateQueryValue = (value)=>{\n if (!isObject(value)) return;\n throw new TypeError(\"Fetcher: query parameters can't have nested objects.\");\n};\nexport const buildRequestConfig = (cfg, requestCfg, abortManager)=>{\n const body = buildRequestBody(requestCfg.body);\n const headers = normalizeHeadersCase(_object_spread({}, cfg.headers, requestCfg.headers));\n if (body instanceof FormData && headers[HEADER_CONTENT_TYPE]) {\n // FormData will set the Content-Type header automatically\n // https://stackoverflow.com/questions/39280438/fetch-missing-boundary-in-multipart-form-data-post\n delete headers[HEADER_CONTENT_TYPE];\n }\n return _object_spread({\n body,\n headers,\n method: requestCfg.method,\n credentials: cfg.credentials,\n cache: cfg.cache,\n referrerPolicy: cfg.referrerPolicy,\n signal: abortManager.setSafe(requestCfg.id)\n }, cfg.referrer ? {\n referrer: cfg.referrer\n } : {});\n};\nexport const buildRequestBody = (body)=>{\n if (!body) return null;\n if (isObject(body)) {\n return JSON.stringify(body);\n }\n return body;\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL3JlcXVlc3QudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHR5cGUgeyBGZXRjaGVyQWJvcnRNYW5hZ2VyIH0gZnJvbSAnQC9hYm9ydC1tYW5hZ2VyJ1xuaW1wb3J0IHsgSEVBREVSX0NPTlRFTlRfVFlQRSB9IGZyb20gJ0AvY29uc3QnXG5pbXBvcnQgdHlwZSB7XG4gIEZldGNoZXJDb25maWcsXG4gIEZldGNoZXJSZXF1ZXN0LFxuICBGZXRjaGVyUmVxdWVzdEJvZHksXG4gIEZldGNoZXJSZXF1ZXN0Q29uZmlnLFxuICBGZXRjaGVyUmVxdWVzdFF1ZXJ5LFxufSBmcm9tICdAL3R5cGVzJ1xuXG5pbXBvcnQgeyBpc09iamVjdCB9IGZyb20gJy4vaXMtb2JqZWN0J1xuaW1wb3J0IHsgbm9ybWFsaXplSGVhZGVyc0Nhc2UgfSBmcm9tICcuL25vcm1hbGl6ZS1oZWFkZXItY2FzZSdcblxuZXhwb3J0IGNvbnN0IGJ1aWxkUmVxdWVzdCA9IChcbiAgY2ZnOiBGZXRjaGVyQ29uZmlnLFxuICByZXF1ZXN0Q2ZnOiBGZXRjaGVyUmVxdWV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JQUVBLE1BQU13QixPQUFPQyxpQkFBaUIxQixXQUFXeUIsSUFBSTtJQUU3QyxNQUFNRSxVQUFVOUIscUJBQXFCLG1CQUNoQ0UsSUFBSTRCLE9BQU8sRUFDWDNCLFdBQVcyQixPQUFPO0lBR3ZCLElBQUlGLGdCQUFnQkcsWUFBWUQsT0FBTyxDQUFDaEMsb0JBQW9CLEVBQUU7UUFDNUQsMERBQTBEO1FBQzFELGtHQUFrRztRQUNsRyxPQUFPZ0MsT0FBTyxDQUFDaEMsb0JBQW9CO0lBQ3JDO0lBRUEsT0FBTztRQUNMOEI7UUFDQUU7UUFDQUUsUUFBUTdCLFdBQVc2QixNQUFNO1FBQ3pCQyxhQUFhL0IsSUFBSStCLFdBQVc7UUFDNUJDLE9BQU9oQyxJQUFJZ0MsS0FBSztRQUNoQkMsZ0JBQWdCakMsSUFBSWlDLGNBQWM7UUFDbENDLFFBQVFoQyxhQUFhaUMsT0FBTyxDQUFDbEMsV0FBV21DLEVBQUU7T0FDdENwQyxJQUFJcUMsUUFBUSxHQUFHO1FBQUVBLFVBQVVyQyxJQUFJcUMsUUFBUTtJQUFDLElBQUksQ0FBQztBQUVyRCxFQUFDO0FBRUQsT0FBTyxNQUFNVixtQkFBbUIsQ0FDOUJEO0lBRUEsSUFBSSxDQUFDQSxNQUFNLE9BQU87SUFFbEIsSUFBSTdCLFNBQVM2QixPQUFPO1FBQ2xCLE9BQU9ZLEtBQUtDLFNBQVMsQ0FBQ2I7SUFDeEI7SUFFQSxPQUFPQTtBQUNULEVBQUMifQ==","export const validateBaseUrl = (baseUrl)=>{\n try {\n new URL(baseUrl);\n } catch (err) {\n throw new TypeError(`Fetcher: invalid base URL. ${err.toString()}`);\n }\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL3ZhbGlkYXRlLWJhc2UtdXJsLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjb25zdCB2YWxpZGF0ZUJhc2VVcmwgPSAoYmFzZVVybDogc3RyaW5nKTogdm9pZCA9PiB7XG4gIHRyeSB7XG4gICAgbmV3IFVSTChiYXNlVXJsKVxuICB9IGNhdGNoIChlcnIpIHtcbiAgICB0aHJvdyBuZXcgVHlwZUVycm9yKFxuICAgICAgYEZldGNoZXI6IGludmFsaWQgYmFzZSBVUkwuICR7KGVyciBhcyBFcnJvcikudG9TdHJpbmcoKX1gLFxuICAgIClcbiAgfVxufVxuIl0sIm5hbWVzIjpbInZhbGlkYXRlQmFzZVVybCIsImJhc2VVcmwiLCJVUkwiLCJlcnIiLCJUeXBlRXJyb3IiLCJ0b1N0cmluZyJdLCJyYW5nZU1hcHBpbmdzIjoiOzs7Ozs7IiwibWFwcGluZ3MiOiJBQUFBLE9BQU8sTUFBTUEsa0JBQWtCLENBQUNDO0lBQzlCLElBQUk7UUFDRixJQUFJQyxJQUFJRDtJQUNWLEVBQUUsT0FBT0UsS0FBSztRQUNaLE1BQU0sSUFBSUMsVUFDUixDQUFDLDJCQUEyQixFQUFFLEFBQUNELElBQWNFLFFBQVEsR0FBRyxDQUFDO0lBRTdEO0FBQ0YsRUFBQyJ9","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nfunction _async_to_generator(fn) {\n return function() {\n var self = this, args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\nfunction _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _class_private_method_get(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return fn;\n}\nfunction _class_private_method_init(obj, privateSet) {\n _check_private_redeclaration(obj, privateSet);\n privateSet.add(obj);\n}\nvar _interceptors = new WeakMap(), _runResponseInterceptors = new WeakSet();\nexport class FetcherInterceptorManager {\n get interceptors() {\n return _class_private_field_get(this, _interceptors);\n }\n add(interceptor) {\n _class_private_field_get(this, _interceptors).push(interceptor);\n }\n remove(interceptor) {\n const index = _class_private_field_get(this, _interceptors).indexOf(interceptor);\n if (!~index) return;\n _class_private_field_get(this, _interceptors).splice(index, 1);\n }\n clear() {\n _class_private_field_set(this, _interceptors, []);\n }\n runRequestInterceptors(request) {\n var _this = this;\n return _async_to_generator(function*() {\n let req = request;\n for (const interceptor of _class_private_field_get(_this, _interceptors)){\n if (interceptor.request) {\n req = yield interceptor.request(req);\n }\n }\n return req;\n })();\n }\n // @distributedlab/web-kit\n //\n runResponseInterceptors(response) {\n var _this = this;\n return _async_to_generator(function*() {\n return _class_private_method_get(_this, _runResponseInterceptors, runResponseInterceptors).call(_this, response, 'response');\n })();\n }\n runErrorInterceptors(response) {\n var _this = this;\n return _async_to_generator(function*() {\n return _class_private_method_get(_this, _runResponseInterceptors, runResponseInterceptors).call(_this, response, 'error');\n })();\n }\n constructor(interceptors){\n _class_private_method_init(this, _runResponseInterceptors);\n _class_private_field_init(this, _interceptors, {\n writable: true,\n value: []\n });\n if (interceptors) {\n _class_private_field_set(this, _interceptors, [\n ...interceptors\n ]);\n }\n }\n} /*#__PURE__*/ /*#__PURE__*/ \nfunction runResponseInterceptors(response, fnName) {\n return _runResponseInterceptors1.apply(this, arguments);\n}\nfunction _runResponseInterceptors1() {\n _runResponseInterceptors1 = _async_to_generator(function*(response, fnName) {\n let resp = response;\n for (const interceptor of _class_private_field_get(this, _interceptors)){\n const fn = interceptor[fnName];\n if (fn) resp = yield fn(resp);\n }\n return resp;\n });\n return _runResponseInterceptors1.apply(this, arguments);\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9pbnRlcmNlcHRvci1tYW5hZ2VyLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB0eXBlIHtcbiAgRmV0Y2hlckludGVyY2VwdG9yLFxuICBGZXRjaGVyUmVxdWVzdCxcbiAgRmV0Y2hlclJlc3BvbnNlLFxufSBmcm9tICdAL3R5cGVzJ1xuXG5leHBvcnQgY2xhc3MgRmV0Y2hlckludGVyY2VwdG9yTWFuYWdlciB7XG4gICNpbnRlcmNlcHRvcnM6IEZldGNoZXJJbnRlcmNlcHRvcltdID0gW11cblxuICBjb25zdHJ1Y3RvcihpbnRlcmNlcHRvcnM/OiBGZXRjaGVySW50ZXJjZXB0b3JbXSkge1xuICAgIGlmIChpbnRlcmNlcHRvcnMpIHtc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g);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nfunction _async_to_generator(fn) {\n return function() {\n var self = this, args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\nfunction _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _class_private_method_get(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return fn;\n}\nfunction _class_private_method_init(obj, privateSet) {\n _check_private_redeclaration(obj, privateSet);\n privateSet.add(obj);\n}\nimport { isEmptyBodyStatusCode } from \"./helpers\";\nvar _response = new WeakMap(), _result = new WeakMap(), _extractData = new WeakSet(), _tryToParseJson = new WeakSet(), _tryToParseBlob = new WeakSet(), _tryToParseFormData = new WeakSet(), _tryToWrapper = new WeakSet();\nexport class FetcherResponseBuilder {\n build() {\n var _this = this;\n return _async_to_generator(function*() {\n if (!_class_private_field_get(_this, _response) || isEmptyBodyStatusCode(_class_private_field_get(_this, _response).status)) {\n return _class_private_field_get(_this, _result);\n }\n yield _class_private_method_get(_this, _extractData, extractData).call(_this);\n return _class_private_field_get(_this, _result);\n })();\n }\n populateResponse(response) {\n _class_private_field_set(this, _response, response.clone());\n _class_private_field_get(this, _result).ok = response.ok;\n _class_private_field_get(this, _result).status = response.status;\n _class_private_field_get(this, _result).statusText = response.statusText;\n _class_private_field_get(this, _result).headers = response.headers;\n _class_private_field_get(this, _result).url = response.url;\n return this;\n }\n constructor(request, response){\n _class_private_method_init(this, _extractData);\n _class_private_method_init(this, _tryToParseJson);\n _class_private_method_init(this, _tryToParseBlob);\n _class_private_method_init(this, _tryToParseFormData);\n _class_private_method_init(this, _tryToWrapper);\n _class_private_field_init(this, _response, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _result, {\n writable: true,\n value: void 0\n });\n _class_private_field_set(this, _result, {\n ok: false,\n status: 0,\n statusText: '',\n headers: {},\n url: '',\n request: request || {\n url: ''\n }\n });\n if (response) {\n this.populateResponse(response);\n }\n }\n} /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ \nfunction extractData() {\n return _extractData1.apply(this, arguments);\n}\nfunction _extractData1() {\n _extractData1 = _async_to_generator(function*() {\n if (!_class_private_field_get(this, _response)) return;\n if (isEmptyBodyStatusCode(_class_private_field_get(this, _response).status)) return;\n const parsers = [\n _class_private_method_get(this, _tryToParseJson, tryToParseJson).bind(this),\n _class_private_method_get(this, _tryToParseFormData, tryToParseFormData).bind(this),\n // TODO: check if it's possible to parse formData\n ..._class_private_field_get(this, _response).ok ? [\n _class_private_method_get(this, _tryToParseBlob, tryToParseBlob).bind(this)\n ] : []\n ];\n for (const parser of parsers){\n const isParsed = yield parser();\n if (isParsed) break;\n }\n });\n return _extractData1.apply(this, arguments);\n}\nfunction tryToParseJson() {\n return _tryToParseJson1.apply(this, arguments);\n}\nfunction _tryToParseJson1() {\n _tryToParseJson1 = _async_to_generator(function*() {\n var _class_private_field_get_clone, _class_private_field_get1;\n // Clone response to be able to read response body multiple times\n // https://developer.mozilla.org/en-US/docs/Web/API/Response/bodyUsed\n return _class_private_method_get(this, _tryToWrapper, tryToWrapper).call(this, (_class_private_field_get1 = _class_private_field_get(this, _response)) === null || _class_private_field_get1 === void 0 ? void 0 : (_class_private_field_get_clone = _class_private_field_get1.clone()) === null || _class_private_field_get_clone === void 0 ? void 0 : _class_private_field_get_clone.json());\n });\n return _tryToParseJson1.apply(this, arguments);\n}\nfunction tryToParseBlob() {\n return _tryToParseBlob1.apply(this, arguments);\n}\nfunction _tryToParseBlob1() {\n _tryToParseBlob1 = _async_to_generator(function*() {\n var _class_private_field_get_clone, _class_private_field_get1;\n return _class_private_method_get(this, _tryToWrapper, tryToWrapper).call(this, (_class_private_field_get1 = _class_private_field_get(this, _response)) === null || _class_private_field_get1 === void 0 ? void 0 : (_class_private_field_get_clone = _class_private_field_get1.clone()) === null || _class_private_field_get_clone === void 0 ? void 0 : _class_private_field_get_clone.blob());\n });\n return _tryToParseBlob1.apply(this, arguments);\n}\nfunction tryToParseFormData() {\n return _tryToParseFormData1.apply(this, arguments);\n}\nfunction _tryToParseFormData1() {\n _tryToParseFormData1 = _async_to_generator(function*() {\n var _class_private_field_get_clone, _class_private_field_get1;\n return _class_private_method_get(this, _tryToWrapper, tryToWrapper).call(this, (_class_private_field_get1 = _class_private_field_get(this, _response)) === null || _class_private_field_get1 === void 0 ? void 0 : (_class_private_field_get_clone = _class_private_field_get1.clone()) === null || _class_private_field_get_clone === void 0 ? void 0 : _class_private_field_get_clone.formData());\n });\n return _tryToParseFormData1.apply(this, arguments);\n}\nfunction tryToWrapper(promise) {\n return _tryToWrapper1.apply(this, arguments);\n}\nfunction _tryToWrapper1() {\n _tryToWrapper1 = _async_to_generator(function*(promise) {\n try {\n _class_private_field_get(this, _result).data = yield promise;\n return true;\n } catch (e) {\n return false;\n }\n });\n return _tryToWrapper1.apply(this, arguments);\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9yZXNwb25zZS1idWlsZGVyLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IGlzRW1wdHlCb2R5U3RhdHVzQ29kZSB9IGZyb20gJ0AvaGVscGVycydcbmltcG9ydCB0eXBlIHsgRmV0Y2hlclJlcXVlc3QsIEZldGNoZXJSZXNwb25zZSB9IGZyb20gJ0AvdHlwZXMnXG5cbmV4cG9ydCBjbGFzcyBGZXRjaGVyUmVzcG9uc2VCdWlsZGVyPFQ+IHtcbiAgI3Jlc3BvbnNlPzogUmVzcG9uc2VcbiAgcmVhZG9ubHkgI3Jlc3VsdDogRmV0Y2hlclJlc3BvbnNlPFQ+XG5cbiAgY29uc3RydWN0b3IocmVxdWVzdD86IEZldGNoZXJSZXF1ZXN0LCByZXNwb25zZT86IFJlc3BvbnNlKSB7XG4gICAgdGhpcy4jcmVzdWx0ID0ge1xuICAgICAgb2s6IGZhbHNlLFxuICAgICAgc3RhdHVzOiAwLFxuICAgICAgc3RhdHVzVGV4dDogJycsXG4gICAgICBoZWFkZXJzOiB7fSBhcyBIZWFkZXJzLFxuICAgICAgdXJsOiAnJyxcbiAgICAgIHJlcXVlc3Q6IHJlcXVlc3QgfHwgeyB1cmw6ICcnIH0sXG4gICAgfVxuXG4gICAgaWYgKHJlc3BvbnNlKSB7XG4gICAgICB0aGlzLnBvcHVsYXRlUmVzcG9uc2UocmVzcG9uc2UpX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CLHlFQUFOLGlDQUFBLDBCQUFnQkssS0FBSyxnQkFBckIscURBQUEsK0JBQXlCZSxJQUFJO0lBQ3pEO1dBSkE7O1NBTUE7V0FBQTs7U0FBQTtJQUFBLG1CQUFBLG9CQUFBO1lBQzRCO1FBQTFCLE9BQU8sMEJBQUEsSUFBSSxFQUFFRCxlQUFBQSxtQkFBTixJQUFJLHdEQUFlLElBQUksRUFBRW5CLHlFQUFOLGlDQUFBLDBCQUFnQkssS0FBSyxnQkFBckIscURBQUEsK0JBQXlCZ0IsSUFBSTtJQUN6RDtXQUZBOztTQUlBO1dBQUE7O1NBQUE7SUFBQSx1QkFBQSxvQkFBQTtZQUM0QjtRQUExQixPQUFPLDBCQUFBLElBQUksRUFBRUYsZUFBQUEsbUJBQU4sSUFBSSx3REFBZSxJQUFJLEVBQUVuQix5RUFBTixpQ0FBQSwwQkFBZ0JLLEtBQUssZ0JBQXJCLHFEQUFBLCtCQUF5QmlCLFFBQVE7SUFDN0Q7V0FGQTs7U0FJQSxhQUFvQkMsT0FBbUI7V0FBdkM7O1NBQUE7SUFBQSxpQkFBQSxvQkFBQSxVQUFvQkEsT0FBbUI7UUFDckMsSUFBSTtZQUNGLHlCQUFBLElBQUksRUFBRXJCLFNBQU9zQixJQUFJLEdBQUksTUFBTUQ7WUFDM0IsT0FBTztRQUNULEVBQUUsT0FBT0UsR0FBRztZQUNWLE9BQU87UUFDVDtJQUNGO1dBUEEifQ==","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nfunction _async_to_generator(fn) {\n return function() {\n var self = this, args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\nfunction _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _class_private_method_get(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return fn;\n}\nfunction _class_private_method_init(obj, privateSet) {\n _check_private_redeclaration(obj, privateSet);\n privateSet.add(obj);\n}\nfunction _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _object_spread(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n _define_property(target, key, source[key]);\n });\n }\n return target;\n}\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) {\n symbols = symbols.filter(function(sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n keys.push.apply(keys, symbols);\n }\n return keys;\n}\nfunction _object_spread_props(target, source) {\n source = source != null ? source : {};\n if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function(key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n}\nimport { v4 as uuid } from \"uuid\";\nimport { FetcherAbortManager } from \"./abort-manager\";\nimport { DEFAULT_CONFIG } from \"./const\";\nimport { HTTP_METHODS } from \"./enums\";\nimport { FetcherError } from \"./error\";\nimport { buildRequest, validateBaseUrl } from \"./helpers\";\nimport { FetcherInterceptorManager } from \"./interceptor-manager\";\nimport { FetcherResponseBuilder } from \"./response-builder\";\nvar _abortManager = new WeakMap(), _interceptorManager = new WeakMap(), _config = new WeakMap(), _executeRequest = new WeakSet();\nexport class Fetcher {\n get config() {\n return _class_private_field_get(this, _config);\n }\n /**\n * Base URL will be prepended to `url` unless `url` is absolute.\n * It can be convenient to set `baseURL` for an instance of Fetcher to pass\n * relative URLs to methods of that instance.\n */ get baseUrl() {\n return _class_private_field_get(this, _config).baseUrl;\n }\n /**\n * Returns the {@link FetcherAbortManager} instance.\n */ get abortManager() {\n return _class_private_field_get(this, _abortManager);\n }\n /**\n * Returns the {@link FetcherInterceptorManager} instance.\n */ get interceptorManager() {\n return _class_private_field_get(this, _interceptorManager);\n }\n /**\n * Clones current Fetcher instance.\n */ clone() {\n return new Fetcher(_class_private_field_get(this, _config), _class_private_field_get(this, _interceptorManager).interceptors);\n }\n /**\n * Sets new interceptor to the current instance.\n */ addInterceptor(interceptor) {\n _class_private_field_get(this, _interceptorManager).add(interceptor);\n }\n /**\n * Removes the existing interceptor from the current instance.\n */ removeInterceptor(interceptor) {\n _class_private_field_get(this, _interceptorManager).remove(interceptor);\n }\n /**\n * Clears all existing interceptors from the current instance.\n */ clearInterceptors() {\n _class_private_field_get(this, _interceptorManager).clear();\n }\n /**\n * Assigns new base URL to the current instance.\n */ useBaseUrl(baseUrl) {\n validateBaseUrl(baseUrl);\n _class_private_field_get(this, _config).baseUrl = baseUrl;\n return this;\n }\n /**\n * Creates new instance Fetcher instance with given base URL.\n */ withBaseUrl(baseUrl) {\n return this.clone().useBaseUrl(baseUrl);\n }\n updateConfig(config) {\n _class_private_field_set(this, _config, _object_spread({}, _class_private_field_get(this, _config), config));\n }\n /**\n * Interrupts the request by given `requestId`, if request is not found returns `false`.\n */ abort(requestId) {\n return _class_private_field_get(this, _abortManager).abort(requestId);\n }\n /**\n * Generates new request id in the UUID format.\n */ createRequestId() {\n return uuid();\n }\n /**\n * Performs a http request.\n */ request(cfg) {\n var _this = this;\n return _async_to_generator(function*() {\n let result;\n const reqConfig = _object_spread_props(_object_spread({}, cfg), {\n id: cfg.id || _this.createRequestId()\n });\n const req = buildRequest(_class_private_field_get(_this, _config), reqConfig, _class_private_field_get(_this, _abortManager));\n const builder = new FetcherResponseBuilder(req);\n const raw = yield _class_private_method_get(_this, _executeRequest, executeRequest).call(_this, reqConfig.id, req);\n const response = yield builder.populateResponse(raw).build();\n result = yield _class_private_field_get(_this, _interceptorManager).runResponseInterceptors(response);\n if (result.ok) return result;\n result = yield _class_private_field_get(_this, _interceptorManager).runErrorInterceptors(result);\n if (!result.ok) throw new FetcherError(result);\n return result;\n })();\n }\n /**\n * Makes a `GET` to a target `endpoint` with the provided `query` params.\n */ get(endpoint, opts) {\n return this.request(_object_spread({\n endpoint,\n method: HTTP_METHODS.GET\n }, opts || {}));\n }\n /**\n * Makes a `POST` to a target `endpoint` with the provided `body`.\n */ post(endpoint, opts) {\n return this.request(_object_spread({\n endpoint,\n method: HTTP_METHODS.POST\n }, opts || {}));\n }\n /**\n * Makes a `PATCH` to a target `endpoint` with the provided `body`.\n */ patch(endpoint, opts) {\n return this.request(_object_spread({\n endpoint,\n method: HTTP_METHODS.PATCH\n }, opts || {}));\n }\n /**\n * Makes a `PUT` to a target `endpoint` with the provided `body`.\n */ put(endpoint, opts) {\n return this.request(_object_spread({\n endpoint,\n method: HTTP_METHODS.PUT\n }, opts || {}));\n }\n /**\n * Makes a `DELETE` to a target `endpoint` with the provided `body`.\n */ delete(endpoint, opts) {\n return this.request(_object_spread({\n endpoint,\n method: HTTP_METHODS.DELETE\n }, opts || {}));\n }\n constructor(config, interceptors){\n _class_private_method_init(this, _executeRequest);\n _class_private_field_init(this, _abortManager, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _interceptorManager, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _config, {\n writable: true,\n value: void 0\n });\n validateBaseUrl(config.baseUrl);\n _class_private_field_set(this, _config, _object_spread_props(_object_spread({}, DEFAULT_CONFIG, config), {\n baseUrl: config.baseUrl\n }));\n _class_private_field_set(this, _abortManager, new FetcherAbortManager());\n _class_private_field_set(this, _interceptorManager, new FetcherInterceptorManager(interceptors));\n }\n} /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ \nfunction executeRequest(id, request) {\n return _executeRequest1.apply(this, arguments);\n}\nfunction _executeRequest1() {\n _executeRequest1 = _async_to_generator(function*(id, request) {\n const config = yield _class_private_field_get(this, _interceptorManager).runRequestInterceptors(request);\n const timeoutId = setTimeout(()=>this.abort(id), _class_private_field_get(this, _config).timeout);\n const response = yield fetch(config.url, config);\n _class_private_field_get(this, _abortManager).clear(id);\n clearTimeout(timeoutId);\n return response;\n });\n return _executeRequest1.apply(this, arguments);\n}\n\n//# sourceMappingUR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I7V0FBekQ7O1NBQUE7SUFBQSxtQkFBQSxvQkFBQSxVQUFzQkksRUFBVSxFQUFFSixPQUF1QjtRQUN2RCxNQUFNbkIsU0FBUyxNQUFNLHlCQUFBLElBQUksRUFBRUcscUJBQW1CNkMsc0JBQXNCLENBQ2xFN0I7UUFFRixNQUFNOEIsWUFBWUMsV0FBVyxJQUFNLElBQUksQ0FBQ2xDLEtBQUssQ0FBQ08sS0FBSyx5QkFBQSxJQUFJLEVBQUV2QixTQUFPbUQsT0FBTztRQUV2RSxNQUFNdkIsV0FBVyxNQUFNd0IsTUFBTXBELE9BQU9xRCxHQUFHLEVBQUVyRDtRQUV6Qyx5QkFBQSxJQUFJLEVBQUVFLGVBQWFVLEtBQUssQ0FBQ1c7UUFDekIrQixhQUFhTDtRQUNiLE9BQU9yQjtJQUNUO1dBWEEifQ==","function _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nvar _originalError = new WeakMap(), _meta = new WeakMap(), _nestedErrors = new WeakMap();\n/**\n * Generic server error response.\n */ export class JsonApiError extends Error {\n /**\n * Response HTTP status.\n */ get httpStatus() {\n var _class_private_field_get_response, _class_private_field_get1;\n return (_class_private_field_get1 = _class_private_field_get(this, _originalError)) === null || _class_private_field_get1 === void 0 ? void 0 : (_class_private_field_get_response = _class_private_field_get1.response) === null || _class_private_field_get_response === void 0 ? void 0 : _class_private_field_get_response.status;\n }\n /**\n * Error meta.\n */ get meta() {\n return _class_private_field_get(this, _meta);\n }\n get requestPath() {\n var _class_private_field_get_response_request, _class_private_field_get_response, _class_private_field_get1;\n return new URL((_class_private_field_get1 = _class_private_field_get(this, _originalError)) === null || _class_private_field_get1 === void 0 ? void 0 : (_class_private_field_get_response = _class_private_field_get1.response) === null || _class_private_field_get_response === void 0 ? void 0 : (_class_private_field_get_response_request = _class_private_field_get_response.request) === null || _class_private_field_get_response_request === void 0 ? void 0 : _class_private_field_get_response_request.url).pathname;\n }\n /**\n * Errors for every invalid field.\n */ get nestedErrors() {\n return _class_private_field_get(this, _nestedErrors);\n }\n /*\n * Original error\n */ get originalError() {\n return _class_private_field_get(this, _originalError);\n }\n constructor(originalError){\n var _originalError_response_data, _originalError_response;\n super();\n _define_property(this, \"name\", 'JsonApiError');\n _define_property(this, \"message\", void 0);\n _class_private_field_init(this, _originalError, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _meta, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _nestedErrors, {\n writable: true,\n value: void 0\n });\n const errors = (originalError === null || originalError === void 0 ? void 0 : (_originalError_response = originalError.response) === null || _originalError_response === void 0 ? void 0 : (_originalError_response_data = _originalError_response.data) === null || _originalError_response_data === void 0 ? void 0 : _originalError_response_data.errors) || [];\n const unwrappedError = errors === null || errors === void 0 ? void 0 : errors[0];\n var _unwrappedError_detail;\n const detail = (_unwrappedError_detail = unwrappedError === null || unwrappedError === void 0 ? void 0 : unwrappedError.detail) !== null && _unwrappedError_detail !== void 0 ? _unwrappedError_detail : '';\n var _unwrappedError_title;\n const title = (_unwrappedError_title = unwrappedError === null || unwrappedError === void 0 ? void 0 : unwrappedError.title) !== null && _unwrappedError_title !== void 0 ? _unwrappedError_title : '';\n this.message = `${title}: ${detail}`;\n _class_private_field_set(this, _originalError, originalError);\n var _unwrappedError_meta;\n _class_private_field_set(this, _meta, (_unwrappedError_meta = unwrappedError === null || unwrappedError === void 0 ? void 0 : unwrappedError.meta) !== null && _unwrappedError_meta !== void 0 ? _unwrappedError_meta : {});\n if (errors.length > 1) {\n this.message = 'Request contains multiple errors. Check \"nestedErrors\"';\n }\n _class_private_field_set(this, _nestedErrors, errors.map((err)=>{\n var _err_title, _err_detail, _err_meta;\n return {\n title: (_err_title = err === null || err === void 0 ? void 0 : err.title) !== null && _err_title !== void 0 ? _err_title : '',\n detail: (_err_detail = err === null || err === void 0 ? void 0 : err.detail) !== null && _err_detail !== void 0 ? _err_detail : '',\n meta: (_err_meta = err === null || err === void 0 ? void 0 : err.meta) !== null && _err_meta !== void 0 ? _err_meta : {}\n };\n }));\n }\n}\nexport class BadRequestError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'BadRequestError');\n }\n}\n/**\n * 401(Unauthorized) error.\n */ export class UnauthorizedError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'UnauthorizedError');\n }\n}\n/**\n * 403(Forbidden) error.\n */ export class ForbiddenError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'ForbiddenError');\n }\n}\n/**\n * (404)The requested resource was not found.\n */ export class NotFoundError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'NotFoundError');\n }\n}\n/**\n * The request could not be completed due to a conflict with the current state\n * of the target resource.\n */ export class ConflictError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'ConflictError');\n }\n}\n/**\n * 500(Internal server) error\n */ export class InternalServerError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'InternalServerError');\n }\n}\n/**\n * Network error.\n */ export class NetworkError extends JsonApiError {\n constructor(originalError){\n super(originalError);\n _define_property(this, \"name\", 'NetworkError');\n }\n} /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ \n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9lcnJvcnMvc2VydmVyLWVycm9ycy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSB7IEZldGNoZXJFcnJvciB9IGZyb20gJ0BkaXN0cmlidXRlZGxhYi9mZXRjaGVyJ1xuXG5pbXBvcnQgdHlwZSB7XG4gIEpzb25BcGlFcnJvck1ldGFUeXBlLFxuICBKc29uQXBpUmVzcG9uc2VFcnJvcnMsXG4gIEpzb25BcGlSZXNwb25zZU5lc3RlZEVycm9ycyxcbn0gZnJvbSAnQC90eXBlcydcblxuLyoqXG4gKiBHZW5lcmljIHNlcnZlciBlcnJvciByZXNwb25zZS5cbiAqL1xuXG5leHBvcnQgY2xhc3MgSnNvbkFwaUVycm9yIGV4dGVuZHMgRXJyb3Ige1xuICBwdWJsaWMgbmFtZSA9ICdKc29uQXBpRXJyb3InXG4gIHB1YmxpYyBtZXNzYWdlOiBzdHJpbmdcbiAgcmVhZG9ubHkgI29yaWdpbmFsRXJyb3I6IEZldGNoZXJFcnJvcjxKc29uQXBpUmVzcG9uc2VFcnJvcnM+XG4gIHJlYWRvbmx5ICNtZXRhOiBKc29uQXBpRXJyb3JNZXRhVHlwZVxuICByZWFkb25seSAjbmVzdGVkRXJyb3JzOiBKc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BTWEsc0JBQXNCM0I7SUFFakNhLFlBQVlWLGFBQWtELENBQUU7UUFDOUQsS0FBSyxDQUFDQTtRQUZSLHVCQUFPVyxRQUFPO0lBR2Q7QUFDRjtBQUVBOzs7Q0FHQyxHQUNELE9BQU8sTUFBTWMsc0JBQXNCNUI7SUFFakNhLFlBQVlWLGFBQWtELENBQUU7UUFDOUQsS0FBSyxDQUFDQTtRQUZSLHVCQUFPVyxRQUFPO0lBR2Q7QUFDRjtBQUVBOztDQUVDLEdBQ0QsT0FBTyxNQUFNZSw0QkFBNEI3QjtJQUV2Q2EsWUFBWVYsYUFBa0QsQ0FBRTtRQUM5RCxLQUFLLENBQUNBO1FBRlIsdUJBQU9XLFFBQU87SUFHZDtBQUNGO0FBRUE7O0NBRUMsR0FDRCxPQUFPLE1BQU1nQixxQkFBcUI5QjtJQUVoQ2EsWUFBWVYsYUFBa0QsQ0FBRTtRQUM5RCxLQUFLLENBQUNBO1FBRlIsdUJBQU9XLFFBQU87SUFHZDtBQUNGIn0=","function _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _object_spread(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n _define_property(target, key, source[key]);\n });\n }\n return target;\n}\nimport * as serverErrors from \"./server-errors\";\nexport * from \"./server-errors\";\nexport const errors = _object_spread({}, serverErrors);\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9lcnJvcnMvaW5kZXgudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0ICogYXMgc2VydmVyRXJyb3JzIGZyb20gJy4vc2VydmVyLWVycm9ycydcbmV4cG9ydCAqIGZyb20gJy4vc2VydmVyLWVycm9ycydcbmV4cG9ydCBjb25zdCBlcnJvcnMgPSB7IC4uLnNlcnZlckVycm9ycyB9XG4iXSwibmFtZXMiOlsic2VydmVyRXJyb3JzIiwiZXJyb3JzIl0sInJhbmdlTWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OzsiLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLFlBQVlBLGtCQUFrQixrQkFBaUI7QUFDL0MsY0FBYyxrQkFBaUI7QUFDL0IsT0FBTyxNQUFNQyxTQUFTLG1CQUFLRCxjQUFjIn0=","function _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _class_private_method_get(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return fn;\n}\nfunction _class_private_method_init(obj, privateSet) {\n _check_private_redeclaration(obj, privateSet);\n privateSet.add(obj);\n}\nfunction _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _object_spread(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n _define_property(target, key, source[key]);\n });\n }\n return target;\n}\nconst RELATIONSHIP_NAMES_PROP = 'relationshipNames';\nconst jsonParse = (str)=>{\n let parsed;\n try {\n parsed = JSON.parse(str);\n } catch (e) {\n parsed = {};\n console.warn(e);\n }\n return parsed;\n};\nconst jsonStringify = (json)=>{\n let stringified;\n try {\n stringified = JSON.stringify(json);\n } catch (e) {\n stringified = '';\n console.warn(e);\n }\n return stringified;\n};\nlet JsonPropertiesMapper = class JsonPropertiesMapper {\n createModel(type) {\n return {\n type\n };\n }\n setId(model, id) {\n model.id = id;\n }\n setAttributes(model, attributes) {\n Object.keys(attributes).forEach((propName)=>{\n model[propName] = attributes[propName];\n });\n }\n setMeta(model, meta) {\n model.meta = meta;\n }\n setLinks(model, links) {\n model.links = links;\n }\n setResourceIdObjMeta(model, meta) {\n model.resourceIdObjMeta = meta;\n }\n setRelationships(model, relationships) {\n Object.keys(relationships).forEach((propName)=>{\n if (typeof relationships[propName] === 'function') {\n relationships[propName];\n } else {\n model[propName] = relationships[propName];\n }\n });\n const newNames = Object.keys(relationships);\n const currentNames = model[RELATIONSHIP_NAMES_PROP];\n if (currentNames && Object.keys(currentNames).length) {\n model[RELATIONSHIP_NAMES_PROP] = [\n _object_spread({}, currentNames),\n ...newNames\n ].filter((value, i, self)=>self.indexOf(value) === i);\n } else {\n model[RELATIONSHIP_NAMES_PROP] = newNames;\n }\n }\n};\nlet DeserializeCache = class DeserializeCache {\n getCachedModel(data, resourceIdObject) {\n const entityKey = this.createCacheKey(data, resourceIdObject);\n return this.cachedModels[entityKey] || null;\n }\n handleModel(model, data, resourceIdObject) {\n const entityKey = this.createCacheKey(data, resourceIdObject);\n const dataWithPayload = data.attributes || data.relationships;\n if (entityKey && dataWithPayload) {\n this.cachedModels[entityKey] = model;\n }\n }\n createCacheKey(data, resourceIdObject) {\n // resourceIdObject.meta sets to model in simplePropertyMappers.ts, so it should be used here to\n // cache in this case probably will be redundant\n if (!data.id || !data.type) {\n return '';\n }\n let resourcePart = resourceIdObject ? `${resourceIdObject.type}-${resourceIdObject.id}` : '';\n if (resourceIdObject === null || resourceIdObject === void 0 ? void 0 : resourceIdObject.meta) {\n resourcePart += `-${jsonStringify(resourceIdObject.meta)}`;\n }\n if (data.meta) {\n return `${data.type}-${data.id}-${jsonStringify(data.meta)}-${resourcePart}`;\n }\n return `${data.type}-${data.id}-${resourcePart}`;\n }\n constructor(){\n _define_property(this, \"cachedModels\", {});\n }\n};\nvar _pm = new WeakMap(), _dc = new WeakMap(), _body = new WeakMap(), _dataInObject = new WeakMap(), _preferNestedDataFromData = new WeakMap(), _includedInObject = new WeakMap(), _buildModelByData = new WeakSet(), _buildRelationsByData = new WeakSet(), _buildDataFromIncludedOrData = new WeakSet(), _buildDataInObject = new WeakSet(), _buildIncludedInObject = new WeakSet();\nexport class JsonDeserializer {\n setJsonParsedObject(body) {\n _class_private_field_set(this, _body, body);\n }\n build() {\n const { data } = _class_private_field_get(this, _body);\n let result;\n if (Array.isArray(data)) {\n result = [];\n for(let i = 0; i < data.length; i++){\n if (!data[i]) {\n continue;\n }\n const model = _class_private_method_get(this, _buildModelByData, buildModelByData).call(this, data[i]);\n if (model) {\n result.push(model);\n }\n }\n } else if (data) {\n result = _class_private_method_get(this, _buildModelByData, buildModelByData).call(this, data);\n }\n return result;\n }\n constructor(propertiesMapper, deserializeCache, options){\n _class_private_method_init(this, _buildModelByData);\n _class_private_method_init(this, _buildRelationsByData);\n _class_private_method_init(this, _buildDataFromIncludedOrData);\n _class_private_method_init(this, _buildDataInObject);\n _class_private_method_init(this, _buildIncludedInObject);\n _class_private_field_init(this, _pm, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _dc, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _body, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _dataInObject, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _preferNestedDataFromData, {\n writable: true,\n value: false\n });\n _class_private_field_init(this, _includedInObject, {\n writable: true,\n value: void 0\n });\n _class_private_field_set(this, _pm, propertiesMapper);\n _class_private_field_set(this, _dc, deserializeCache);\n _class_private_field_set(this, _body, {});\n _class_private_field_set(this, _dataInObject, {});\n _class_private_field_set(this, _includedInObject, undefined);\n if (!options) {\n return;\n }\n if (options.preferNestedDataFromData) {\n _class_private_field_set(this, _preferNestedDataFromData, true);\n }\n }\n}\nfunction buildModelByData(data, resourceIdObj) {\n const cachedModel = _class_private_field_get(this, _dc).getCachedModel(data, resourceIdObj);\n if (cachedModel) {\n return cachedModel;\n }\n const model = _class_private_field_get(this, _pm).createModel(data.type);\n _class_private_field_get(this, _dc).handleModel(model, data, resourceIdObj);\n // should be called before this.#pm.setRelationships(model, relationships);\n if (!model) return model;\n _class_private_field_get(this, _pm).setId(model, data.id);\n if (data.attributes) {\n _class_private_field_get(this, _pm).setAttributes(model, data.attributes);\n }\n if (data.meta && _class_private_field_get(this, _pm).setMeta) {\n _class_private_field_get(this, _pm).setMeta(model, data.meta);\n }\n if (data.links && _class_private_field_get(this, _pm).setLinks) {\n _class_private_field_get(this, _pm).setLinks(model, data.links);\n }\n if (resourceIdObj === null || resourceIdObj === void 0 ? void 0 : resourceIdObj.meta) {\n _class_private_field_get(this, _pm).setResourceIdObjMeta(model, resourceIdObj.meta);\n }\n const relationships = _class_private_method_get(this, _buildRelationsByData, buildRelationsByData).call(this, data);\n if (relationships) {\n _class_private_field_get(this, _pm).setRelationships(model, relationships);\n }\n return model;\n}\nfunction buildRelationsByData(data) {\n const readyRelations = {};\n const relationships = data.relationships;\n if (!relationships) return null;\n Object.keys(relationships).forEach((k)=>{\n const relation = relationships[k];\n const relationData = relation.data;\n if (relationData === null) readyRelations[k] = {};\n if (Array.isArray(relationData)) {\n readyRelations[k] = [];\n relationData.forEach((resourceIdObj)=>{\n if (!resourceIdObj) return;\n const dataItem = _class_private_method_get(this, _buildDataFromIncludedOrData, buildDataFromIncludedOrData).call(this, resourceIdObj.id, resourceIdObj.type);\n readyRelations[k].push(_class_private_method_get(this, _buildModelByData, buildModelByData).call(this, dataItem, resourceIdObj));\n });\n } else if (relationData) {\n const dataItem = _class_private_method_get(this, _buildDataFromIncludedOrData, buildDataFromIncludedOrData).call(this, relationData.id, relationData.type);\n readyRelations[k] = _class_private_method_get(this, _buildModelByData, buildModelByData).call(this, dataItem, relationData);\n }\n });\n if (Object.keys(readyRelations).length) {\n return readyRelations;\n }\n return null;\n}\nfunction buildDataFromIncludedOrData(id, type) {\n if (_class_private_field_get(this, _preferNestedDataFromData)) {\n const dataObject = _class_private_method_get(this, _buildDataInObject, buildDataInObject).call(this);\n const dataItemFromData = dataObject[type + id];\n if (dataItemFromData) {\n return dataItemFromData;\n }\n }\n const includedObject = _class_private_method_get(this, _buildIncludedInObject, buildIncludedInObject).call(this);\n const dataItemFromIncluded = includedObject[type + id];\n if (dataItemFromIncluded) {\n return dataItemFromIncluded;\n }\n if (!_class_private_field_get(this, _preferNestedDataFromData)) {\n const dataObject = _class_private_method_get(this, _buildDataInObject, buildDataInObject).call(this);\n const dataItemFromData = dataObject[type + id];\n if (dataItemFromData) {\n return dataItemFromData;\n }\n }\n return {\n id,\n type\n };\n}\nfunction buildDataInObject() {\n const { data } = _class_private_field_get(this, _body);\n if (_class_private_field_get(this, _dataInObject) || !data) return _class_private_field_get(this, _dataInObject);\n _class_private_field_set(this, _dataInObject, {});\n if (!Array.isArray(data)) {\n _class_private_field_get(this, _dataInObject)[data.type + data.id] = data;\n return _class_private_field_get(this, _dataInObject);\n }\n data.forEach((item)=>{\n _class_private_field_get(this, _dataInObject)[item.type + item.id] = item;\n });\n return _class_private_field_get(this, _dataInObject);\n}\nfunction buildIncludedInObject() {\n if (_class_private_field_get(this, _includedInObject)) return _class_private_field_get(this, _includedInObject);\n _class_private_field_set(this, _includedInObject, {});\n if (!_class_private_field_get(this, _body).included && !Array.isArray(_class_private_field_get(this, _body).included)) {\n return _class_private_field_get(this, _includedInObject);\n }\n _class_private_field_get(this, _body).included.forEach((item)=>{\n _class_private_field_get(this, _includedInObject)[item.type + item.id] = item;\n });\n return _class_private_field_get(this, _includedInObject);\n}\nexport const deserialize = (body, options)=>{\n if (!body) {\n throw new TypeError(\"Can't be deserialized, body is not passed\");\n }\n const deserializeCache = new DeserializeCache();\n const modelBuilder = new JsonDeserializer(new JsonPropertiesMapper(), deserializeCache, options);\n const _body = typeof body === 'string' ? jsonParse(body) : body;\n modelBuilder.setJsonParsedObject(_body);\n return modelBuilder.build();\n} /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ ;\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL2Rlc2VyaWFsaXplLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB0eXBlIHtcbiAgVEFueUtleVZhbHVlT2JqZWN0L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Q0FBTyxJQUFJLEVBQUVsQjtBQUNmO0FBR0YsT0FBTyxNQUFNb0IsY0FBYyxDQUN6QmxDLE1BQ0FVO0lBRUEsSUFBSSxDQUFDVixNQUFNO1FBQ1QsTUFBTSxJQUFJbUMsVUFBVTtJQUN0QjtJQUVBLE1BQU0xQixtQkFBbUIsSUFBSXJCO0lBQzdCLE1BQU1nRCxlQUFlLElBQUl0QyxpQkFDdkIsSUFBSXRDLHdCQUNKaUQsa0JBQ0FDO0lBR0YsTUFBTTJCLFFBQ0osT0FBT3JDLFNBQVMsV0FDWHBELFVBQVVvRCxRQUNYQTtJQUVOb0MsYUFBYXJDLG1CQUFtQixDQUFDc0M7SUFFakMsT0FBT0QsYUFBYW5DLEtBQUs7QUFDM0IsdUtBQUMifQ==","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","import isPlainObject from \"lodash/isPlainObject\";\nexport const isUndefined = (arg)=>{\n return typeof arg === 'undefined';\n};\nexport const isObject = (arg)=>{\n return isPlainObject(arg);\n};\nexport const isObjectOrArray = (arg)=>{\n return isObject(arg) || Array.isArray(arg);\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL3R5cGUtY2hlY2tzLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBpc1BsYWluT2JqZWN0IGZyb20gJ2xvZGFzaC9pc1BsYWluT2JqZWN0J1xuXG5leHBvcnQgY29uc3QgaXNVbmRlZmluZWQgPSAoYXJnOiB1bmtub3duKTogYXJnIGlzIHVuZGVmaW5lZCA9PiB7XG4gIHJldHVybiB0eXBlb2YgYXJnID09PSAndW5kZWZpbmVkJ1xufVxuXG5leHBvcnQgY29uc3QgaXNPYmplY3QgPSAoYXJnOiB1bmtub3duKTogYm9vbGVhbiA9PiB7XG4gIHJldHVybiBpc1BsYWluT2JqZWN0KGFyZylcbn1cblxuZXhwb3J0IGNvbnN0IGlzT2JqZWN0T3JBcnJheSA9IChhcmc6IHVua25vd24pOiBib29sZWFuID0+IHtcbiAgcmV0dXJuIGlzT2JqZWN0KGFyZykgfHwgQXJyYXkuaXNBcnJheShhcmcpXG59XG4iXSwibmFtZXMiOlsiaXNQbGFpbk9iamVjdCIsImlzVW5kZWZpbmVkIiwiYXJnIiwiaXNPYmplY3QiLCJpc09iamVjdE9yQXJyYXkiLCJBcnJheSIsImlzQXJyYXkiXSwicmFuZ2VNYXBwaW5ncyI6Ijs7Ozs7Ozs7OyIsIm1hcHBpbmdzIjoiQUFBQSxPQUFPQSxtQkFBbUIsdUJBQXNCO0FBRWhELE9BQU8sTUFBTUMsY0FBYyxDQUFDQztJQUMxQixPQUFPLE9BQU9BLFFBQVE7QUFDeEIsRUFBQztBQUVELE9BQU8sTUFBTUMsV0FBVyxDQUFDRDtJQUN2QixPQUFPRixjQUFjRTtBQUN2QixFQUFDO0FBRUQsT0FBTyxNQUFNRSxrQkFBa0IsQ0FBQ0Y7SUFDOUIsT0FBT0MsU0FBU0QsUUFBUUcsTUFBTUMsT0FBTyxDQUFDSjtBQUN4QyxFQUFDIn0=","import { isObjectOrArray } from \"./type-checks\";\nexport function isDeeperThanOneNesting(object = {}) {\n return Object.values(object).filter((value)=>isObjectOrArray(value)).reduce((acc, cur)=>acc.concat(Object.values(cur)), []).some((value)=>isObjectOrArray(value));\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzL2lzLWRlZXBlci10aGFuLW9uZS1uZXN0aW5nLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IGlzT2JqZWN0T3JBcnJheSB9IGZyb20gJy4vdHlwZS1jaGVja3MnXG5cbmV4cG9ydCBmdW5jdGlvbiBpc0RlZXBlclRoYW5PbmVOZXN0aW5nPFQgZXh0ZW5kcyBvYmplY3Q+KFxuICBvYmplY3QgPSB7fSBhcyBULFxuKTogYm9vbGVhbiB7XG4gIHJldHVybiBPYmplY3QudmFsdWVzKG9iamVjdClcbiAgICAuZmlsdGVyKHZhbHVlID0+IGlzT2JqZWN0T3JBcnJheSh2YWx1ZSkpXG4gICAgLnJlZHVjZSgoYWNjOiBUW10sIGN1cjogVCkgPT4gYWNjLmNvbmNhdChPYmplY3QudmFsdWVzKGN1cikpLCBbXSlcbiAgICAuc29tZSgodmFsdWU6IFQpID0+IGlzT2JqZWN0T3JBcnJheSh2YWx1ZSkpXG59XG4iXSwibmFtZXMiOlsiaXNPYmplY3RPckFycmF5IiwiaXNEZWVwZXJUaGFuT25lTmVzdGluZyIsIm9iamVjdCIsIk9iamVjdCIsInZhbHVlcyIsImZpbHRlciIsInZhbHVlIiwicmVkdWNlIiwiYWNjIiwiY3VyIiwiY29uY2F0Iiwic29tZSJdLCJyYW5nZU1hcHBpbmdzIjoiOzs7IiwibWFwcGluZ3MiOiJBQUFBLFNBQVNBLGVBQWUsUUFBUSxnQkFBZTtBQUUvQyxPQUFPLFNBQVNDLHVCQUNkQyxTQUFTLENBQUMsQ0FBTTtJQUVoQixPQUFPQyxPQUFPQyxNQUFNLENBQUNGLFFBQ2xCRyxNQUFNLENBQUNDLENBQUFBLFFBQVNOLGdCQUFnQk0sUUFDaENDLE1BQU0sQ0FBQyxDQUFDQyxLQUFVQyxNQUFXRCxJQUFJRSxNQUFNLENBQUNQLE9BQU9DLE1BQU0sQ0FBQ0ssT0FBTyxFQUFFLEVBQy9ERSxJQUFJLENBQUMsQ0FBQ0wsUUFBYU4sZ0JBQWdCTTtBQUN4QyJ9","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nmodule.exports = arrayEach;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n","var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","var copyObject = require('./_copyObject'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nmodule.exports = baseAssign;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nmodule.exports = baseAssignIn;\n","var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nmodule.exports = cloneBuffer;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nmodule.exports = copyArray;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n","var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nmodule.exports = getSymbols;\n","var copyObject = require('./_copyObject'),\n getSymbols = require('./_getSymbols');\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nmodule.exports = copySymbols;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","var arrayPush = require('./_arrayPush'),\n getPrototype = require('./_getPrototype'),\n getSymbols = require('./_getSymbols'),\n stubArray = require('./stubArray');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nmodule.exports = getSymbolsIn;\n","var copyObject = require('./_copyObject'),\n getSymbolsIn = require('./_getSymbolsIn');\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nmodule.exports = copySymbolsIn;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbolsIn = require('./_getSymbolsIn'),\n keysIn = require('./keysIn');\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nmodule.exports = getAllKeysIn;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nmodule.exports = initCloneArray;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nmodule.exports = cloneDataView;\n","/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nmodule.exports = cloneRegExp;\n","var Symbol = require('./_Symbol');\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nmodule.exports = cloneSymbol;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer'),\n cloneDataView = require('./_cloneDataView'),\n cloneRegExp = require('./_cloneRegExp'),\n cloneSymbol = require('./_cloneSymbol'),\n cloneTypedArray = require('./_cloneTypedArray');\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nmodule.exports = initCloneByTag;\n","var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nmodule.exports = baseCreate;\n","var baseCreate = require('./_baseCreate'),\n getPrototype = require('./_getPrototype'),\n isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nmodule.exports = initCloneObject;\n","var getTag = require('./_getTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nmodule.exports = baseIsMap;\n","var baseIsMap = require('./_baseIsMap'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nmodule.exports = isMap;\n","var getTag = require('./_getTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nmodule.exports = baseIsSet;\n","var baseIsSet = require('./_baseIsSet'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nmodule.exports = isSet;\n","var Stack = require('./_Stack'),\n arrayEach = require('./_arrayEach'),\n assignValue = require('./_assignValue'),\n baseAssign = require('./_baseAssign'),\n baseAssignIn = require('./_baseAssignIn'),\n cloneBuffer = require('./_cloneBuffer'),\n copyArray = require('./_copyArray'),\n copySymbols = require('./_copySymbols'),\n copySymbolsIn = require('./_copySymbolsIn'),\n getAllKeys = require('./_getAllKeys'),\n getAllKeysIn = require('./_getAllKeysIn'),\n getTag = require('./_getTag'),\n initCloneArray = require('./_initCloneArray'),\n initCloneByTag = require('./_initCloneByTag'),\n initCloneObject = require('./_initCloneObject'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isMap = require('./isMap'),\n isObject = require('./isObject'),\n isSet = require('./isSet'),\n keys = require('./keys'),\n keysIn = require('./keysIn');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nmodule.exports = baseClone;\n","var baseClone = require('./_baseClone');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nmodule.exports = cloneDeep;\n","function _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _object_spread(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n _define_property(target, key, source[key]);\n });\n }\n return target;\n}\nimport cloneDeep from \"lodash/cloneDeep\";\nimport { isDeeperThanOneNesting, isObject, isObjectOrArray } from \"../helpers\";\n/**\n * flatJsonApiQuery is needed to provide easier interface for complex query\n * params.\n */ export const flatJsonApiQuery = (q)=>{\n if (!q) return;\n const query = cloneDeep(q);\n if (isDeeperThanOneNesting(query)) {\n throw new TypeError('Nested arrays or objects are not allowed for using in query params');\n }\n return _object_spread({}, flattenArraysOnly(query), flattenObjectsOnly(query), flattenPrimitivesOnly(query));\n};\nfunction flattenArraysOnly(object) {\n return Object.entries(object).filter(([, value])=>Array.isArray(value)).map(([key, value])=>[\n key,\n value.join(',')\n ]).reduce((res, [key, val])=>_object_spread({}, res, {\n [key]: val\n }), {});\n}\nfunction flattenObjectsOnly(object) {\n return Object.entries(object).filter(([, value])=>isObject(value)).map(([prefix, nestedObj])=>Object.entries(nestedObj).map(([key, value])=>[\n `${prefix}[${key}]`,\n value\n ])).reduce((acc, row)=>acc.concat(row), []).reduce((res, [key, val])=>_object_spread({}, res, {\n [key]: val\n }), {});\n}\nfunction flattenPrimitivesOnly(object) {\n return Object.entries(object).filter(([, value])=>!isObjectOrArray(value)).reduce((res, [key, val])=>_object_spread({}, res, {\n [key]: val\n }), {});\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9taWRkbGV3YXJlcy9mbGF0LWpzb24tYXBpLXF1ZXJ5LnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBjbG9uZURlZXAgZnJvbSAnbG9kYXNoL2Nsb25lRGVlcCdcblxuaW1wb3J0IHsgaXNEZWVwZXJUaGFuT25lTmVzdGluZywgaXNPYmplY3QsIGlzT2JqZWN0T3JBcnJheSB9IGZyb20gJ0AvaGVscGVycydcbmltcG9ydCB0eXBlIHsgSnNvbkFwaUNsaWVudFJlcXVlc3RRdWVyeSB9I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BSyxDQUFDSCxLQUFLSSxJQUFJLEdBQU0sbUJBQUtELEtBQVE7WUFBRSxDQUFDSCxJQUFJLEVBQUVJO1FBQUksSUFBTSxDQUFDO0FBQ25FIn0=","import { HTTP_STATUS_CODES } from \"@distributedlab/fetcher\";\nimport { errors } from \"../errors\";\n/*\n * Parses server error and returns corresponding error instance.\n * Needed to handle on client side different behavior based on error type\n */ export const parseJsonApiError = (error)=>{\n var _error_response;\n const status = error === null || error === void 0 ? void 0 : (_error_response = error.response) === null || _error_response === void 0 ? void 0 : _error_response.status;\n switch(status){\n case HTTP_STATUS_CODES.BAD_REQUEST:\n return new errors.BadRequestError(error);\n case HTTP_STATUS_CODES.UNAUTHORIZED:\n return new errors.UnauthorizedError(error);\n case HTTP_STATUS_CODES.FORBIDDEN:\n return new errors.ForbiddenError(error);\n case HTTP_STATUS_CODES.NOT_FOUND:\n return new errors.NotFoundError(error);\n case HTTP_STATUS_CODES.CONFLICT:\n return new errors.ConflictError(error);\n case HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR:\n return new errors.InternalServerError(error);\n default:\n return new errors.NetworkError(error);\n }\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9taWRkbGV3YXJlcy9wYXJzZS1qc29uLWFwaS1lcnJvci50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBGZXRjaGVyRXJyb3IsIEhUVFBfU1RBVFVTX0NPREVTIH0gZnJvbSAnQGRpc3RyaWJ1dGVkbGFiL2ZldGNoZXInXG5cbmltcG9ydCB0eXBlIHsgSnNvbkFwaUVycm9yIH0gZnJvbSAnQC9lcnJvcnMnXG5pbXBvcnQgeyBlcnJvcnMgfSBmcm9tICdAL2Vycm9ycydcbmltcG9ydCB0eXBlIHsgSnNvbkFwaVJlc3BvbnNlRXJyb3JzIH0gZnJvbSAnQC90eXBlcydcblxuLypcbiAqIFBhcnNlcyBzZX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JBQWtCVSxTQUFTO1lBQzlCLE9BQU8sSUFBSVQsT0FBT1UsY0FBYyxDQUFDUjtRQUNuQyxLQUFLSCxrQkFBa0JZLFNBQVM7WUFDOUIsT0FBTyxJQUFJWCxPQUFPWSxhQUFhLENBQUNWO1FBQ2xDLEtBQUtILGtCQUFrQmMsUUFBUTtZQUM3QixPQUFPLElBQUliLE9BQU9jLGFBQWEsQ0FBQ1o7UUFDbEMsS0FBS0gsa0JBQWtCZ0IscUJBQXFCO1lBQzFDLE9BQU8sSUFBSWYsT0FBT2dCLG1CQUFtQixDQUFDZDtRQUN4QztZQUNFLE9BQU8sSUFBSUYsT0FBT2lCLFlBQVksQ0FBQ2Y7SUFDbkM7QUFDRixFQUFDIn0=","var baseKeys = require('./_baseKeys'),\n getTag = require('./_getTag'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLike = require('./isArrayLike'),\n isBuffer = require('./isBuffer'),\n isPrototype = require('./_isPrototype'),\n isTypedArray = require('./isTypedArray');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n setTag = '[object Set]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\nfunction isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n}\n\nmodule.exports = isEmpty;\n","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nfunction _async_to_generator(fn) {\n return function() {\n var self = this, args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\nfunction _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _class_private_method_get(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return fn;\n}\nfunction _class_private_method_init(obj, privateSet) {\n _check_private_redeclaration(obj, privateSet);\n privateSet.add(obj);\n}\nimport isEmpty from \"lodash/isEmpty\";\nimport { deserialize } from \"./helpers\";\nconst PAGE_LIMIT_KEY = 'page[limit]';\nvar _raw = new WeakMap(), _rawData = new WeakMap(), _links = new WeakMap(), _isNeedRaw = new WeakMap(), _meta = new WeakMap(), _data = new WeakMap(), _apiClient = new WeakMap(), /**\n * Parses and unwraps response data.\n */ _parseResponse = new WeakSet();\n/**\n * JSON API response wrapper.\n */ export class JsonApiResponse {\n get meta() {\n return _class_private_field_get(this, _meta);\n }\n /**\n * Get raw response.\n */ get rawResponse() {\n return _class_private_field_get(this, _raw);\n }\n /**\n * Get request page limit.\n */ get pageLimit() {\n const requestConfig = _class_private_field_get(this, _raw).request;\n const decodedUrl = decodeURIComponent(requestConfig.url || '');\n const limit = new URL(decodedUrl).searchParams.get(PAGE_LIMIT_KEY);\n return Number(limit);\n }\n /**\n * Get raw response data.\n */ get rawData() {\n return _class_private_field_get(this, _rawData) || {};\n }\n /**\n * Get response data.\n */ get data() {\n return _class_private_field_get(this, _data);\n }\n /**\n * Get response HTTP status.\n */ get status() {\n return _class_private_field_get(this, _raw).status;\n }\n /**\n * Get response headers.\n */ get headers() {\n return _class_private_field_get(this, _raw).headers;\n }\n /**\n * Get response links.\n */ get links() {\n return _class_private_field_get(this, _links);\n }\n /**\n * Is response links exist.\n */ get isLinksExist() {\n return Boolean(_class_private_field_get(this, _links)) && !isEmpty(_class_private_field_get(this, _links));\n }\n createLink(link) {\n var _class_private_field_get1;\n const baseUrl = (_class_private_field_get1 = _class_private_field_get(this, _apiClient)) === null || _class_private_field_get1 === void 0 ? void 0 : _class_private_field_get1.baseUrl;\n if (!baseUrl) return link;\n const baseUrlPath = new URL(baseUrl).pathname;\n // Do not remove leading slash if baseUrl is root\n return baseUrlPath === '/' ? link : link.replace(new RegExp(`^${baseUrlPath}`), '');\n }\n fetchPage(page) {\n var _this = this;\n return _async_to_generator(function*() {\n if (!_this.isLinksExist) {\n throw new TypeError('There are no links in response');\n }\n const link = _this.createLink(_this.links[page]);\n const jsonApiClientRequestOpts = {\n endpoint: link,\n method: _class_private_field_get(_this, _raw).request.method,\n headers: _class_private_field_get(_this, _raw).request.headers,\n isNeedRaw: _class_private_field_get(_this, _isNeedRaw)\n };\n return _class_private_field_get(_this, _apiClient).request(jsonApiClientRequestOpts);\n })();\n }\n constructor(opts){\n _class_private_method_init(this, _parseResponse);\n _class_private_field_init(this, _raw, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _rawData, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _links, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _isNeedRaw, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _meta, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _data, {\n writable: true,\n value: void 0\n });\n _class_private_field_init(this, _apiClient, {\n writable: true,\n value: void 0\n });\n const response = opts.raw;\n const data = response.data;\n _class_private_field_set(this, _raw, response);\n _class_private_field_set(this, _data, {});\n _class_private_field_set(this, _rawData, data || {});\n var _data_links;\n _class_private_field_set(this, _links, (_data_links = data === null || data === void 0 ? void 0 : data.links) !== null && _data_links !== void 0 ? _data_links : {});\n _class_private_field_set(this, _apiClient, opts.apiClient);\n _class_private_field_set(this, _isNeedRaw, opts.isNeedRaw);\n _class_private_method_get(this, _parseResponse, parseResponse).call(this, opts.raw, opts.isNeedRaw);\n _class_private_field_set(this, _meta, (data === null || data === void 0 ? void 0 : data.meta) || {});\n }\n} /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ /*#__PURE__*/ \nfunction parseResponse(raw, isNeedRaw) {\n if (!raw.data) return;\n _class_private_field_set(this, _data, isNeedRaw ? raw.data : deserialize(raw.data));\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9yZXNwb25zZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSB7IEhUVFBfTUVUSE9EUywgSFRUUF9TVEFUVVNfQ09ERVMgfSBmcm9tICdAZGlzdHJpYnV0ZWRsYWIvZmV0Y2hlcidcbmltcG9ydCBpc0VtcHR5IGZyb20gJ2xvZGFzaC9pc0VtcHR5J1xuXG5pbXBvcnQgdHlwZSB7IEpzb25BcGlDbGllbnQgfSBmcm9tICdAL2pzb24tYXBpJ1xuXG5pbXBvcnQgeyBkZXNlcmlhbGl6ZSB9IGZyb20gJy4vaGVscGVycydcbmltcG9ydCB0eXBlIHtcbiAgRW5kcG9pbnQsXG4gIEpzb25BcGlDbGllbnRSZXF1ZXN0Q29uZmlnSGVhZGVycyxcbiAgSnNvbkFwaURlZmF1bHRNZXRhLFxuICBKc29uQXBpTGlua0ZpZWxkcyxcbiAgSnNvbkFwaVJlc3BvbnNlTGlua3MsXG4gIEpzb25BcGlSZXNwb25zZVJhdyxcbiAgSnNvbkFwaVJlc3BvbnNlUmF3RGF0YSxcbn0gZnJvbSAnLi90eXBlcydcblxuY29uc3QgUEFHRV9MSU1JVF9LRVkgPSAncGFnZVtsaW1pdF0nXG5cbi8qKlxuICogSlNPTiBBUEkgcmVzcG9uc2Ugd3JhcHBlci5cbiAqL1xuZXhwb3J0IGNsYXNzIEpzb25BcGlSZXNwb25zZTxULCBVID0gSnNvbkFwaURlZmF1bHRNZXRhPiB7XG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PdUIsU0FBU3ZCLElBQUk7dUNBQ3BCYixNQUFNb0M7dUNBQ052QixPQUFPLENBQUM7dUNBQ1JELFVBQVVDLFFBQVEsQ0FBQztZQUNYQTt1Q0FBUkcsUUFBUUgsQ0FBQUEsY0FBQUEsaUJBQUFBLDJCQUFBQSxLQUFNRyxLQUFLLGNBQVhILHlCQUFBQSxjQUFlLENBQUM7dUNBQ3hCUyxZQUFZYSxLQUFLYixTQUFTO3VDQUMxQlcsWUFBWUUsS0FBS0YsU0FBUztRQUVoQywwQkFBQSxJQUFJLEVBQUVJLGdCQUFBQSxvQkFBTixJQUFJLEVBQWdCRixLQUFLbkMsR0FBRyxFQUFFbUMsS0FBS0YsU0FBUzt1Q0FDdENuQyxPQUFRZSxDQUFBQSxpQkFBQUEsMkJBQUFBLEtBQU1mLElBQUksS0FBSSxDQUFDO0lBQy9CO0FBdUdGO0FBbkNFLFNBQUEsY0FBZUUsR0FBdUIsRUFBRWlDLFNBQWtCO0lBQ3hELElBQUksQ0FBQ2pDLElBQUlhLElBQUksRUFBRTttQ0FFVEEsT0FBT29CLFlBQWFqQyxJQUFJYSxJQUFJLEdBQVVsQixZQUFZSyxJQUFJYSxJQUFJO0FBQ2xFIn0=","import { JsonApiResponse } from \"../response\";\nexport const parseJsonApiResponse = (opts)=>{\n return new JsonApiResponse(opts);\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9taWRkbGV3YXJlcy9wYXJzZS1qc29uLWFwaS1yZXNwb25zZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSB7IEpzb25BcGlDbGllbnQgfSBmcm9tICdAL2pzb24tYXBpJ1xuaW1wb3J0IHsgSnNvbkFwaVJlc3BvbnNlIH0gZnJvbSAnQC9yZXNwb25zZSdcbmltcG9ydCB0eXBlIHsgSnNvbkFwaURlZmF1bHRNZXRhLCBKc29uQXBpUmVzcG9uc2VSYXcgfSBmcm9tICdAL3R5cGVzJ1xuXG5leHBvcnQgY29uc3QgcGFyc2VKc29uQXBpUmVzcG9uc2UgPSA8VCwgVSA9IEpzb25BcGlEZWZhdWx0TWV0YT4ob3B0czoge1xuICByYXc6IEpzb25BcGlSZXNwb25zZVJhd1xuICBhcGlDbGllbnQ6IEpzb25BcGlDbGllbnRcbiAgaXNOZWVkUmF3OiBib29sZWFuXG59KSA9PiB7XG4gIHJldHVybiBuZXcgSnNvbkFwaVJlc3BvbnNlPFQsIFU+KG9wdHMpXG59XG4iXSwibmFtZXMiOlsiSnNvbkFwaVJlc3BvbnNlIiwicGFyc2VKc29uQXBpUmVzcG9uc2UiLCJvcHRzIl0sInJhbmdlTWFwcGluZ3MiOiI7OzsiLCJtYXBwaW5ncyI6IkFBQ0EsU0FBU0EsZUFBZSxRQUFRLGNBQVk7QUFHNUMsT0FBTyxNQUFNQyx1QkFBdUIsQ0FBNEJDO0lBSzlELE9BQU8sSUFBSUYsZ0JBQXNCRTtBQUNuQyxFQUFDIn0=","import cloneDeep from \"lodash/cloneDeep\";\nconst MIME_TYPE_JSON_API = 'application/vnd.api+json';\nconst HEADER_CONTENT_TYPE = 'Content-Type';\nconst HEADER_ACCEPT = 'Accept';\nexport const setJsonApiHeaders = (h)=>{\n const headers = cloneDeep(h);\n headers[HEADER_CONTENT_TYPE] = MIME_TYPE_JSON_API;\n headers[HEADER_ACCEPT] = MIME_TYPE_JSON_API;\n return headers;\n};\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9taWRkbGV3YXJlcy9zZXQtanNvbi1hcGktaGVhZGVycy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgY2xvbmVEZWVwIGZyb20gJ2xvZGFzaC9jbG9uZURlZXAnXG5cbmltcG9ydCB0eXBlIHsgSnNvbkFwaUNsaWVudFJlcXVlc3RDb25maWdIZWFkZXJzIH0gZnJ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yxHQUFHRjtJQUV6QixPQUFPSztBQUNULEVBQUMifQ==","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nfunction _async_to_generator(fn) {\n return function() {\n var self = this, args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\nfunction _check_private_redeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}\nfunction _class_apply_descriptor_get(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n}\nfunction _class_apply_descriptor_set(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n}\nfunction _class_extract_field_descriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n return privateMap.get(receiver);\n}\nfunction _class_private_field_get(receiver, privateMap) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"get\");\n return _class_apply_descriptor_get(receiver, descriptor);\n}\nfunction _class_private_field_init(obj, privateMap, value) {\n _check_private_redeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}\nfunction _class_private_field_set(receiver, privateMap, value) {\n var descriptor = _class_extract_field_descriptor(receiver, privateMap, \"set\");\n _class_apply_descriptor_set(receiver, descriptor, value);\n return value;\n}\nfunction _define_property(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _object_spread(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n _define_property(target, key, source[key]);\n });\n }\n return target;\n}\nimport { Fetcher, FetcherError, HTTP_METHODS } from \"@distributedlab/fetcher\";\nimport { flatJsonApiQuery, parseJsonApiError, parseJsonApiResponse, setJsonApiHeaders } from \"./middlewares\";\nvar _fetcher = new WeakMap();\n/**\n * Represents JsonApiClient that performs requests to backend\n */ export class JsonApiClient {\n /**\n * Clones current JsonApiClient instance\n */ clone() {\n return new JsonApiClient(_class_private_field_get(this, _fetcher).config, _class_private_field_get(this, _fetcher).interceptorManager.interceptors);\n }\n /**\n * Sets Fetcher instance to the client instance.\n */ get fetcher() {\n return _class_private_field_get(this, _fetcher);\n }\n /**\n * Sets Fetcher instance to the client instance.\n */ useFetcher(fetcher) {\n _class_private_field_set(this, _fetcher, fetcher);\n return this;\n }\n /**\n * Base URL will be prepended to `url` unless `url` is absolute.\n * It can be convenient to set `baseUrl` for an instance of fetcher to pass\n * relative URLs to methods of that instance.\n */ get baseUrl() {\n return _class_private_field_get(this, _fetcher).baseUrl;\n }\n /**\n * Assigns new base URL to the current instance.\n */ useBaseUrl(baseUrl) {\n _class_private_field_get(this, _fetcher).useBaseUrl(baseUrl);\n return this;\n }\n /**\n * Creates new instance JsonApiClient instance with given base URL.\n */ withBaseUrl(baseUrl) {\n return this.clone().useBaseUrl(baseUrl);\n }\n /**\n * Sets new interceptor to the current Fetcher instance.\n */ addInterceptor(interceptor) {\n _class_private_field_get(this, _fetcher).addInterceptor(interceptor);\n }\n /**\n * Removes the existing interceptor from the Fetcher instance.\n */ removeInterceptor(interceptor) {\n _class_private_field_get(this, _fetcher).removeInterceptor(interceptor);\n }\n /**\n * Clears all existing interceptors from the Fetcher instance.\n */ clearInterceptors() {\n _class_private_field_get(this, _fetcher).clearInterceptors();\n }\n /**\n * Generates new request id in the UUID format.\n */ createRequestId() {\n return _class_private_field_get(this, _fetcher).createRequestId();\n }\n /**\n * Interrupts the request by given `requestId`, if request is not found returns `false`.\n */ abort(requestId) {\n return _class_private_field_get(this, _fetcher).abort(requestId);\n }\n /**\n * Performs a http request\n */ request(opts) {\n var _this = this;\n return _async_to_generator(function*() {\n let raw;\n var _opts_headers;\n const config = {\n body: opts.body,\n method: opts.method,\n query: flatJsonApiQuery(opts.query),\n headers: setJsonApiHeaders((_opts_headers = opts === null || opts === void 0 ? void 0 : opts.headers) !== null && _opts_headers !== void 0 ? _opts_headers : {}),\n endpoint: opts.endpoint\n };\n try {\n raw = yield _class_private_field_get(_this, _fetcher).request(config);\n } catch (e) {\n if (e instanceof FetcherError) {\n throw parseJsonApiError(e);\n }\n throw e;\n }\n return parseJsonApiResponse({\n raw,\n isNeedRaw: Boolean(opts === null || opts === void 0 ? void 0 : opts.isNeedRaw),\n apiClient: _this\n });\n })();\n }\n /**\n * Makes a `GET` to a target `endpoint` with the provided `query` params.\n * Parses the response in JsonApi format.\n */ get(endpoint, opts) {\n return this.request(_object_spread({\n method: HTTP_METHODS.GET,\n endpoint\n }, opts || {}));\n }\n /**\n * Makes a `POST` to a target `endpoint` with the provided `data` as body.\n * Parses the response in JsonApi format.\n */ post(endpoint, opts) {\n return this.request(_object_spread({\n method: HTTP_METHODS.POST,\n endpoint\n }, opts || {}));\n }\n /**\n * Makes a `PATCH` to a target `endpoint` with the provided `data` as body.\n * Signing can be enabled with `needSign` argument. Parses the response in\n * JsonApi format.\n */ patch(endpoint, opts) {\n return this.request(_object_spread({\n method: HTTP_METHODS.PATCH,\n endpoint\n }, opts || {}));\n }\n /**\n * Makes a `PUT` to a target `endpoint` with the provided `data` as body.\n * Parses the response in JsonApi format.\n */ put(endpoint, opts) {\n return this.request(_object_spread({\n method: HTTP_METHODS.PUT,\n endpoint\n }, opts || {}));\n }\n /**\n * Makes a `DELETE` to a target `endpoint` with the provided `data` as body.\n * Parses the response in JsonApi format.\n */ delete(endpoint, opts) {\n return this.request(_object_spread({\n method: HTTP_METHODS.DELETE,\n endpoint\n }, opts || {}));\n }\n constructor(config, interceptors){\n _class_private_field_init(this, _fetcher, {\n writable: true,\n value: void 0\n });\n _class_private_field_set(this, _fetcher, new Fetcher(config, interceptors));\n }\n} /*#__PURE__*/ \n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9qc29uLWFwaS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSB7XG4gIEZldGNoZXJJbnRlcmNlcHRvcixcbiAgRmV0Y2hlclJlcXVlc3RRdWVyeSxcbn0gZnJvbSAnQGRpc3RyaWJ1dGVkbGFiL2ZldGNoZXInXG5pbXBvcnQgeyBGZXRjaGVyLCBGZXRjaGVyRXJyb3IsIEhUVFBfTUVUSE9EUyB9IGZyb20gJ0BkaXN0cmlidXRlZGxhYi9mZXRjaGVyJ1xuXG5pbXBvcnQgdHlwZSB7IEpzb25BcGlSZXNwb25zZSB9IGZyb20gJ0AvcmVzcG9uc2UnXG5cbmltcG9ydCB7XG4gIGZsYXRKc29uQXBpUXVlcnksXG4gIHBhcnNlSnNvbkFwaUVycm9yLFxuICBwYXJzZUpzb25BcGlSZXNwb25zZSxcbiAgc2V0SnNvbkFwaUhlYWRlcnMsXG59IGZyb20gJy4vbWlkZGxld2FyZXMnXG5pbXBvcnQgdHlwZSB7XG4gIEVuZHBvaW50LFxuICBKc29uQXBpQ2xpZW50Q29uZmlnLFxuICBKc29uQXBpQ2xpZW50UmVxdWVzdENvbmZpZyxcbiAgSnNvbkFwaUNsaWVudFJlcXVlc3RPcHR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} from '@config'\nimport { Fetcher } from '@distributedlab/fetcher'\nimport { JsonApiClient } from '@distributedlab/jac'\n\nexport let api: JsonApiClient\n\nexport let issuerApi: Fetcher\n\nexport const initApi = () => {\n api = new JsonApiClient({\n baseUrl: config.API_URL,\n })\n issuerApi = new Fetcher({\n baseUrl: config.ISSUER_API_URL,\n })\n}\n","import { createContext } from 'react';\n\n/**\n * @public\n */\nconst MotionConfigContext = createContext({\n transformPagePoint: (p) => p,\n isStatic: false,\n reducedMotion: \"never\",\n});\n\nexport { MotionConfigContext };\n","import { createContext } from 'react';\n\nconst MotionContext = createContext({});\n\nexport { MotionContext };\n","import { createContext } from 'react';\n\n/**\n * @public\n */\nconst PresenceContext = createContext(null);\n\nexport { PresenceContext };\n","const isBrowser = typeof document !== \"undefined\";\n\nexport { isBrowser };\n","import { useLayoutEffect, useEffect } from 'react';\nimport { isBrowser } from './is-browser.mjs';\n\nconst useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect;\n\nexport { useIsomorphicLayoutEffect };\n","import { createContext } from 'react';\n\nconst LazyContext = createContext({ strict: false });\n\nexport { LazyContext };\n","/**\n * Convert camelCase to dash-case properties.\n */\nconst camelToDash = (str) => str.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase();\n\nexport { camelToDash };\n","import { camelToDash } from '../../render/dom/utils/camel-to-dash.mjs';\n\nconst optimizedAppearDataId = \"framerAppearId\";\nconst optimizedAppearDataAttribute = \"data-\" + camelToDash(optimizedAppearDataId);\n\nexport { optimizedAppearDataAttribute, optimizedAppearDataId };\n","import { useContext, useRef, useInsertionEffect, useEffect } from 'react';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\nimport { MotionContext } from '../../context/MotionContext/index.mjs';\nimport { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';\nimport { LazyContext } from '../../context/LazyContext.mjs';\nimport { MotionConfigContext } from '../../context/MotionConfigContext.mjs';\nimport { optimizedAppearDataAttribute } from '../../animation/optimized-appear/data-id.mjs';\n\nfunction useVisualElement(Component, visualState, props, createVisualElement) {\n const { visualElement: parent } = useContext(MotionContext);\n const lazyContext = useContext(LazyContext);\n const presenceContext = useContext(PresenceContext);\n const reducedMotionConfig = useContext(MotionConfigContext).reducedMotion;\n const visualElementRef = useRef();\n /**\n * If we haven't preloaded a renderer, check to see if we have one lazy-loaded\n */\n createVisualElement = createVisualElement || lazyContext.renderer;\n if (!visualElementRef.current && createVisualElement) {\n visualElementRef.current = createVisualElement(Component, {\n visualState,\n parent,\n props,\n presenceContext,\n blockInitialAnimation: presenceContext\n ? presenceContext.initial === false\n : false,\n reducedMotionConfig,\n });\n }\n const visualElement = visualElementRef.current;\n useInsertionEffect(() => {\n visualElement && visualElement.update(props, presenceContext);\n });\n /**\n * Cache this value as we want to know whether HandoffAppearAnimations\n * was present on initial render - it will be deleted after this.\n */\n const wantsHandoff = useRef(Boolean(props[optimizedAppearDataAttribute] && !window.HandoffComplete));\n useIsomorphicLayoutEffect(() => {\n if (!visualElement)\n return;\n visualElement.render();\n /**\n * Ideally this function would always run in a useEffect.\n *\n * However, if we have optimised appear animations to handoff from,\n * it needs to happen synchronously to ensure there's no flash of\n * incorrect styles in the event of a hydration error.\n *\n * So if we detect a situtation where optimised appear animations\n * are running, we use useLayoutEffect to trigger animations.\n */\n if (wantsHandoff.current && visualElement.animationState) {\n visualElement.animationState.animateChanges();\n }\n });\n useEffect(() => {\n if (!visualElement)\n return;\n visualElement.updateFeatures();\n if (!wantsHandoff.current && visualElement.animationState) {\n visualElement.animationState.animateChanges();\n }\n if (wantsHandoff.current) {\n wantsHandoff.current = false;\n // This ensures all future calls to animateChanges() will run in useEffect\n window.HandoffComplete = true;\n }\n });\n return visualElement;\n}\n\nexport { useVisualElement };\n","function isRefObject(ref) {\n return (ref &&\n typeof ref === \"object\" &&\n Object.prototype.hasOwnProperty.call(ref, \"current\"));\n}\n\nexport { isRefObject };\n","import { useCallback } from 'react';\nimport { isRefObject } from '../../utils/is-ref-object.mjs';\n\n/**\n * Creates a ref function that, when called, hydrates the provided\n * external ref and VisualElement.\n */\nfunction useMotionRef(visualState, visualElement, externalRef) {\n return useCallback((instance) => {\n instance && visualState.mount && visualState.mount(instance);\n if (visualElement) {\n instance\n ? visualElement.mount(instance)\n : visualElement.unmount();\n }\n if (externalRef) {\n if (typeof externalRef === \"function\") {\n externalRef(instance);\n }\n else if (isRefObject(externalRef)) {\n externalRef.current = instance;\n }\n }\n }, \n /**\n * Only pass a new ref callback to React if we've received a visual element\n * factory. Otherwise we'll be mounting/remounting every time externalRef\n * or other dependencies change.\n */\n [visualElement]);\n}\n\nexport { useMotionRef };\n","/**\n * Decides if the supplied variable is variant label\n */\nfunction isVariantLabel(v) {\n return typeof v === \"string\" || Array.isArray(v);\n}\n\nexport { isVariantLabel };\n","function isAnimationControls(v) {\n return (v !== null &&\n typeof v === \"object\" &&\n typeof v.start === \"function\");\n}\n\nexport { isAnimationControls };\n","const variantPriorityOrder = [\n \"animate\",\n \"whileInView\",\n \"whileFocus\",\n \"whileHover\",\n \"whileTap\",\n \"whileDrag\",\n \"exit\",\n];\nconst variantProps = [\"initial\", ...variantPriorityOrder];\n\nexport { variantPriorityOrder, variantProps };\n","import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';\nimport { isVariantLabel } from './is-variant-label.mjs';\nimport { variantProps } from './variant-props.mjs';\n\nfunction isControllingVariants(props) {\n return (isAnimationControls(props.animate) ||\n variantProps.some((name) => isVariantLabel(props[name])));\n}\nfunction isVariantNode(props) {\n return Boolean(isControllingVariants(props) || props.variants);\n}\n\nexport { isControllingVariants, isVariantNode };\n","import { isVariantLabel } from '../../render/utils/is-variant-label.mjs';\nimport { isControllingVariants } from '../../render/utils/is-controlling-variants.mjs';\n\nfunction getCurrentTreeVariants(props, context) {\n if (isControllingVariants(props)) {\n const { initial, animate } = props;\n return {\n initial: initial === false || isVariantLabel(initial)\n ? initial\n : undefined,\n animate: isVariantLabel(animate) ? animate : undefined,\n };\n }\n return props.inherit !== false ? context : {};\n}\n\nexport { getCurrentTreeVariants };\n","import { useContext, useMemo } from 'react';\nimport { MotionContext } from './index.mjs';\nimport { getCurrentTreeVariants } from './utils.mjs';\n\nfunction useCreateMotionContext(props) {\n const { initial, animate } = getCurrentTreeVariants(props, useContext(MotionContext));\n return useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);\n}\nfunction variantLabelsAsDependency(prop) {\n return Array.isArray(prop) ? prop.join(\" \") : prop;\n}\n\nexport { useCreateMotionContext };\n","const featureProps = {\n animation: [\n \"animate\",\n \"variants\",\n \"whileHover\",\n \"whileTap\",\n \"exit\",\n \"whileInView\",\n \"whileFocus\",\n \"whileDrag\",\n ],\n exit: [\"exit\"],\n drag: [\"drag\", \"dragControls\"],\n focus: [\"whileFocus\"],\n hover: [\"whileHover\", \"onHoverStart\", \"onHoverEnd\"],\n tap: [\"whileTap\", \"onTap\", \"onTapStart\", \"onTapCancel\"],\n pan: [\"onPan\", \"onPanStart\", \"onPanSessionStart\", \"onPanEnd\"],\n inView: [\"whileInView\", \"onViewportEnter\", \"onViewportLeave\"],\n layout: [\"layout\", \"layoutId\"],\n};\nconst featureDefinitions = {};\nfor (const key in featureProps) {\n featureDefinitions[key] = {\n isEnabled: (props) => featureProps[key].some((name) => !!props[name]),\n };\n}\n\nexport { featureDefinitions };\n","import { featureDefinitions } from './definitions.mjs';\n\nfunction loadFeatures(features) {\n for (const key in features) {\n featureDefinitions[key] = {\n ...featureDefinitions[key],\n ...features[key],\n };\n }\n}\n\nexport { loadFeatures };\n","import { createContext } from 'react';\n\nconst LayoutGroupContext = createContext({});\n\nexport { LayoutGroupContext };\n","import { createContext } from 'react';\n\n/**\n * Internal, exported only for usage in Framer\n */\nconst SwitchLayoutGroupContext = createContext({});\n\nexport { SwitchLayoutGroupContext };\n","const motionComponentSymbol = Symbol.for(\"motionComponentSymbol\");\n\nexport { motionComponentSymbol };\n","import * as React from 'react';\nimport { forwardRef, useContext } from 'react';\nimport { MotionConfigContext } from '../context/MotionConfigContext.mjs';\nimport { MotionContext } from '../context/MotionContext/index.mjs';\nimport { useVisualElement } from './utils/use-visual-element.mjs';\nimport { useMotionRef } from './utils/use-motion-ref.mjs';\nimport { useCreateMotionContext } from '../context/MotionContext/create.mjs';\nimport { loadFeatures } from './features/load-features.mjs';\nimport { isBrowser } from '../utils/is-browser.mjs';\nimport { LayoutGroupContext } from '../context/LayoutGroupContext.mjs';\nimport { LazyContext } from '../context/LazyContext.mjs';\nimport { SwitchLayoutGroupContext } from '../context/SwitchLayoutGroupContext.mjs';\nimport { motionComponentSymbol } from './utils/symbol.mjs';\n\n/**\n * Create a `motion` component.\n *\n * This function accepts a Component argument, which can be either a string (ie \"div\"\n * for `motion.div`), or an actual React component.\n *\n * Alongside this is a config option which provides a way of rendering the provided\n * component \"offline\", or outside the React render cycle.\n */\nfunction createMotionComponent({ preloadedFeatures, createVisualElement, useRender, useVisualState, Component, }) {\n preloadedFeatures && loadFeatures(preloadedFeatures);\n function MotionComponent(props, externalRef) {\n /**\n * If we need to measure the element we load this functionality in a\n * separate class component in order to gain access to getSnapshotBeforeUpdate.\n */\n let MeasureLayout;\n const configAndProps = {\n ...useContext(MotionConfigContext),\n ...props,\n layoutId: useLayoutId(props),\n };\n const { isStatic } = configAndProps;\n const context = useCreateMotionContext(props);\n const visualState = useVisualState(props, isStatic);\n if (!isStatic && isBrowser) {\n /**\n * Create a VisualElement for this component. A VisualElement provides a common\n * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as\n * providing a way of rendering to these APIs outside of the React render loop\n * for more performant animations and interactions\n */\n context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement);\n /**\n * Load Motion gesture and animation features. These are rendered as renderless\n * components so each feature can optionally make use of React lifecycle methods.\n */\n const initialLayoutGroupConfig = useContext(SwitchLayoutGroupContext);\n const isStrict = useContext(LazyContext).strict;\n if (context.visualElement) {\n MeasureLayout = context.visualElement.loadFeatures(\n // Note: Pass the full new combined props to correctly re-render dynamic feature components.\n configAndProps, isStrict, preloadedFeatures, initialLayoutGroupConfig);\n }\n }\n /**\n * The mount order and hierarchy is specific to ensure our element ref\n * is hydrated by the time features fire their effects.\n */\n return (React.createElement(MotionContext.Provider, { value: context },\n MeasureLayout && context.visualElement ? (React.createElement(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null,\n useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, context.visualElement)));\n }\n const ForwardRefComponent = forwardRef(MotionComponent);\n ForwardRefComponent[motionComponentSymbol] = Component;\n return ForwardRefComponent;\n}\nfunction useLayoutId({ layoutId }) {\n const layoutGroupId = useContext(LayoutGroupContext).id;\n return layoutGroupId && layoutId !== undefined\n ? layoutGroupId + \"-\" + layoutId\n : layoutId;\n}\n\nexport { createMotionComponent };\n","import { createMotionComponent } from '../../motion/index.mjs';\n\n/**\n * Convert any React component into a `motion` component. The provided component\n * **must** use `React.forwardRef` to the underlying DOM component you want to animate.\n *\n * ```jsx\n * const Component = React.forwardRef((props, ref) => {\n * return \n * })\n *\n * const MotionComponent = motion(Component)\n * ```\n *\n * @public\n */\nfunction createMotionProxy(createConfig) {\n function custom(Component, customMotionComponentConfig = {}) {\n return createMotionComponent(createConfig(Component, customMotionComponentConfig));\n }\n if (typeof Proxy === \"undefined\") {\n return custom;\n }\n /**\n * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc.\n * Rather than generating them anew every render.\n */\n const componentCache = new Map();\n return new Proxy(custom, {\n /**\n * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc.\n * The prop name is passed through as `key` and we can use that to generate a `motion`\n * DOM component with that name.\n */\n get: (_target, key) => {\n /**\n * If this element doesn't exist in the component cache, create it and cache.\n */\n if (!componentCache.has(key)) {\n componentCache.set(key, custom(key));\n }\n return componentCache.get(key);\n },\n });\n}\n\nexport { createMotionProxy };\n","/**\n * We keep these listed seperately as we use the lowercase tag names as part\n * of the runtime bundle to detect SVG components\n */\nconst lowercaseSVGElements = [\n \"animate\",\n \"circle\",\n \"defs\",\n \"desc\",\n \"ellipse\",\n \"g\",\n \"image\",\n \"line\",\n \"filter\",\n \"marker\",\n \"mask\",\n \"metadata\",\n \"path\",\n \"pattern\",\n \"polygon\",\n \"polyline\",\n \"rect\",\n \"stop\",\n \"switch\",\n \"symbol\",\n \"svg\",\n \"text\",\n \"tspan\",\n \"use\",\n \"view\",\n];\n\nexport { lowercaseSVGElements };\n","import { lowercaseSVGElements } from '../../svg/lowercase-elements.mjs';\n\nfunction isSVGComponent(Component) {\n if (\n /**\n * If it's not a string, it's a custom React component. Currently we only support\n * HTML custom React components.\n */\n typeof Component !== \"string\" ||\n /**\n * If it contains a dash, the element is a custom HTML webcomponent.\n */\n Component.includes(\"-\")) {\n return false;\n }\n else if (\n /**\n * If it's in our list of lowercase SVG tags, it's an SVG component\n */\n lowercaseSVGElements.indexOf(Component) > -1 ||\n /**\n * If it contains a capital letter, it's an SVG component\n */\n /[A-Z]/.test(Component)) {\n return true;\n }\n return false;\n}\n\nexport { isSVGComponent };\n","const scaleCorrectors = {};\nfunction addScaleCorrector(correctors) {\n Object.assign(scaleCorrectors, correctors);\n}\n\nexport { addScaleCorrector, scaleCorrectors };\n","/**\n * Generate a list of every possible transform key.\n */\nconst transformPropOrder = [\n \"transformPerspective\",\n \"x\",\n \"y\",\n \"z\",\n \"translateX\",\n \"translateY\",\n \"translateZ\",\n \"scale\",\n \"scaleX\",\n \"scaleY\",\n \"rotate\",\n \"rotateX\",\n \"rotateY\",\n \"rotateZ\",\n \"skew\",\n \"skewX\",\n \"skewY\",\n];\n/**\n * A quick lookup for transform props.\n */\nconst transformProps = new Set(transformPropOrder);\n\nexport { transformPropOrder, transformProps };\n","import { scaleCorrectors } from '../../projection/styles/scale-correction.mjs';\nimport { transformProps } from '../../render/html/utils/transform.mjs';\n\nfunction isForcedMotionValue(key, { layout, layoutId }) {\n return (transformProps.has(key) ||\n key.startsWith(\"origin\") ||\n ((layout || layoutId !== undefined) &&\n (!!scaleCorrectors[key] || key === \"opacity\")));\n}\n\nexport { isForcedMotionValue };\n","const isMotionValue = (value) => Boolean(value && value.getVelocity);\n\nexport { isMotionValue };\n","import { transformPropOrder } from './transform.mjs';\n\nconst translateAlias = {\n x: \"translateX\",\n y: \"translateY\",\n z: \"translateZ\",\n transformPerspective: \"perspective\",\n};\nconst numTransforms = transformPropOrder.length;\n/**\n * Build a CSS transform style from individual x/y/scale etc properties.\n *\n * This outputs with a default order of transforms/scales/rotations, this can be customised by\n * providing a transformTemplate function.\n */\nfunction buildTransform(transform, { enableHardwareAcceleration = true, allowTransformNone = true, }, transformIsDefault, transformTemplate) {\n // The transform string we're going to build into.\n let transformString = \"\";\n /**\n * Loop over all possible transforms in order, adding the ones that\n * are present to the transform string.\n */\n for (let i = 0; i < numTransforms; i++) {\n const key = transformPropOrder[i];\n if (transform[key] !== undefined) {\n const transformName = translateAlias[key] || key;\n transformString += `${transformName}(${transform[key]}) `;\n }\n }\n if (enableHardwareAcceleration && !transform.z) {\n transformString += \"translateZ(0)\";\n }\n transformString = transformString.trim();\n // If we have a custom `transform` template, pass our transform values and\n // generated transformString to that before returning\n if (transformTemplate) {\n transformString = transformTemplate(transform, transformIsDefault ? \"\" : transformString);\n }\n else if (allowTransformNone && transformIsDefault) {\n transformString = \"none\";\n }\n return transformString;\n}\n\nexport { buildTransform };\n","const checkStringStartsWith = (token) => (key) => typeof key === \"string\" && key.startsWith(token);\nconst isCSSVariableName = checkStringStartsWith(\"--\");\nconst isCSSVariableToken = checkStringStartsWith(\"var(--\");\nconst cssVariableRegex = /var\\s*\\(\\s*--[\\w-]+(\\s*,\\s*(?:(?:[^)(]|\\((?:[^)(]+|\\([^)(]*\\))*\\))*)+)?\\s*\\)/g;\n\nexport { cssVariableRegex, isCSSVariableName, isCSSVariableToken };\n","/**\n * Provided a value and a ValueType, returns the value as that value type.\n */\nconst getValueAsType = (value, type) => {\n return type && typeof value === \"number\"\n ? type.transform(value)\n : value;\n};\n\nexport { getValueAsType };\n","const clamp = (min, max, v) => Math.min(Math.max(v, min), max);\n\nexport { clamp };\n","import { clamp } from '../../../utils/clamp.mjs';\n\nconst number = {\n test: (v) => typeof v === \"number\",\n parse: parseFloat,\n transform: (v) => v,\n};\nconst alpha = {\n ...number,\n transform: (v) => clamp(0, 1, v),\n};\nconst scale = {\n ...number,\n default: 1,\n};\n\nexport { alpha, number, scale };\n","/**\n * TODO: When we move from string as a source of truth to data models\n * everything in this folder should probably be referred to as models vs types\n */\n// If this number is a decimal, make it just five decimal places\n// to avoid exponents\nconst sanitize = (v) => Math.round(v * 100000) / 100000;\nconst floatRegex = /(-)?([\\d]*\\.?[\\d])+/g;\nconst colorRegex = /(#[0-9a-f]{3,8}|(rgb|hsl)a?\\((-?[\\d\\.]+%?[,\\s]+){2}(-?[\\d\\.]+%?)\\s*[\\,\\/]?\\s*[\\d\\.]*%?\\))/gi;\nconst singleColorRegex = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\\((-?[\\d\\.]+%?[,\\s]+){2}(-?[\\d\\.]+%?)\\s*[\\,\\/]?\\s*[\\d\\.]*%?\\))$/i;\nfunction isString(v) {\n return typeof v === \"string\";\n}\n\nexport { colorRegex, floatRegex, isString, sanitize, singleColorRegex };\n","import { isString } from '../utils.mjs';\n\nconst createUnitType = (unit) => ({\n test: (v) => isString(v) && v.endsWith(unit) && v.split(\" \").length === 1,\n parse: parseFloat,\n transform: (v) => `${v}${unit}`,\n});\nconst degrees = createUnitType(\"deg\");\nconst percent = createUnitType(\"%\");\nconst px = createUnitType(\"px\");\nconst vh = createUnitType(\"vh\");\nconst vw = createUnitType(\"vw\");\nconst progressPercentage = {\n ...percent,\n parse: (v) => percent.parse(v) / 100,\n transform: (v) => percent.transform(v * 100),\n};\n\nexport { degrees, percent, progressPercentage, px, vh, vw };\n","import { number } from '../../../value/types/numbers/index.mjs';\n\nconst int = {\n ...number,\n transform: Math.round,\n};\n\nexport { int };\n","import { scale, alpha } from '../../../value/types/numbers/index.mjs';\nimport { px, degrees, progressPercentage } from '../../../value/types/numbers/units.mjs';\nimport { int } from './type-int.mjs';\n\nconst numberValueTypes = {\n // Border props\n borderWidth: px,\n borderTopWidth: px,\n borderRightWidth: px,\n borderBottomWidth: px,\n borderLeftWidth: px,\n borderRadius: px,\n radius: px,\n borderTopLeftRadius: px,\n borderTopRightRadius: px,\n borderBottomRightRadius: px,\n borderBottomLeftRadius: px,\n // Positioning props\n width: px,\n maxWidth: px,\n height: px,\n maxHeight: px,\n size: px,\n top: px,\n right: px,\n bottom: px,\n left: px,\n // Spacing props\n padding: px,\n paddingTop: px,\n paddingRight: px,\n paddingBottom: px,\n paddingLeft: px,\n margin: px,\n marginTop: px,\n marginRight: px,\n marginBottom: px,\n marginLeft: px,\n // Transform props\n rotate: degrees,\n rotateX: degrees,\n rotateY: degrees,\n rotateZ: degrees,\n scale,\n scaleX: scale,\n scaleY: scale,\n scaleZ: scale,\n skew: degrees,\n skewX: degrees,\n skewY: degrees,\n distance: px,\n translateX: px,\n translateY: px,\n translateZ: px,\n x: px,\n y: px,\n z: px,\n perspective: px,\n transformPerspective: px,\n opacity: alpha,\n originX: progressPercentage,\n originY: progressPercentage,\n originZ: px,\n // Misc\n zIndex: int,\n // SVG\n fillOpacity: alpha,\n strokeOpacity: alpha,\n numOctaves: int,\n};\n\nexport { numberValueTypes };\n","import { buildTransform } from './build-transform.mjs';\nimport { isCSSVariableName } from '../../dom/utils/is-css-variable.mjs';\nimport { transformProps } from './transform.mjs';\nimport { getValueAsType } from '../../dom/value-types/get-as-type.mjs';\nimport { numberValueTypes } from '../../dom/value-types/number.mjs';\n\nfunction buildHTMLStyles(state, latestValues, options, transformTemplate) {\n const { style, vars, transform, transformOrigin } = state;\n // Track whether we encounter any transform or transformOrigin values.\n let hasTransform = false;\n let hasTransformOrigin = false;\n // Does the calculated transform essentially equal \"none\"?\n let transformIsNone = true;\n /**\n * Loop over all our latest animated values and decide whether to handle them\n * as a style or CSS variable.\n *\n * Transforms and transform origins are kept seperately for further processing.\n */\n for (const key in latestValues) {\n const value = latestValues[key];\n /**\n * If this is a CSS variable we don't do any further processing.\n */\n if (isCSSVariableName(key)) {\n vars[key] = value;\n continue;\n }\n // Convert the value to its default value type, ie 0 -> \"0px\"\n const valueType = numberValueTypes[key];\n const valueAsType = getValueAsType(value, valueType);\n if (transformProps.has(key)) {\n // If this is a transform, flag to enable further transform processing\n hasTransform = true;\n transform[key] = valueAsType;\n // If we already know we have a non-default transform, early return\n if (!transformIsNone)\n continue;\n // Otherwise check to see if this is a default transform\n if (value !== (valueType.default || 0))\n transformIsNone = false;\n }\n else if (key.startsWith(\"origin\")) {\n // If this is a transform origin, flag and enable further transform-origin processing\n hasTransformOrigin = true;\n transformOrigin[key] = valueAsType;\n }\n else {\n style[key] = valueAsType;\n }\n }\n if (!latestValues.transform) {\n if (hasTransform || transformTemplate) {\n style.transform = buildTransform(state.transform, options, transformIsNone, transformTemplate);\n }\n else if (style.transform) {\n /**\n * If we have previously created a transform but currently don't have any,\n * reset transform style to none.\n */\n style.transform = \"none\";\n }\n }\n /**\n * Build a transformOrigin style. Uses the same defaults as the browser for\n * undefined origins.\n */\n if (hasTransformOrigin) {\n const { originX = \"50%\", originY = \"50%\", originZ = 0, } = transformOrigin;\n style.transformOrigin = `${originX} ${originY} ${originZ}`;\n }\n}\n\nexport { buildHTMLStyles };\n","const createHtmlRenderState = () => ({\n style: {},\n transform: {},\n transformOrigin: {},\n vars: {},\n});\n\nexport { createHtmlRenderState };\n","import { useMemo } from 'react';\nimport { isForcedMotionValue } from '../../motion/utils/is-forced-motion-value.mjs';\nimport { isMotionValue } from '../../value/utils/is-motion-value.mjs';\nimport { buildHTMLStyles } from './utils/build-styles.mjs';\nimport { createHtmlRenderState } from './utils/create-render-state.mjs';\n\nfunction copyRawValuesOnly(target, source, props) {\n for (const key in source) {\n if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) {\n target[key] = source[key];\n }\n }\n}\nfunction useInitialMotionValues({ transformTemplate }, visualState, isStatic) {\n return useMemo(() => {\n const state = createHtmlRenderState();\n buildHTMLStyles(state, visualState, { enableHardwareAcceleration: !isStatic }, transformTemplate);\n return Object.assign({}, state.vars, state.style);\n }, [visualState]);\n}\nfunction useStyle(props, visualState, isStatic) {\n const styleProp = props.style || {};\n const style = {};\n /**\n * Copy non-Motion Values straight into style\n */\n copyRawValuesOnly(style, styleProp, props);\n Object.assign(style, useInitialMotionValues(props, visualState, isStatic));\n return props.transformValues ? props.transformValues(style) : style;\n}\nfunction useHTMLProps(props, visualState, isStatic) {\n // The `any` isn't ideal but it is the type of createElement props argument\n const htmlProps = {};\n const style = useStyle(props, visualState, isStatic);\n if (props.drag && props.dragListener !== false) {\n // Disable the ghost element when a user drags\n htmlProps.draggable = false;\n // Disable text selection\n style.userSelect =\n style.WebkitUserSelect =\n style.WebkitTouchCallout =\n \"none\";\n // Disable scrolling on the draggable direction\n style.touchAction =\n props.drag === true\n ? \"none\"\n : `pan-${props.drag === \"x\" ? \"y\" : \"x\"}`;\n }\n if (props.tabIndex === undefined &&\n (props.onTap || props.onTapStart || props.whileTap)) {\n htmlProps.tabIndex = 0;\n }\n htmlProps.style = style;\n return htmlProps;\n}\n\nexport { copyRawValuesOnly, useHTMLProps };\n","/**\n * A list of all valid MotionProps.\n *\n * @privateRemarks\n * This doesn't throw if a `MotionProp` name is missing - it should.\n */\nconst validMotionProps = new Set([\n \"animate\",\n \"exit\",\n \"variants\",\n \"initial\",\n \"style\",\n \"values\",\n \"variants\",\n \"transition\",\n \"transformTemplate\",\n \"transformValues\",\n \"custom\",\n \"inherit\",\n \"onBeforeLayoutMeasure\",\n \"onAnimationStart\",\n \"onAnimationComplete\",\n \"onUpdate\",\n \"onDragStart\",\n \"onDrag\",\n \"onDragEnd\",\n \"onMeasureDragConstraints\",\n \"onDirectionLock\",\n \"onDragTransitionEnd\",\n \"_dragX\",\n \"_dragY\",\n \"onHoverStart\",\n \"onHoverEnd\",\n \"onViewportEnter\",\n \"onViewportLeave\",\n \"globalTapTarget\",\n \"ignoreStrict\",\n \"viewport\",\n]);\n/**\n * Check whether a prop name is a valid `MotionProp` key.\n *\n * @param key - Name of the property to check\n * @returns `true` is key is a valid `MotionProp`.\n *\n * @public\n */\nfunction isValidMotionProp(key) {\n return (key.startsWith(\"while\") ||\n (key.startsWith(\"drag\") && key !== \"draggable\") ||\n key.startsWith(\"layout\") ||\n key.startsWith(\"onTap\") ||\n key.startsWith(\"onPan\") ||\n key.startsWith(\"onLayout\") ||\n validMotionProps.has(key));\n}\n\nexport { isValidMotionProp };\n","import { isValidMotionProp } from '../../../motion/utils/valid-prop.mjs';\n\nlet shouldForward = (key) => !isValidMotionProp(key);\nfunction loadExternalIsValidProp(isValidProp) {\n if (!isValidProp)\n return;\n // Explicitly filter our events\n shouldForward = (key) => key.startsWith(\"on\") ? !isValidMotionProp(key) : isValidProp(key);\n}\n/**\n * Emotion and Styled Components both allow users to pass through arbitrary props to their components\n * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which\n * of these should be passed to the underlying DOM node.\n *\n * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props\n * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props\n * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of\n * `@emotion/is-prop-valid`, however to fix this problem we need to use it.\n *\n * By making it an optionalDependency we can offer this functionality only in the situations where it's\n * actually required.\n */\ntry {\n /**\n * We attempt to import this package but require won't be defined in esm environments, in that case\n * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed\n * in favour of explicit injection.\n */\n loadExternalIsValidProp(require(\"@emotion/is-prop-valid\").default);\n}\ncatch (_a) {\n // We don't need to actually do anything here - the fallback is the existing `isPropValid`.\n}\nfunction filterProps(props, isDom, forwardMotionProps) {\n const filteredProps = {};\n for (const key in props) {\n /**\n * values is considered a valid prop by Emotion, so if it's present\n * this will be rendered out to the DOM unless explicitly filtered.\n *\n * We check the type as it could be used with the `feColorMatrix`\n * element, which we support.\n */\n if (key === \"values\" && typeof props.values === \"object\")\n continue;\n if (shouldForward(key) ||\n (forwardMotionProps === true && isValidMotionProp(key)) ||\n (!isDom && !isValidMotionProp(key)) ||\n // If trying to use native HTML drag events, forward drag listeners\n (props[\"draggable\"] && key.startsWith(\"onDrag\"))) {\n filteredProps[key] = props[key];\n }\n }\n return filteredProps;\n}\n\nexport { filterProps, loadExternalIsValidProp };\n","import { px } from '../../../value/types/numbers/units.mjs';\n\nfunction calcOrigin(origin, offset, size) {\n return typeof origin === \"string\"\n ? origin\n : px.transform(offset + size * origin);\n}\n/**\n * The SVG transform origin defaults are different to CSS and is less intuitive,\n * so we use the measured dimensions of the SVG to reconcile these.\n */\nfunction calcSVGTransformOrigin(dimensions, originX, originY) {\n const pxOriginX = calcOrigin(originX, dimensions.x, dimensions.width);\n const pxOriginY = calcOrigin(originY, dimensions.y, dimensions.height);\n return `${pxOriginX} ${pxOriginY}`;\n}\n\nexport { calcSVGTransformOrigin };\n","import { px } from '../../../value/types/numbers/units.mjs';\n\nconst dashKeys = {\n offset: \"stroke-dashoffset\",\n array: \"stroke-dasharray\",\n};\nconst camelKeys = {\n offset: \"strokeDashoffset\",\n array: \"strokeDasharray\",\n};\n/**\n * Build SVG path properties. Uses the path's measured length to convert\n * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset\n * and stroke-dasharray attributes.\n *\n * This function is mutative to reduce per-frame GC.\n */\nfunction buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {\n // Normalise path length by setting SVG attribute pathLength to 1\n attrs.pathLength = 1;\n // We use dash case when setting attributes directly to the DOM node and camel case\n // when defining props on a React component.\n const keys = useDashCase ? dashKeys : camelKeys;\n // Build the dash offset\n attrs[keys.offset] = px.transform(-offset);\n // Build the dash array\n const pathLength = px.transform(length);\n const pathSpacing = px.transform(spacing);\n attrs[keys.array] = `${pathLength} ${pathSpacing}`;\n}\n\nexport { buildSVGPath };\n","import { buildHTMLStyles } from '../../html/utils/build-styles.mjs';\nimport { calcSVGTransformOrigin } from './transform-origin.mjs';\nimport { buildSVGPath } from './path.mjs';\n\n/**\n * Build SVG visual attrbutes, like cx and style.transform\n */\nfunction buildSVGAttrs(state, { attrX, attrY, attrScale, originX, originY, pathLength, pathSpacing = 1, pathOffset = 0, \n// This is object creation, which we try to avoid per-frame.\n...latest }, options, isSVGTag, transformTemplate) {\n buildHTMLStyles(state, latest, options, transformTemplate);\n /**\n * For svg tags we just want to make sure viewBox is animatable and treat all the styles\n * as normal HTML tags.\n */\n if (isSVGTag) {\n if (state.style.viewBox) {\n state.attrs.viewBox = state.style.viewBox;\n }\n return;\n }\n state.attrs = state.style;\n state.style = {};\n const { attrs, style, dimensions } = state;\n /**\n * However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs\n * and copy it into style.\n */\n if (attrs.transform) {\n if (dimensions)\n style.transform = attrs.transform;\n delete attrs.transform;\n }\n // Parse transformOrigin\n if (dimensions &&\n (originX !== undefined || originY !== undefined || style.transform)) {\n style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== undefined ? originX : 0.5, originY !== undefined ? originY : 0.5);\n }\n // Render attrX/attrY/attrScale as attributes\n if (attrX !== undefined)\n attrs.x = attrX;\n if (attrY !== undefined)\n attrs.y = attrY;\n if (attrScale !== undefined)\n attrs.scale = attrScale;\n // Build SVG path if one has been defined\n if (pathLength !== undefined) {\n buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);\n }\n}\n\nexport { buildSVGAttrs };\n","import { createHtmlRenderState } from '../../html/utils/create-render-state.mjs';\n\nconst createSvgRenderState = () => ({\n ...createHtmlRenderState(),\n attrs: {},\n});\n\nexport { createSvgRenderState };\n","const isSVGTag = (tag) => typeof tag === \"string\" && tag.toLowerCase() === \"svg\";\n\nexport { isSVGTag };\n","import { useMemo } from 'react';\nimport { copyRawValuesOnly } from '../html/use-props.mjs';\nimport { buildSVGAttrs } from './utils/build-attrs.mjs';\nimport { createSvgRenderState } from './utils/create-render-state.mjs';\nimport { isSVGTag } from './utils/is-svg-tag.mjs';\n\nfunction useSVGProps(props, visualState, _isStatic, Component) {\n const visualProps = useMemo(() => {\n const state = createSvgRenderState();\n buildSVGAttrs(state, visualState, { enableHardwareAcceleration: false }, isSVGTag(Component), props.transformTemplate);\n return {\n ...state.attrs,\n style: { ...state.style },\n };\n }, [visualState]);\n if (props.style) {\n const rawStyles = {};\n copyRawValuesOnly(rawStyles, props.style, props);\n visualProps.style = { ...rawStyles, ...visualProps.style };\n }\n return visualProps;\n}\n\nexport { useSVGProps };\n","import { useMemo, createElement } from 'react';\nimport { useHTMLProps } from '../html/use-props.mjs';\nimport { filterProps } from './utils/filter-props.mjs';\nimport { isSVGComponent } from './utils/is-svg-component.mjs';\nimport { useSVGProps } from '../svg/use-props.mjs';\nimport { isMotionValue } from '../../value/utils/is-motion-value.mjs';\n\nfunction createUseRender(forwardMotionProps = false) {\n const useRender = (Component, props, ref, { latestValues }, isStatic) => {\n const useVisualProps = isSVGComponent(Component)\n ? useSVGProps\n : useHTMLProps;\n const visualProps = useVisualProps(props, latestValues, isStatic, Component);\n const filteredProps = filterProps(props, typeof Component === \"string\", forwardMotionProps);\n const elementProps = {\n ...filteredProps,\n ...visualProps,\n ref,\n };\n /**\n * If component has been handed a motion value as its child,\n * memoise its initial value and render that. Subsequent updates\n * will be handled by the onChange handler\n */\n const { children } = props;\n const renderedChildren = useMemo(() => (isMotionValue(children) ? children.get() : children), [children]);\n return createElement(Component, {\n ...elementProps,\n children: renderedChildren,\n });\n };\n return useRender;\n}\n\nexport { createUseRender };\n","function renderHTML(element, { style, vars }, styleProp, projection) {\n Object.assign(element.style, style, projection && projection.getProjectionStyles(styleProp));\n // Loop over any CSS variables and assign those.\n for (const key in vars) {\n element.style.setProperty(key, vars[key]);\n }\n}\n\nexport { renderHTML };\n","/**\n * A set of attribute names that are always read/written as camel case.\n */\nconst camelCaseAttributes = new Set([\n \"baseFrequency\",\n \"diffuseConstant\",\n \"kernelMatrix\",\n \"kernelUnitLength\",\n \"keySplines\",\n \"keyTimes\",\n \"limitingConeAngle\",\n \"markerHeight\",\n \"markerWidth\",\n \"numOctaves\",\n \"targetX\",\n \"targetY\",\n \"surfaceScale\",\n \"specularConstant\",\n \"specularExponent\",\n \"stdDeviation\",\n \"tableValues\",\n \"viewBox\",\n \"gradientTransform\",\n \"pathLength\",\n \"startOffset\",\n \"textLength\",\n \"lengthAdjust\",\n]);\n\nexport { camelCaseAttributes };\n","import { camelToDash } from '../../dom/utils/camel-to-dash.mjs';\nimport { renderHTML } from '../../html/utils/render.mjs';\nimport { camelCaseAttributes } from './camel-case-attrs.mjs';\n\nfunction renderSVG(element, renderState, _styleProp, projection) {\n renderHTML(element, renderState, undefined, projection);\n for (const key in renderState.attrs) {\n element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);\n }\n}\n\nexport { renderSVG };\n","import { isForcedMotionValue } from '../../../motion/utils/is-forced-motion-value.mjs';\nimport { isMotionValue } from '../../../value/utils/is-motion-value.mjs';\n\nfunction scrapeMotionValuesFromProps(props, prevProps) {\n const { style } = props;\n const newValues = {};\n for (const key in style) {\n if (isMotionValue(style[key]) ||\n (prevProps.style && isMotionValue(prevProps.style[key])) ||\n isForcedMotionValue(key, props)) {\n newValues[key] = style[key];\n }\n }\n return newValues;\n}\n\nexport { scrapeMotionValuesFromProps };\n","import { isMotionValue } from '../../../value/utils/is-motion-value.mjs';\nimport { scrapeMotionValuesFromProps as scrapeMotionValuesFromProps$1 } from '../../html/utils/scrape-motion-values.mjs';\nimport { transformPropOrder } from '../../html/utils/transform.mjs';\n\nfunction scrapeMotionValuesFromProps(props, prevProps) {\n const newValues = scrapeMotionValuesFromProps$1(props, prevProps);\n for (const key in props) {\n if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) {\n const targetKey = transformPropOrder.indexOf(key) !== -1\n ? \"attr\" + key.charAt(0).toUpperCase() + key.substring(1)\n : key;\n newValues[targetKey] = props[key];\n }\n }\n return newValues;\n}\n\nexport { scrapeMotionValuesFromProps };\n","function resolveVariantFromProps(props, definition, custom, currentValues = {}, currentVelocity = {}) {\n /**\n * If the variant definition is a function, resolve.\n */\n if (typeof definition === \"function\") {\n definition = definition(custom !== undefined ? custom : props.custom, currentValues, currentVelocity);\n }\n /**\n * If the variant definition is a variant label, or\n * the function returned a variant label, resolve.\n */\n if (typeof definition === \"string\") {\n definition = props.variants && props.variants[definition];\n }\n /**\n * At this point we've resolved both functions and variant labels,\n * but the resolved variant label might itself have been a function.\n * If so, resolve. This can only have returned a valid target object.\n */\n if (typeof definition === \"function\") {\n definition = definition(custom !== undefined ? custom : props.custom, currentValues, currentVelocity);\n }\n return definition;\n}\n\nexport { resolveVariantFromProps };\n","import { useRef } from 'react';\n\n/**\n * Creates a constant value over the lifecycle of a component.\n *\n * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer\n * a guarantee that it won't re-run for performance reasons later on. By using `useConstant`\n * you can ensure that initialisers don't execute twice or more.\n */\nfunction useConstant(init) {\n const ref = useRef(null);\n if (ref.current === null) {\n ref.current = init();\n }\n return ref.current;\n}\n\nexport { useConstant };\n","const isKeyframesTarget = (v) => {\n return Array.isArray(v);\n};\n\nexport { isKeyframesTarget };\n","import { isKeyframesTarget } from '../animation/utils/is-keyframes-target.mjs';\n\nconst isCustomValue = (v) => {\n return Boolean(v && typeof v === \"object\" && v.mix && v.toValue);\n};\nconst resolveFinalValueInKeyframes = (v) => {\n // TODO maybe throw if v.length - 1 is placeholder token?\n return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;\n};\n\nexport { isCustomValue, resolveFinalValueInKeyframes };\n","import { isCustomValue } from '../../utils/resolve-value.mjs';\nimport { isMotionValue } from './is-motion-value.mjs';\n\n/**\n * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself\n *\n * TODO: Remove and move to library\n */\nfunction resolveMotionValue(value) {\n const unwrappedValue = isMotionValue(value) ? value.get() : value;\n return isCustomValue(unwrappedValue)\n ? unwrappedValue.toValue()\n : unwrappedValue;\n}\n\nexport { resolveMotionValue };\n","import { useContext } from 'react';\nimport { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\nimport { resolveVariantFromProps } from '../../render/utils/resolve-variants.mjs';\nimport { useConstant } from '../../utils/use-constant.mjs';\nimport { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs';\nimport { MotionContext } from '../../context/MotionContext/index.mjs';\nimport { isControllingVariants, isVariantNode } from '../../render/utils/is-controlling-variants.mjs';\n\nfunction makeState({ scrapeMotionValuesFromProps, createRenderState, onMount, }, props, context, presenceContext) {\n const state = {\n latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps),\n renderState: createRenderState(),\n };\n if (onMount) {\n state.mount = (instance) => onMount(props, instance, state);\n }\n return state;\n}\nconst makeUseVisualState = (config) => (props, isStatic) => {\n const context = useContext(MotionContext);\n const presenceContext = useContext(PresenceContext);\n const make = () => makeState(config, props, context, presenceContext);\n return isStatic ? make() : useConstant(make);\n};\nfunction makeLatestValues(props, context, presenceContext, scrapeMotionValues) {\n const values = {};\n const motionValues = scrapeMotionValues(props, {});\n for (const key in motionValues) {\n values[key] = resolveMotionValue(motionValues[key]);\n }\n let { initial, animate } = props;\n const isControllingVariants$1 = isControllingVariants(props);\n const isVariantNode$1 = isVariantNode(props);\n if (context &&\n isVariantNode$1 &&\n !isControllingVariants$1 &&\n props.inherit !== false) {\n if (initial === undefined)\n initial = context.initial;\n if (animate === undefined)\n animate = context.animate;\n }\n let isInitialAnimationBlocked = presenceContext\n ? presenceContext.initial === false\n : false;\n isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false;\n const variantToSet = isInitialAnimationBlocked ? animate : initial;\n if (variantToSet &&\n typeof variantToSet !== \"boolean\" &&\n !isAnimationControls(variantToSet)) {\n const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet];\n list.forEach((definition) => {\n const resolved = resolveVariantFromProps(props, definition);\n if (!resolved)\n return;\n const { transitionEnd, transition, ...target } = resolved;\n for (const key in target) {\n let valueTarget = target[key];\n if (Array.isArray(valueTarget)) {\n /**\n * Take final keyframe if the initial animation is blocked because\n * we want to initialise at the end of that blocked animation.\n */\n const index = isInitialAnimationBlocked\n ? valueTarget.length - 1\n : 0;\n valueTarget = valueTarget[index];\n }\n if (valueTarget !== null) {\n values[key] = valueTarget;\n }\n }\n for (const key in transitionEnd)\n values[key] = transitionEnd[key];\n });\n }\n return values;\n}\n\nexport { makeUseVisualState };\n","const noop = (any) => any;\n\nexport { noop };\n","class Queue {\n constructor() {\n this.order = [];\n this.scheduled = new Set();\n }\n add(process) {\n if (!this.scheduled.has(process)) {\n this.scheduled.add(process);\n this.order.push(process);\n return true;\n }\n }\n remove(process) {\n const index = this.order.indexOf(process);\n if (index !== -1) {\n this.order.splice(index, 1);\n this.scheduled.delete(process);\n }\n }\n clear() {\n this.order.length = 0;\n this.scheduled.clear();\n }\n}\nfunction createRenderStep(runNextFrame) {\n /**\n * We create and reuse two queues, one to queue jobs for the current frame\n * and one for the next. We reuse to avoid triggering GC after x frames.\n */\n let thisFrame = new Queue();\n let nextFrame = new Queue();\n let numToRun = 0;\n /**\n * Track whether we're currently processing jobs in this step. This way\n * we can decide whether to schedule new jobs for this frame or next.\n */\n let isProcessing = false;\n let flushNextFrame = false;\n /**\n * A set of processes which were marked keepAlive when scheduled.\n */\n const toKeepAlive = new WeakSet();\n const step = {\n /**\n * Schedule a process to run on the next frame.\n */\n schedule: (callback, keepAlive = false, immediate = false) => {\n const addToCurrentFrame = immediate && isProcessing;\n const queue = addToCurrentFrame ? thisFrame : nextFrame;\n if (keepAlive)\n toKeepAlive.add(callback);\n if (queue.add(callback) && addToCurrentFrame && isProcessing) {\n // If we're adding it to the currently running queue, update its measured size\n numToRun = thisFrame.order.length;\n }\n return callback;\n },\n /**\n * Cancel the provided callback from running on the next frame.\n */\n cancel: (callback) => {\n nextFrame.remove(callback);\n toKeepAlive.delete(callback);\n },\n /**\n * Execute all schedule callbacks.\n */\n process: (frameData) => {\n /**\n * If we're already processing we've probably been triggered by a flushSync\n * inside an existing process. Instead of executing, mark flushNextFrame\n * as true and ensure we flush the following frame at the end of this one.\n */\n if (isProcessing) {\n flushNextFrame = true;\n return;\n }\n isProcessing = true;\n [thisFrame, nextFrame] = [nextFrame, thisFrame];\n // Clear the next frame queue\n nextFrame.clear();\n // Execute this frame\n numToRun = thisFrame.order.length;\n if (numToRun) {\n for (let i = 0; i < numToRun; i++) {\n const callback = thisFrame.order[i];\n callback(frameData);\n if (toKeepAlive.has(callback)) {\n step.schedule(callback);\n runNextFrame();\n }\n }\n }\n isProcessing = false;\n if (flushNextFrame) {\n flushNextFrame = false;\n step.process(frameData);\n }\n },\n };\n return step;\n}\n\nexport { createRenderStep };\n","import { createRenderStep } from './render-step.mjs';\n\nconst stepsOrder = [\n \"prepare\",\n \"read\",\n \"update\",\n \"preRender\",\n \"render\",\n \"postRender\",\n];\nconst maxElapsed = 40;\nfunction createRenderBatcher(scheduleNextBatch, allowKeepAlive) {\n let runNextFrame = false;\n let useDefaultElapsed = true;\n const state = {\n delta: 0,\n timestamp: 0,\n isProcessing: false,\n };\n const steps = stepsOrder.reduce((acc, key) => {\n acc[key] = createRenderStep(() => (runNextFrame = true));\n return acc;\n }, {});\n const processStep = (stepId) => steps[stepId].process(state);\n const processBatch = () => {\n const timestamp = performance.now();\n runNextFrame = false;\n state.delta = useDefaultElapsed\n ? 1000 / 60\n : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);\n state.timestamp = timestamp;\n state.isProcessing = true;\n stepsOrder.forEach(processStep);\n state.isProcessing = false;\n if (runNextFrame && allowKeepAlive) {\n useDefaultElapsed = false;\n scheduleNextBatch(processBatch);\n }\n };\n const wake = () => {\n runNextFrame = true;\n useDefaultElapsed = true;\n if (!state.isProcessing) {\n scheduleNextBatch(processBatch);\n }\n };\n const schedule = stepsOrder.reduce((acc, key) => {\n const step = steps[key];\n acc[key] = (process, keepAlive = false, immediate = false) => {\n if (!runNextFrame)\n wake();\n return step.schedule(process, keepAlive, immediate);\n };\n return acc;\n }, {});\n const cancel = (process) => stepsOrder.forEach((key) => steps[key].cancel(process));\n return { schedule, cancel, state, steps };\n}\n\nexport { createRenderBatcher, stepsOrder };\n","import { noop } from '../utils/noop.mjs';\nimport { createRenderBatcher } from './batcher.mjs';\n\nconst { schedule: frame, cancel: cancelFrame, state: frameData, steps, } = createRenderBatcher(typeof requestAnimationFrame !== \"undefined\" ? requestAnimationFrame : noop, true);\n\nexport { cancelFrame, frame, frameData, steps };\n","import { renderSVG } from './utils/render.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\nimport { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs';\nimport { createSvgRenderState } from './utils/create-render-state.mjs';\nimport { buildSVGAttrs } from './utils/build-attrs.mjs';\nimport { isSVGTag } from './utils/is-svg-tag.mjs';\nimport { frame } from '../../frameloop/frame.mjs';\n\nconst svgMotionConfig = {\n useVisualState: makeUseVisualState({\n scrapeMotionValuesFromProps: scrapeMotionValuesFromProps,\n createRenderState: createSvgRenderState,\n onMount: (props, instance, { renderState, latestValues }) => {\n frame.read(() => {\n try {\n renderState.dimensions =\n typeof instance.getBBox ===\n \"function\"\n ? instance.getBBox()\n : instance.getBoundingClientRect();\n }\n catch (e) {\n // Most likely trying to measure an unrendered element under Firefox\n renderState.dimensions = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n };\n }\n });\n frame.render(() => {\n buildSVGAttrs(renderState, latestValues, { enableHardwareAcceleration: false }, isSVGTag(instance.tagName), props.transformTemplate);\n renderSVG(instance, renderState);\n });\n },\n }),\n};\n\nexport { svgMotionConfig };\n","import { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\nimport { createHtmlRenderState } from './utils/create-render-state.mjs';\n\nconst htmlMotionConfig = {\n useVisualState: makeUseVisualState({\n scrapeMotionValuesFromProps,\n createRenderState: createHtmlRenderState,\n }),\n};\n\nexport { htmlMotionConfig };\n","import { isSVGComponent } from './is-svg-component.mjs';\nimport { createUseRender } from '../use-render.mjs';\nimport { svgMotionConfig } from '../../svg/config-motion.mjs';\nimport { htmlMotionConfig } from '../../html/config-motion.mjs';\n\nfunction createDomMotionConfig(Component, { forwardMotionProps = false }, preloadedFeatures, createVisualElement) {\n const baseConfig = isSVGComponent(Component)\n ? svgMotionConfig\n : htmlMotionConfig;\n return {\n ...baseConfig,\n preloadedFeatures,\n useRender: createUseRender(forwardMotionProps),\n createVisualElement,\n Component,\n };\n}\n\nexport { createDomMotionConfig };\n","function addDomEvent(target, eventName, handler, options = { passive: true }) {\n target.addEventListener(eventName, handler, options);\n return () => target.removeEventListener(eventName, handler);\n}\n\nexport { addDomEvent };\n","const isPrimaryPointer = (event) => {\n if (event.pointerType === \"mouse\") {\n return typeof event.button !== \"number\" || event.button <= 0;\n }\n else {\n /**\n * isPrimary is true for all mice buttons, whereas every touch point\n * is regarded as its own input. So subsequent concurrent touch points\n * will be false.\n *\n * Specifically match against false here as incomplete versions of\n * PointerEvents in very old browser might have it set as undefined.\n */\n return event.isPrimary !== false;\n }\n};\n\nexport { isPrimaryPointer };\n","import { isPrimaryPointer } from './utils/is-primary-pointer.mjs';\n\nfunction extractEventInfo(event, pointType = \"page\") {\n return {\n point: {\n x: event[pointType + \"X\"],\n y: event[pointType + \"Y\"],\n },\n };\n}\nconst addPointerInfo = (handler) => {\n return (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event));\n};\n\nexport { addPointerInfo, extractEventInfo };\n","import { addDomEvent } from './add-dom-event.mjs';\nimport { addPointerInfo } from './event-info.mjs';\n\nfunction addPointerEvent(target, eventName, handler, options) {\n return addDomEvent(target, eventName, addPointerInfo(handler), options);\n}\n\nexport { addPointerEvent };\n","/**\n * Pipe\n * Compose other transformers to run linearily\n * pipe(min(20), max(40))\n * @param {...functions} transformers\n * @return {function}\n */\nconst combineFunctions = (a, b) => (v) => b(a(v));\nconst pipe = (...transformers) => transformers.reduce(combineFunctions);\n\nexport { pipe };\n","function createLock(name) {\n let lock = null;\n return () => {\n const openLock = () => {\n lock = null;\n };\n if (lock === null) {\n lock = name;\n return openLock;\n }\n return false;\n };\n}\nconst globalHorizontalLock = createLock(\"dragHorizontal\");\nconst globalVerticalLock = createLock(\"dragVertical\");\nfunction getGlobalLock(drag) {\n let lock = false;\n if (drag === \"y\") {\n lock = globalVerticalLock();\n }\n else if (drag === \"x\") {\n lock = globalHorizontalLock();\n }\n else {\n const openHorizontal = globalHorizontalLock();\n const openVertical = globalVerticalLock();\n if (openHorizontal && openVertical) {\n lock = () => {\n openHorizontal();\n openVertical();\n };\n }\n else {\n // Release the locks because we don't use them\n if (openHorizontal)\n openHorizontal();\n if (openVertical)\n openVertical();\n }\n }\n return lock;\n}\nfunction isDragActive() {\n // Check the gesture lock - if we get it, it means no drag gesture is active\n // and we can safely fire the tap gesture.\n const openGestureLock = getGlobalLock(true);\n if (!openGestureLock)\n return true;\n openGestureLock();\n return false;\n}\n\nexport { createLock, getGlobalLock, isDragActive };\n","class Feature {\n constructor(node) {\n this.isMounted = false;\n this.node = node;\n }\n update() { }\n}\n\nexport { Feature };\n","import { addPointerEvent } from '../events/add-pointer-event.mjs';\nimport { pipe } from '../utils/pipe.mjs';\nimport { isDragActive } from './drag/utils/lock.mjs';\nimport { Feature } from '../motion/features/Feature.mjs';\nimport { frame } from '../frameloop/frame.mjs';\n\nfunction addHoverEvent(node, isActive) {\n const eventName = \"pointer\" + (isActive ? \"enter\" : \"leave\");\n const callbackName = \"onHover\" + (isActive ? \"Start\" : \"End\");\n const handleEvent = (event, info) => {\n if (event.pointerType === \"touch\" || isDragActive())\n return;\n const props = node.getProps();\n if (node.animationState && props.whileHover) {\n node.animationState.setActive(\"whileHover\", isActive);\n }\n if (props[callbackName]) {\n frame.update(() => props[callbackName](event, info));\n }\n };\n return addPointerEvent(node.current, eventName, handleEvent, {\n passive: !node.getProps()[callbackName],\n });\n}\nclass HoverGesture extends Feature {\n mount() {\n this.unmount = pipe(addHoverEvent(this.node, true), addHoverEvent(this.node, false));\n }\n unmount() { }\n}\n\nexport { HoverGesture };\n","import { addDomEvent } from '../events/add-dom-event.mjs';\nimport { Feature } from '../motion/features/Feature.mjs';\nimport { pipe } from '../utils/pipe.mjs';\n\nclass FocusGesture extends Feature {\n constructor() {\n super(...arguments);\n this.isActive = false;\n }\n onFocus() {\n let isFocusVisible = false;\n /**\n * If this element doesn't match focus-visible then don't\n * apply whileHover. But, if matches throws that focus-visible\n * is not a valid selector then in that browser outline styles will be applied\n * to the element by default and we want to match that behaviour with whileFocus.\n */\n try {\n isFocusVisible = this.node.current.matches(\":focus-visible\");\n }\n catch (e) {\n isFocusVisible = true;\n }\n if (!isFocusVisible || !this.node.animationState)\n return;\n this.node.animationState.setActive(\"whileFocus\", true);\n this.isActive = true;\n }\n onBlur() {\n if (!this.isActive || !this.node.animationState)\n return;\n this.node.animationState.setActive(\"whileFocus\", false);\n this.isActive = false;\n }\n mount() {\n this.unmount = pipe(addDomEvent(this.node.current, \"focus\", () => this.onFocus()), addDomEvent(this.node.current, \"blur\", () => this.onBlur()));\n }\n unmount() { }\n}\n\nexport { FocusGesture };\n","/**\n * Recursively traverse up the tree to check whether the provided child node\n * is the parent or a descendant of it.\n *\n * @param parent - Element to find\n * @param child - Element to test against parent\n */\nconst isNodeOrChild = (parent, child) => {\n if (!child) {\n return false;\n }\n else if (parent === child) {\n return true;\n }\n else {\n return isNodeOrChild(parent, child.parentElement);\n }\n};\n\nexport { isNodeOrChild };\n","import { extractEventInfo } from '../events/event-info.mjs';\nimport { addDomEvent } from '../events/add-dom-event.mjs';\nimport { addPointerEvent } from '../events/add-pointer-event.mjs';\nimport { Feature } from '../motion/features/Feature.mjs';\nimport { pipe } from '../utils/pipe.mjs';\nimport { isDragActive } from './drag/utils/lock.mjs';\nimport { isNodeOrChild } from './utils/is-node-or-child.mjs';\nimport { noop } from '../utils/noop.mjs';\nimport { frame } from '../frameloop/frame.mjs';\n\nfunction fireSyntheticPointerEvent(name, handler) {\n if (!handler)\n return;\n const syntheticPointerEvent = new PointerEvent(\"pointer\" + name);\n handler(syntheticPointerEvent, extractEventInfo(syntheticPointerEvent));\n}\nclass PressGesture extends Feature {\n constructor() {\n super(...arguments);\n this.removeStartListeners = noop;\n this.removeEndListeners = noop;\n this.removeAccessibleListeners = noop;\n this.startPointerPress = (startEvent, startInfo) => {\n if (this.isPressing)\n return;\n this.removeEndListeners();\n const props = this.node.getProps();\n const endPointerPress = (endEvent, endInfo) => {\n if (!this.checkPressEnd())\n return;\n const { onTap, onTapCancel, globalTapTarget } = this.node.getProps();\n frame.update(() => {\n /**\n * We only count this as a tap gesture if the event.target is the same\n * as, or a child of, this component's element\n */\n !globalTapTarget &&\n !isNodeOrChild(this.node.current, endEvent.target)\n ? onTapCancel && onTapCancel(endEvent, endInfo)\n : onTap && onTap(endEvent, endInfo);\n });\n };\n const removePointerUpListener = addPointerEvent(window, \"pointerup\", endPointerPress, { passive: !(props.onTap || props[\"onPointerUp\"]) });\n const removePointerCancelListener = addPointerEvent(window, \"pointercancel\", (cancelEvent, cancelInfo) => this.cancelPress(cancelEvent, cancelInfo), { passive: !(props.onTapCancel || props[\"onPointerCancel\"]) });\n this.removeEndListeners = pipe(removePointerUpListener, removePointerCancelListener);\n this.startPress(startEvent, startInfo);\n };\n this.startAccessiblePress = () => {\n const handleKeydown = (keydownEvent) => {\n if (keydownEvent.key !== \"Enter\" || this.isPressing)\n return;\n const handleKeyup = (keyupEvent) => {\n if (keyupEvent.key !== \"Enter\" || !this.checkPressEnd())\n return;\n fireSyntheticPointerEvent(\"up\", (event, info) => {\n const { onTap } = this.node.getProps();\n if (onTap) {\n frame.update(() => onTap(event, info));\n }\n });\n };\n this.removeEndListeners();\n this.removeEndListeners = addDomEvent(this.node.current, \"keyup\", handleKeyup);\n fireSyntheticPointerEvent(\"down\", (event, info) => {\n this.startPress(event, info);\n });\n };\n const removeKeydownListener = addDomEvent(this.node.current, \"keydown\", handleKeydown);\n const handleBlur = () => {\n if (!this.isPressing)\n return;\n fireSyntheticPointerEvent(\"cancel\", (cancelEvent, cancelInfo) => this.cancelPress(cancelEvent, cancelInfo));\n };\n const removeBlurListener = addDomEvent(this.node.current, \"blur\", handleBlur);\n this.removeAccessibleListeners = pipe(removeKeydownListener, removeBlurListener);\n };\n }\n startPress(event, info) {\n this.isPressing = true;\n const { onTapStart, whileTap } = this.node.getProps();\n /**\n * Ensure we trigger animations before firing event callback\n */\n if (whileTap && this.node.animationState) {\n this.node.animationState.setActive(\"whileTap\", true);\n }\n if (onTapStart) {\n frame.update(() => onTapStart(event, info));\n }\n }\n checkPressEnd() {\n this.removeEndListeners();\n this.isPressing = false;\n const props = this.node.getProps();\n if (props.whileTap && this.node.animationState) {\n this.node.animationState.setActive(\"whileTap\", false);\n }\n return !isDragActive();\n }\n cancelPress(event, info) {\n if (!this.checkPressEnd())\n return;\n const { onTapCancel } = this.node.getProps();\n if (onTapCancel) {\n frame.update(() => onTapCancel(event, info));\n }\n }\n mount() {\n const props = this.node.getProps();\n const removePointerListener = addPointerEvent(props.globalTapTarget ? window : this.node.current, \"pointerdown\", this.startPointerPress, { passive: !(props.onTapStart || props[\"onPointerStart\"]) });\n const removeFocusListener = addDomEvent(this.node.current, \"focus\", this.startAccessiblePress);\n this.removeStartListeners = pipe(removePointerListener, removeFocusListener);\n }\n unmount() {\n this.removeStartListeners();\n this.removeEndListeners();\n this.removeAccessibleListeners();\n }\n}\n\nexport { PressGesture };\n","/**\n * Map an IntersectionHandler callback to an element. We only ever make one handler for one\n * element, so even though these handlers might all be triggered by different\n * observers, we can keep them in the same map.\n */\nconst observerCallbacks = new WeakMap();\n/**\n * Multiple observers can be created for multiple element/document roots. Each with\n * different settings. So here we store dictionaries of observers to each root,\n * using serialised settings (threshold/margin) as lookup keys.\n */\nconst observers = new WeakMap();\nconst fireObserverCallback = (entry) => {\n const callback = observerCallbacks.get(entry.target);\n callback && callback(entry);\n};\nconst fireAllObserverCallbacks = (entries) => {\n entries.forEach(fireObserverCallback);\n};\nfunction initIntersectionObserver({ root, ...options }) {\n const lookupRoot = root || document;\n /**\n * If we don't have an observer lookup map for this root, create one.\n */\n if (!observers.has(lookupRoot)) {\n observers.set(lookupRoot, {});\n }\n const rootObservers = observers.get(lookupRoot);\n const key = JSON.stringify(options);\n /**\n * If we don't have an observer for this combination of root and settings,\n * create one.\n */\n if (!rootObservers[key]) {\n rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options });\n }\n return rootObservers[key];\n}\nfunction observeIntersection(element, options, callback) {\n const rootInteresectionObserver = initIntersectionObserver(options);\n observerCallbacks.set(element, callback);\n rootInteresectionObserver.observe(element);\n return () => {\n observerCallbacks.delete(element);\n rootInteresectionObserver.unobserve(element);\n };\n}\n\nexport { observeIntersection };\n","import { Feature } from '../Feature.mjs';\nimport { observeIntersection } from './observers.mjs';\n\nconst thresholdNames = {\n some: 0,\n all: 1,\n};\nclass InViewFeature extends Feature {\n constructor() {\n super(...arguments);\n this.hasEnteredView = false;\n this.isInView = false;\n }\n startObserver() {\n this.unmount();\n const { viewport = {} } = this.node.getProps();\n const { root, margin: rootMargin, amount = \"some\", once } = viewport;\n const options = {\n root: root ? root.current : undefined,\n rootMargin,\n threshold: typeof amount === \"number\" ? amount : thresholdNames[amount],\n };\n const onIntersectionUpdate = (entry) => {\n const { isIntersecting } = entry;\n /**\n * If there's been no change in the viewport state, early return.\n */\n if (this.isInView === isIntersecting)\n return;\n this.isInView = isIntersecting;\n /**\n * Handle hasEnteredView. If this is only meant to run once, and\n * element isn't visible, early return. Otherwise set hasEnteredView to true.\n */\n if (once && !isIntersecting && this.hasEnteredView) {\n return;\n }\n else if (isIntersecting) {\n this.hasEnteredView = true;\n }\n if (this.node.animationState) {\n this.node.animationState.setActive(\"whileInView\", isIntersecting);\n }\n /**\n * Use the latest committed props rather than the ones in scope\n * when this observer is created\n */\n const { onViewportEnter, onViewportLeave } = this.node.getProps();\n const callback = isIntersecting ? onViewportEnter : onViewportLeave;\n callback && callback(entry);\n };\n return observeIntersection(this.node.current, options, onIntersectionUpdate);\n }\n mount() {\n this.startObserver();\n }\n update() {\n if (typeof IntersectionObserver === \"undefined\")\n return;\n const { props, prevProps } = this.node;\n const hasOptionsChanged = [\"amount\", \"margin\", \"root\"].some(hasViewportOptionChanged(props, prevProps));\n if (hasOptionsChanged) {\n this.startObserver();\n }\n }\n unmount() { }\n}\nfunction hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) {\n return (name) => viewport[name] !== prevViewport[name];\n}\n\nexport { InViewFeature };\n","import { HoverGesture } from '../../gestures/hover.mjs';\nimport { FocusGesture } from '../../gestures/focus.mjs';\nimport { PressGesture } from '../../gestures/press.mjs';\nimport { InViewFeature } from './viewport/index.mjs';\n\nconst gestureAnimations = {\n inView: {\n Feature: InViewFeature,\n },\n tap: {\n Feature: PressGesture,\n },\n focus: {\n Feature: FocusGesture,\n },\n hover: {\n Feature: HoverGesture,\n },\n};\n\nexport { gestureAnimations };\n","function shallowCompare(next, prev) {\n if (!Array.isArray(prev))\n return false;\n const prevLength = prev.length;\n if (prevLength !== next.length)\n return false;\n for (let i = 0; i < prevLength; i++) {\n if (prev[i] !== next[i])\n return false;\n }\n return true;\n}\n\nexport { shallowCompare };\n","import { resolveVariantFromProps } from './resolve-variants.mjs';\n\n/**\n * Creates an object containing the latest state of every MotionValue on a VisualElement\n */\nfunction getCurrent(visualElement) {\n const current = {};\n visualElement.values.forEach((value, key) => (current[key] = value.get()));\n return current;\n}\n/**\n * Creates an object containing the latest velocity of every MotionValue on a VisualElement\n */\nfunction getVelocity(visualElement) {\n const velocity = {};\n visualElement.values.forEach((value, key) => (velocity[key] = value.getVelocity()));\n return velocity;\n}\nfunction resolveVariant(visualElement, definition, custom) {\n const props = visualElement.getProps();\n return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, getCurrent(visualElement), getVelocity(visualElement));\n}\n\nexport { resolveVariant };\n","import { noop } from './noop.mjs';\n\nlet warning = noop;\nlet invariant = noop;\nif (process.env.NODE_ENV !== \"production\") {\n warning = (check, message) => {\n if (!check && typeof console !== \"undefined\") {\n console.warn(message);\n }\n };\n invariant = (check, message) => {\n if (!check) {\n throw new Error(message);\n }\n };\n}\n\nexport { invariant, warning };\n","/**\n * Converts seconds to milliseconds\n *\n * @param seconds - Time in seconds.\n * @return milliseconds - Converted time in milliseconds.\n */\nconst secondsToMilliseconds = (seconds) => seconds * 1000;\nconst millisecondsToSeconds = (milliseconds) => milliseconds / 1000;\n\nexport { millisecondsToSeconds, secondsToMilliseconds };\n","const instantAnimationState = {\n current: false,\n};\n\nexport { instantAnimationState };\n","const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === \"number\";\n\nexport { isBezierDefinition };\n","import { isBezierDefinition } from '../../../easing/utils/is-bezier-definition.mjs';\n\nfunction isWaapiSupportedEasing(easing) {\n return Boolean(!easing ||\n (typeof easing === \"string\" && supportedWaapiEasing[easing]) ||\n isBezierDefinition(easing) ||\n (Array.isArray(easing) && easing.every(isWaapiSupportedEasing)));\n}\nconst cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;\nconst supportedWaapiEasing = {\n linear: \"linear\",\n ease: \"ease\",\n easeIn: \"ease-in\",\n easeOut: \"ease-out\",\n easeInOut: \"ease-in-out\",\n circIn: cubicBezierAsString([0, 0.65, 0.55, 1]),\n circOut: cubicBezierAsString([0.55, 0, 1, 0.45]),\n backIn: cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),\n backOut: cubicBezierAsString([0.33, 1.53, 0.69, 0.99]),\n};\nfunction mapEasingToNativeEasing(easing) {\n if (!easing)\n return undefined;\n return isBezierDefinition(easing)\n ? cubicBezierAsString(easing)\n : Array.isArray(easing)\n ? easing.map(mapEasingToNativeEasing)\n : supportedWaapiEasing[easing];\n}\n\nexport { cubicBezierAsString, isWaapiSupportedEasing, mapEasingToNativeEasing, supportedWaapiEasing };\n","import { mapEasingToNativeEasing } from './easing.mjs';\n\nfunction animateStyle(element, valueName, keyframes, { delay = 0, duration, repeat = 0, repeatType = \"loop\", ease, times, } = {}) {\n const keyframeOptions = { [valueName]: keyframes };\n if (times)\n keyframeOptions.offset = times;\n const easing = mapEasingToNativeEasing(ease);\n /**\n * If this is an easing array, apply to keyframes, not animation as a whole\n */\n if (Array.isArray(easing))\n keyframeOptions.easing = easing;\n return element.animate(keyframeOptions, {\n delay,\n duration,\n easing: !Array.isArray(easing) ? easing : \"linear\",\n fill: \"both\",\n iterations: repeat + 1,\n direction: repeatType === \"reverse\" ? \"alternate\" : \"normal\",\n });\n}\n\nexport { animateStyle };\n","function getFinalKeyframe(keyframes, { repeat, repeatType = \"loop\" }) {\n const index = repeat && repeatType !== \"loop\" && repeat % 2 === 1\n ? 0\n : keyframes.length - 1;\n return keyframes[index];\n}\n\nexport { getFinalKeyframe };\n","import { noop } from '../utils/noop.mjs';\n\n/*\n Bezier function generator\n This has been modified from Gaëtan Renaudeau's BezierEasing\n https://github.com/gre/bezier-easing/blob/master/src/index.js\n https://github.com/gre/bezier-easing/blob/master/LICENSE\n \n I've removed the newtonRaphsonIterate algo because in benchmarking it\n wasn't noticiably faster than binarySubdivision, indeed removing it\n usually improved times, depending on the curve.\n I also removed the lookup table, as for the added bundle size and loop we're\n only cutting ~4 or so subdivision iterations. I bumped the max iterations up\n to 12 to compensate and this still tended to be faster for no perceivable\n loss in accuracy.\n Usage\n const easeOut = cubicBezier(.17,.67,.83,.67);\n const x = easeOut(0.5); // returns 0.627...\n*/\n// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.\nconst calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) *\n t;\nconst subdivisionPrecision = 0.0000001;\nconst subdivisionMaxIterations = 12;\nfunction binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {\n let currentX;\n let currentT;\n let i = 0;\n do {\n currentT = lowerBound + (upperBound - lowerBound) / 2.0;\n currentX = calcBezier(currentT, mX1, mX2) - x;\n if (currentX > 0.0) {\n upperBound = currentT;\n }\n else {\n lowerBound = currentT;\n }\n } while (Math.abs(currentX) > subdivisionPrecision &&\n ++i < subdivisionMaxIterations);\n return currentT;\n}\nfunction cubicBezier(mX1, mY1, mX2, mY2) {\n // If this is a linear gradient, return linear easing\n if (mX1 === mY1 && mX2 === mY2)\n return noop;\n const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);\n // If animation is at start/end, return t without easing\n return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);\n}\n\nexport { cubicBezier };\n","import { cubicBezier } from './cubic-bezier.mjs';\n\nconst easeIn = cubicBezier(0.42, 0, 1, 1);\nconst easeOut = cubicBezier(0, 0, 0.58, 1);\nconst easeInOut = cubicBezier(0.42, 0, 0.58, 1);\n\nexport { easeIn, easeInOut, easeOut };\n","const isEasingArray = (ease) => {\n return Array.isArray(ease) && typeof ease[0] !== \"number\";\n};\n\nexport { isEasingArray };\n","// Accepts an easing function and returns a new one that outputs mirrored values for\n// the second half of the animation. Turns easeIn into easeInOut.\nconst mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;\n\nexport { mirrorEasing };\n","// Accepts an easing function and returns a new one that outputs reversed values.\n// Turns easeIn into easeOut.\nconst reverseEasing = (easing) => (p) => 1 - easing(1 - p);\n\nexport { reverseEasing };\n","import { mirrorEasing } from './modifiers/mirror.mjs';\nimport { reverseEasing } from './modifiers/reverse.mjs';\n\nconst circIn = (p) => 1 - Math.sin(Math.acos(p));\nconst circOut = reverseEasing(circIn);\nconst circInOut = mirrorEasing(circIn);\n\nexport { circIn, circInOut, circOut };\n","import { cubicBezier } from './cubic-bezier.mjs';\nimport { mirrorEasing } from './modifiers/mirror.mjs';\nimport { reverseEasing } from './modifiers/reverse.mjs';\n\nconst backOut = cubicBezier(0.33, 1.53, 0.69, 0.99);\nconst backIn = reverseEasing(backOut);\nconst backInOut = mirrorEasing(backIn);\n\nexport { backIn, backInOut, backOut };\n","import { backIn } from './back.mjs';\n\nconst anticipate = (p) => (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));\n\nexport { anticipate };\n","import { invariant } from '../../utils/errors.mjs';\nimport { cubicBezier } from '../cubic-bezier.mjs';\nimport { noop } from '../../utils/noop.mjs';\nimport { easeIn, easeInOut, easeOut } from '../ease.mjs';\nimport { circIn, circInOut, circOut } from '../circ.mjs';\nimport { backIn, backInOut, backOut } from '../back.mjs';\nimport { anticipate } from '../anticipate.mjs';\n\nconst easingLookup = {\n linear: noop,\n easeIn,\n easeInOut,\n easeOut,\n circIn,\n circInOut,\n circOut,\n backIn,\n backInOut,\n backOut,\n anticipate,\n};\nconst easingDefinitionToFunction = (definition) => {\n if (Array.isArray(definition)) {\n // If cubic bezier definition, create bezier curve\n invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`);\n const [x1, y1, x2, y2] = definition;\n return cubicBezier(x1, y1, x2, y2);\n }\n else if (typeof definition === \"string\") {\n // Else lookup from table\n invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`);\n return easingLookup[definition];\n }\n return definition;\n};\n\nexport { easingDefinitionToFunction };\n","import { isString, singleColorRegex, floatRegex } from '../utils.mjs';\n\n/**\n * Returns true if the provided string is a color, ie rgba(0,0,0,0) or #000,\n * but false if a number or multiple colors\n */\nconst isColorString = (type, testProp) => (v) => {\n return Boolean((isString(v) && singleColorRegex.test(v) && v.startsWith(type)) ||\n (testProp && Object.prototype.hasOwnProperty.call(v, testProp)));\n};\nconst splitColor = (aName, bName, cName) => (v) => {\n if (!isString(v))\n return v;\n const [a, b, c, alpha] = v.match(floatRegex);\n return {\n [aName]: parseFloat(a),\n [bName]: parseFloat(b),\n [cName]: parseFloat(c),\n alpha: alpha !== undefined ? parseFloat(alpha) : 1,\n };\n};\n\nexport { isColorString, splitColor };\n","import { clamp } from '../../../utils/clamp.mjs';\nimport { number, alpha } from '../numbers/index.mjs';\nimport { sanitize } from '../utils.mjs';\nimport { isColorString, splitColor } from './utils.mjs';\n\nconst clampRgbUnit = (v) => clamp(0, 255, v);\nconst rgbUnit = {\n ...number,\n transform: (v) => Math.round(clampRgbUnit(v)),\n};\nconst rgba = {\n test: isColorString(\"rgb\", \"red\"),\n parse: splitColor(\"red\", \"green\", \"blue\"),\n transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => \"rgba(\" +\n rgbUnit.transform(red) +\n \", \" +\n rgbUnit.transform(green) +\n \", \" +\n rgbUnit.transform(blue) +\n \", \" +\n sanitize(alpha.transform(alpha$1)) +\n \")\",\n};\n\nexport { rgbUnit, rgba };\n","import { rgba } from './rgba.mjs';\nimport { isColorString } from './utils.mjs';\n\nfunction parseHex(v) {\n let r = \"\";\n let g = \"\";\n let b = \"\";\n let a = \"\";\n // If we have 6 characters, ie #FF0000\n if (v.length > 5) {\n r = v.substring(1, 3);\n g = v.substring(3, 5);\n b = v.substring(5, 7);\n a = v.substring(7, 9);\n // Or we have 3 characters, ie #F00\n }\n else {\n r = v.substring(1, 2);\n g = v.substring(2, 3);\n b = v.substring(3, 4);\n a = v.substring(4, 5);\n r += r;\n g += g;\n b += b;\n a += a;\n }\n return {\n red: parseInt(r, 16),\n green: parseInt(g, 16),\n blue: parseInt(b, 16),\n alpha: a ? parseInt(a, 16) / 255 : 1,\n };\n}\nconst hex = {\n test: isColorString(\"#\"),\n parse: parseHex,\n transform: rgba.transform,\n};\n\nexport { hex };\n","import { alpha } from '../numbers/index.mjs';\nimport { percent } from '../numbers/units.mjs';\nimport { sanitize } from '../utils.mjs';\nimport { isColorString, splitColor } from './utils.mjs';\n\nconst hsla = {\n test: isColorString(\"hsl\", \"hue\"),\n parse: splitColor(\"hue\", \"saturation\", \"lightness\"),\n transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {\n return (\"hsla(\" +\n Math.round(hue) +\n \", \" +\n percent.transform(sanitize(saturation)) +\n \", \" +\n percent.transform(sanitize(lightness)) +\n \", \" +\n sanitize(alpha.transform(alpha$1)) +\n \")\");\n },\n};\n\nexport { hsla };\n","import { isString } from '../utils.mjs';\nimport { hex } from './hex.mjs';\nimport { hsla } from './hsla.mjs';\nimport { rgba } from './rgba.mjs';\n\nconst color = {\n test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),\n parse: (v) => {\n if (rgba.test(v)) {\n return rgba.parse(v);\n }\n else if (hsla.test(v)) {\n return hsla.parse(v);\n }\n else {\n return hex.parse(v);\n }\n },\n transform: (v) => {\n return isString(v)\n ? v\n : v.hasOwnProperty(\"red\")\n ? rgba.transform(v)\n : hsla.transform(v);\n },\n};\n\nexport { color };\n","/*\n Value in range from progress\n\n Given a lower limit and an upper limit, we return the value within\n that range as expressed by progress (usually a number from 0 to 1)\n\n So progress = 0.5 would change\n\n from -------- to\n\n to\n\n from ---- to\n\n E.g. from = 10, to = 20, progress = 0.5 => 15\n\n @param [number]: Lower limit of range\n @param [number]: Upper limit of range\n @param [number]: The progress between lower and upper limits expressed 0-1\n @return [number]: Value as calculated from progress within range (not limited within range)\n*/\nconst mix = (from, to, progress) => -progress * from + progress * to + from;\n\nexport { mix };\n","// Adapted from https://gist.github.com/mjackson/5311256\nfunction hueToRgb(p, q, t) {\n if (t < 0)\n t += 1;\n if (t > 1)\n t -= 1;\n if (t < 1 / 6)\n return p + (q - p) * 6 * t;\n if (t < 1 / 2)\n return q;\n if (t < 2 / 3)\n return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n}\nfunction hslaToRgba({ hue, saturation, lightness, alpha }) {\n hue /= 360;\n saturation /= 100;\n lightness /= 100;\n let red = 0;\n let green = 0;\n let blue = 0;\n if (!saturation) {\n red = green = blue = lightness;\n }\n else {\n const q = lightness < 0.5\n ? lightness * (1 + saturation)\n : lightness + saturation - lightness * saturation;\n const p = 2 * lightness - q;\n red = hueToRgb(p, q, hue + 1 / 3);\n green = hueToRgb(p, q, hue);\n blue = hueToRgb(p, q, hue - 1 / 3);\n }\n return {\n red: Math.round(red * 255),\n green: Math.round(green * 255),\n blue: Math.round(blue * 255),\n alpha,\n };\n}\n\nexport { hslaToRgba };\n","import { mix } from './mix.mjs';\nimport { invariant } from './errors.mjs';\nimport { hslaToRgba } from './hsla-to-rgba.mjs';\nimport { hex } from '../value/types/color/hex.mjs';\nimport { rgba } from '../value/types/color/rgba.mjs';\nimport { hsla } from '../value/types/color/hsla.mjs';\n\n// Linear color space blending\n// Explained https://www.youtube.com/watch?v=LKnqECcg6Gw\n// Demonstrated http://codepen.io/osublake/pen/xGVVaN\nconst mixLinearColor = (from, to, v) => {\n const fromExpo = from * from;\n return Math.sqrt(Math.max(0, v * (to * to - fromExpo) + fromExpo));\n};\nconst colorTypes = [hex, rgba, hsla];\nconst getColorType = (v) => colorTypes.find((type) => type.test(v));\nfunction asRGBA(color) {\n const type = getColorType(color);\n invariant(Boolean(type), `'${color}' is not an animatable color. Use the equivalent color code instead.`);\n let model = type.parse(color);\n if (type === hsla) {\n // TODO Remove this cast - needed since Framer Motion's stricter typing\n model = hslaToRgba(model);\n }\n return model;\n}\nconst mixColor = (from, to) => {\n const fromRGBA = asRGBA(from);\n const toRGBA = asRGBA(to);\n const blended = { ...fromRGBA };\n return (v) => {\n blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v);\n blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v);\n blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v);\n blended.alpha = mix(fromRGBA.alpha, toRGBA.alpha, v);\n return rgba.transform(blended);\n };\n};\n\nexport { mixColor, mixLinearColor };\n","import { cssVariableRegex } from '../../../render/dom/utils/is-css-variable.mjs';\nimport { noop } from '../../../utils/noop.mjs';\nimport { color } from '../color/index.mjs';\nimport { number } from '../numbers/index.mjs';\nimport { colorRegex, floatRegex, isString, sanitize } from '../utils.mjs';\n\nfunction test(v) {\n var _a, _b;\n return (isNaN(v) &&\n isString(v) &&\n (((_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) || 0) +\n (((_b = v.match(colorRegex)) === null || _b === void 0 ? void 0 : _b.length) || 0) >\n 0);\n}\nconst cssVarTokeniser = {\n regex: cssVariableRegex,\n countKey: \"Vars\",\n token: \"${v}\",\n parse: noop,\n};\nconst colorTokeniser = {\n regex: colorRegex,\n countKey: \"Colors\",\n token: \"${c}\",\n parse: color.parse,\n};\nconst numberTokeniser = {\n regex: floatRegex,\n countKey: \"Numbers\",\n token: \"${n}\",\n parse: number.parse,\n};\nfunction tokenise(info, { regex, countKey, token, parse }) {\n const matches = info.tokenised.match(regex);\n if (!matches)\n return;\n info[\"num\" + countKey] = matches.length;\n info.tokenised = info.tokenised.replace(regex, token);\n info.values.push(...matches.map(parse));\n}\nfunction analyseComplexValue(value) {\n const originalValue = value.toString();\n const info = {\n value: originalValue,\n tokenised: originalValue,\n values: [],\n numVars: 0,\n numColors: 0,\n numNumbers: 0,\n };\n if (info.value.includes(\"var(--\"))\n tokenise(info, cssVarTokeniser);\n tokenise(info, colorTokeniser);\n tokenise(info, numberTokeniser);\n return info;\n}\nfunction parseComplexValue(v) {\n return analyseComplexValue(v).values;\n}\nfunction createTransformer(source) {\n const { values, numColors, numVars, tokenised } = analyseComplexValue(source);\n const numValues = values.length;\n return (v) => {\n let output = tokenised;\n for (let i = 0; i < numValues; i++) {\n if (i < numVars) {\n output = output.replace(cssVarTokeniser.token, v[i]);\n }\n else if (i < numVars + numColors) {\n output = output.replace(colorTokeniser.token, color.transform(v[i]));\n }\n else {\n output = output.replace(numberTokeniser.token, sanitize(v[i]));\n }\n }\n return output;\n };\n}\nconst convertNumbersToZero = (v) => typeof v === \"number\" ? 0 : v;\nfunction getAnimatableNone(v) {\n const parsed = parseComplexValue(v);\n const transformer = createTransformer(v);\n return transformer(parsed.map(convertNumbersToZero));\n}\nconst complex = {\n test,\n parse: parseComplexValue,\n createTransformer,\n getAnimatableNone,\n};\n\nexport { analyseComplexValue, complex };\n","import { mix } from './mix.mjs';\nimport { mixColor } from './mix-color.mjs';\nimport { pipe } from './pipe.mjs';\nimport { warning } from './errors.mjs';\nimport { color } from '../value/types/color/index.mjs';\nimport { complex, analyseComplexValue } from '../value/types/complex/index.mjs';\n\nconst mixImmediate = (origin, target) => (p) => `${p > 0 ? target : origin}`;\nfunction getMixer(origin, target) {\n if (typeof origin === \"number\") {\n return (v) => mix(origin, target, v);\n }\n else if (color.test(origin)) {\n return mixColor(origin, target);\n }\n else {\n return origin.startsWith(\"var(\")\n ? mixImmediate(origin, target)\n : mixComplex(origin, target);\n }\n}\nconst mixArray = (from, to) => {\n const output = [...from];\n const numValues = output.length;\n const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i]));\n return (v) => {\n for (let i = 0; i < numValues; i++) {\n output[i] = blendValue[i](v);\n }\n return output;\n };\n};\nconst mixObject = (origin, target) => {\n const output = { ...origin, ...target };\n const blendValue = {};\n for (const key in output) {\n if (origin[key] !== undefined && target[key] !== undefined) {\n blendValue[key] = getMixer(origin[key], target[key]);\n }\n }\n return (v) => {\n for (const key in blendValue) {\n output[key] = blendValue[key](v);\n }\n return output;\n };\n};\nconst mixComplex = (origin, target) => {\n const template = complex.createTransformer(target);\n const originStats = analyseComplexValue(origin);\n const targetStats = analyseComplexValue(target);\n const canInterpolate = originStats.numVars === targetStats.numVars &&\n originStats.numColors === targetStats.numColors &&\n originStats.numNumbers >= targetStats.numNumbers;\n if (canInterpolate) {\n return pipe(mixArray(originStats.values, targetStats.values), template);\n }\n else {\n warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`);\n return mixImmediate(origin, target);\n }\n};\n\nexport { mixArray, mixComplex, mixObject };\n","/*\n Progress within given range\n\n Given a lower limit and an upper limit, we return the progress\n (expressed as a number 0-1) represented by the given value, and\n limit that progress to within 0-1.\n\n @param [number]: Lower limit\n @param [number]: Upper limit\n @param [number]: Value to find progress within given range\n @return [number]: Progress of value within range as expressed 0-1\n*/\nconst progress = (from, to, value) => {\n const toFromDifference = to - from;\n return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;\n};\n\nexport { progress };\n","import { invariant } from './errors.mjs';\nimport { color } from '../value/types/color/index.mjs';\nimport { clamp } from './clamp.mjs';\nimport { mix } from './mix.mjs';\nimport { mixColor } from './mix-color.mjs';\nimport { mixComplex, mixArray, mixObject } from './mix-complex.mjs';\nimport { pipe } from './pipe.mjs';\nimport { progress } from './progress.mjs';\nimport { noop } from './noop.mjs';\n\nconst mixNumber = (from, to) => (p) => mix(from, to, p);\nfunction detectMixerFactory(v) {\n if (typeof v === \"number\") {\n return mixNumber;\n }\n else if (typeof v === \"string\") {\n return color.test(v) ? mixColor : mixComplex;\n }\n else if (Array.isArray(v)) {\n return mixArray;\n }\n else if (typeof v === \"object\") {\n return mixObject;\n }\n return mixNumber;\n}\nfunction createMixers(output, ease, customMixer) {\n const mixers = [];\n const mixerFactory = customMixer || detectMixerFactory(output[0]);\n const numMixers = output.length - 1;\n for (let i = 0; i < numMixers; i++) {\n let mixer = mixerFactory(output[i], output[i + 1]);\n if (ease) {\n const easingFunction = Array.isArray(ease) ? ease[i] || noop : ease;\n mixer = pipe(easingFunction, mixer);\n }\n mixers.push(mixer);\n }\n return mixers;\n}\n/**\n * Create a function that maps from a numerical input array to a generic output array.\n *\n * Accepts:\n * - Numbers\n * - Colors (hex, hsl, hsla, rgb, rgba)\n * - Complex (combinations of one or more numbers or strings)\n *\n * ```jsx\n * const mixColor = interpolate([0, 1], ['#fff', '#000'])\n *\n * mixColor(0.5) // 'rgba(128, 128, 128, 1)'\n * ```\n *\n * TODO Revist this approach once we've moved to data models for values,\n * probably not needed to pregenerate mixer functions.\n *\n * @public\n */\nfunction interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {\n const inputLength = input.length;\n invariant(inputLength === output.length, \"Both input and output ranges must be the same length\");\n /**\n * If we're only provided a single input, we can just make a function\n * that returns the output.\n */\n if (inputLength === 1)\n return () => output[0];\n // If input runs highest -> lowest, reverse both arrays\n if (input[0] > input[inputLength - 1]) {\n input = [...input].reverse();\n output = [...output].reverse();\n }\n const mixers = createMixers(output, ease, mixer);\n const numMixers = mixers.length;\n const interpolator = (v) => {\n let i = 0;\n if (numMixers > 1) {\n for (; i < input.length - 2; i++) {\n if (v < input[i + 1])\n break;\n }\n }\n const progressInRange = progress(input[i], input[i + 1], v);\n return mixers[i](progressInRange);\n };\n return isClamp\n ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v))\n : interpolator;\n}\n\nexport { interpolate };\n","import { mix } from '../mix.mjs';\nimport { progress } from '../progress.mjs';\n\nfunction fillOffset(offset, remaining) {\n const min = offset[offset.length - 1];\n for (let i = 1; i <= remaining; i++) {\n const offsetProgress = progress(0, remaining, i);\n offset.push(mix(min, 1, offsetProgress));\n }\n}\n\nexport { fillOffset };\n","import { fillOffset } from './fill.mjs';\n\nfunction defaultOffset(arr) {\n const offset = [0];\n fillOffset(offset, arr.length - 1);\n return offset;\n}\n\nexport { defaultOffset };\n","function convertOffsetToTimes(offset, duration) {\n return offset.map((o) => o * duration);\n}\n\nexport { convertOffsetToTimes };\n","import { easeInOut } from '../../easing/ease.mjs';\nimport { isEasingArray } from '../../easing/utils/is-easing-array.mjs';\nimport { easingDefinitionToFunction } from '../../easing/utils/map.mjs';\nimport { interpolate } from '../../utils/interpolate.mjs';\nimport { defaultOffset } from '../../utils/offsets/default.mjs';\nimport { convertOffsetToTimes } from '../../utils/offsets/time.mjs';\n\nfunction defaultEasing(values, easing) {\n return values.map(() => easing || easeInOut).splice(0, values.length - 1);\n}\nfunction keyframes({ duration = 300, keyframes: keyframeValues, times, ease = \"easeInOut\", }) {\n /**\n * Easing functions can be externally defined as strings. Here we convert them\n * into actual functions.\n */\n const easingFunctions = isEasingArray(ease)\n ? ease.map(easingDefinitionToFunction)\n : easingDefinitionToFunction(ease);\n /**\n * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator\n * to reduce GC during animation.\n */\n const state = {\n done: false,\n value: keyframeValues[0],\n };\n /**\n * Create a times array based on the provided 0-1 offsets\n */\n const absoluteTimes = convertOffsetToTimes(\n // Only use the provided offsets if they're the correct length\n // TODO Maybe we should warn here if there's a length mismatch\n times && times.length === keyframeValues.length\n ? times\n : defaultOffset(keyframeValues), duration);\n const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {\n ease: Array.isArray(easingFunctions)\n ? easingFunctions\n : defaultEasing(keyframeValues, easingFunctions),\n });\n return {\n calculatedDuration: duration,\n next: (t) => {\n state.value = mapTimeToKeyframe(t);\n state.done = t >= duration;\n return state;\n },\n };\n}\n\nexport { defaultEasing, keyframes };\n","/*\n Convert velocity into velocity per second\n\n @param [number]: Unit per frame\n @param [number]: Frame duration in ms\n*/\nfunction velocityPerSecond(velocity, frameDuration) {\n return frameDuration ? velocity * (1000 / frameDuration) : 0;\n}\n\nexport { velocityPerSecond };\n","import { velocityPerSecond } from '../../../utils/velocity-per-second.mjs';\n\nconst velocitySampleDuration = 5; // ms\nfunction calcGeneratorVelocity(resolveValue, t, current) {\n const prevT = Math.max(t - velocitySampleDuration, 0);\n return velocityPerSecond(current - resolveValue(prevT), t - prevT);\n}\n\nexport { calcGeneratorVelocity };\n","import { warning } from '../../../utils/errors.mjs';\nimport { clamp } from '../../../utils/clamp.mjs';\nimport { secondsToMilliseconds, millisecondsToSeconds } from '../../../utils/time-conversion.mjs';\n\nconst safeMin = 0.001;\nconst minDuration = 0.01;\nconst maxDuration = 10.0;\nconst minDamping = 0.05;\nconst maxDamping = 1;\nfunction findSpring({ duration = 800, bounce = 0.25, velocity = 0, mass = 1, }) {\n let envelope;\n let derivative;\n warning(duration <= secondsToMilliseconds(maxDuration), \"Spring duration must be 10 seconds or less\");\n let dampingRatio = 1 - bounce;\n /**\n * Restrict dampingRatio and duration to within acceptable ranges.\n */\n dampingRatio = clamp(minDamping, maxDamping, dampingRatio);\n duration = clamp(minDuration, maxDuration, millisecondsToSeconds(duration));\n if (dampingRatio < 1) {\n /**\n * Underdamped spring\n */\n envelope = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const a = exponentialDecay - velocity;\n const b = calcAngularFreq(undampedFreq, dampingRatio);\n const c = Math.exp(-delta);\n return safeMin - (a / b) * c;\n };\n derivative = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const d = delta * velocity + velocity;\n const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;\n const f = Math.exp(-delta);\n const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);\n const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;\n return (factor * ((d - e) * f)) / g;\n };\n }\n else {\n /**\n * Critically-damped spring\n */\n envelope = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = (undampedFreq - velocity) * duration + 1;\n return -safeMin + a * b;\n };\n derivative = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = (velocity - undampedFreq) * (duration * duration);\n return a * b;\n };\n }\n const initialGuess = 5 / duration;\n const undampedFreq = approximateRoot(envelope, derivative, initialGuess);\n duration = secondsToMilliseconds(duration);\n if (isNaN(undampedFreq)) {\n return {\n stiffness: 100,\n damping: 10,\n duration,\n };\n }\n else {\n const stiffness = Math.pow(undampedFreq, 2) * mass;\n return {\n stiffness,\n damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),\n duration,\n };\n }\n}\nconst rootIterations = 12;\nfunction approximateRoot(envelope, derivative, initialGuess) {\n let result = initialGuess;\n for (let i = 1; i < rootIterations; i++) {\n result = result - envelope(result) / derivative(result);\n }\n return result;\n}\nfunction calcAngularFreq(undampedFreq, dampingRatio) {\n return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);\n}\n\nexport { calcAngularFreq, findSpring, maxDamping, maxDuration, minDamping, minDuration };\n","import { millisecondsToSeconds } from '../../../utils/time-conversion.mjs';\nimport { calcGeneratorVelocity } from '../utils/velocity.mjs';\nimport { findSpring, calcAngularFreq } from './find.mjs';\n\nconst durationKeys = [\"duration\", \"bounce\"];\nconst physicsKeys = [\"stiffness\", \"damping\", \"mass\"];\nfunction isSpringType(options, keys) {\n return keys.some((key) => options[key] !== undefined);\n}\nfunction getSpringOptions(options) {\n let springOptions = {\n velocity: 0.0,\n stiffness: 100,\n damping: 10,\n mass: 1.0,\n isResolvedFromDuration: false,\n ...options,\n };\n // stiffness/damping/mass overrides duration/bounce\n if (!isSpringType(options, physicsKeys) &&\n isSpringType(options, durationKeys)) {\n const derived = findSpring(options);\n springOptions = {\n ...springOptions,\n ...derived,\n mass: 1.0,\n };\n springOptions.isResolvedFromDuration = true;\n }\n return springOptions;\n}\nfunction spring({ keyframes, restDelta, restSpeed, ...options }) {\n const origin = keyframes[0];\n const target = keyframes[keyframes.length - 1];\n /**\n * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator\n * to reduce GC during animation.\n */\n const state = { done: false, value: origin };\n const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration, } = getSpringOptions({\n ...options,\n velocity: -millisecondsToSeconds(options.velocity || 0),\n });\n const initialVelocity = velocity || 0.0;\n const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));\n const initialDelta = target - origin;\n const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass));\n /**\n * If we're working on a granular scale, use smaller defaults for determining\n * when the spring is finished.\n *\n * These defaults have been selected emprically based on what strikes a good\n * ratio between feeling good and finishing as soon as changes are imperceptible.\n */\n const isGranularScale = Math.abs(initialDelta) < 5;\n restSpeed || (restSpeed = isGranularScale ? 0.01 : 2);\n restDelta || (restDelta = isGranularScale ? 0.005 : 0.5);\n let resolveSpring;\n if (dampingRatio < 1) {\n const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);\n // Underdamped spring\n resolveSpring = (t) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);\n return (target -\n envelope *\n (((initialVelocity +\n dampingRatio * undampedAngularFreq * initialDelta) /\n angularFreq) *\n Math.sin(angularFreq * t) +\n initialDelta * Math.cos(angularFreq * t)));\n };\n }\n else if (dampingRatio === 1) {\n // Critically damped spring\n resolveSpring = (t) => target -\n Math.exp(-undampedAngularFreq * t) *\n (initialDelta +\n (initialVelocity + undampedAngularFreq * initialDelta) * t);\n }\n else {\n // Overdamped spring\n const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);\n resolveSpring = (t) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);\n // When performing sinh or cosh values can hit Infinity so we cap them here\n const freqForT = Math.min(dampedAngularFreq * t, 300);\n return (target -\n (envelope *\n ((initialVelocity +\n dampingRatio * undampedAngularFreq * initialDelta) *\n Math.sinh(freqForT) +\n dampedAngularFreq *\n initialDelta *\n Math.cosh(freqForT))) /\n dampedAngularFreq);\n };\n }\n return {\n calculatedDuration: isResolvedFromDuration ? duration || null : null,\n next: (t) => {\n const current = resolveSpring(t);\n if (!isResolvedFromDuration) {\n let currentVelocity = initialVelocity;\n if (t !== 0) {\n /**\n * We only need to calculate velocity for under-damped springs\n * as over- and critically-damped springs can't overshoot, so\n * checking only for displacement is enough.\n */\n if (dampingRatio < 1) {\n currentVelocity = calcGeneratorVelocity(resolveSpring, t, current);\n }\n else {\n currentVelocity = 0;\n }\n }\n const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;\n const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta;\n state.done =\n isBelowVelocityThreshold && isBelowDisplacementThreshold;\n }\n else {\n state.done = t >= duration;\n }\n state.value = state.done ? target : current;\n return state;\n },\n };\n}\n\nexport { spring };\n","import { spring } from './spring/index.mjs';\nimport { calcGeneratorVelocity } from './utils/velocity.mjs';\n\nfunction inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {\n const origin = keyframes[0];\n const state = {\n done: false,\n value: origin,\n };\n const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);\n const nearestBoundary = (v) => {\n if (min === undefined)\n return max;\n if (max === undefined)\n return min;\n return Math.abs(min - v) < Math.abs(max - v) ? min : max;\n };\n let amplitude = power * velocity;\n const ideal = origin + amplitude;\n const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);\n /**\n * If the target has changed we need to re-calculate the amplitude, otherwise\n * the animation will start from the wrong position.\n */\n if (target !== ideal)\n amplitude = target - origin;\n const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);\n const calcLatest = (t) => target + calcDelta(t);\n const applyFriction = (t) => {\n const delta = calcDelta(t);\n const latest = calcLatest(t);\n state.done = Math.abs(delta) <= restDelta;\n state.value = state.done ? target : latest;\n };\n /**\n * Ideally this would resolve for t in a stateless way, we could\n * do that by always precalculating the animation but as we know\n * this will be done anyway we can assume that spring will\n * be discovered during that.\n */\n let timeReachedBoundary;\n let spring$1;\n const checkCatchBoundary = (t) => {\n if (!isOutOfBounds(state.value))\n return;\n timeReachedBoundary = t;\n spring$1 = spring({\n keyframes: [state.value, nearestBoundary(state.value)],\n velocity: calcGeneratorVelocity(calcLatest, t, state.value),\n damping: bounceDamping,\n stiffness: bounceStiffness,\n restDelta,\n restSpeed,\n });\n };\n checkCatchBoundary(0);\n return {\n calculatedDuration: null,\n next: (t) => {\n /**\n * We need to resolve the friction to figure out if we need a\n * spring but we don't want to do this twice per frame. So here\n * we flag if we updated for this frame and later if we did\n * we can skip doing it again.\n */\n let hasUpdatedFrame = false;\n if (!spring$1 && timeReachedBoundary === undefined) {\n hasUpdatedFrame = true;\n applyFriction(t);\n checkCatchBoundary(t);\n }\n /**\n * If we have a spring and the provided t is beyond the moment the friction\n * animation crossed the min/max boundary, use the spring.\n */\n if (timeReachedBoundary !== undefined && t > timeReachedBoundary) {\n return spring$1.next(t - timeReachedBoundary);\n }\n else {\n !hasUpdatedFrame && applyFriction(t);\n return state;\n }\n },\n };\n}\n\nexport { inertia };\n","import { frame, cancelFrame, frameData } from '../../../frameloop/frame.mjs';\n\nconst frameloopDriver = (update) => {\n const passTimestamp = ({ timestamp }) => update(timestamp);\n return {\n start: () => frame.update(passTimestamp, true),\n stop: () => cancelFrame(passTimestamp),\n /**\n * If we're processing this frame we can use the\n * framelocked timestamp to keep things in sync.\n */\n now: () => frameData.isProcessing ? frameData.timestamp : performance.now(),\n };\n};\n\nexport { frameloopDriver };\n","/**\n * Implement a practical max duration for keyframe generation\n * to prevent infinite loops\n */\nconst maxGeneratorDuration = 20000;\nfunction calcGeneratorDuration(generator) {\n let duration = 0;\n const timeStep = 50;\n let state = generator.next(duration);\n while (!state.done && duration < maxGeneratorDuration) {\n duration += timeStep;\n state = generator.next(duration);\n }\n return duration >= maxGeneratorDuration ? Infinity : duration;\n}\n\nexport { calcGeneratorDuration, maxGeneratorDuration };\n","import { keyframes } from '../../generators/keyframes.mjs';\nimport { spring } from '../../generators/spring/index.mjs';\nimport { inertia } from '../../generators/inertia.mjs';\nimport { frameloopDriver } from './driver-frameloop.mjs';\nimport { interpolate } from '../../../utils/interpolate.mjs';\nimport { clamp } from '../../../utils/clamp.mjs';\nimport { millisecondsToSeconds, secondsToMilliseconds } from '../../../utils/time-conversion.mjs';\nimport { calcGeneratorDuration } from '../../generators/utils/calc-duration.mjs';\nimport { invariant } from '../../../utils/errors.mjs';\n\nconst types = {\n decay: inertia,\n inertia,\n tween: keyframes,\n keyframes: keyframes,\n spring,\n};\n/**\n * Animate a single value on the main thread.\n *\n * This function is written, where functionality overlaps,\n * to be largely spec-compliant with WAAPI to allow fungibility\n * between the two.\n */\nfunction animateValue({ autoplay = true, delay = 0, driver = frameloopDriver, keyframes: keyframes$1, type = \"keyframes\", repeat = 0, repeatDelay = 0, repeatType = \"loop\", onPlay, onStop, onComplete, onUpdate, ...options }) {\n let speed = 1;\n let hasStopped = false;\n let resolveFinishedPromise;\n let currentFinishedPromise;\n /**\n * Resolve the current Promise every time we enter the\n * finished state. This is WAAPI-compatible behaviour.\n */\n const updateFinishedPromise = () => {\n currentFinishedPromise = new Promise((resolve) => {\n resolveFinishedPromise = resolve;\n });\n };\n // Create the first finished promise\n updateFinishedPromise();\n let animationDriver;\n const generatorFactory = types[type] || keyframes;\n /**\n * If this isn't the keyframes generator and we've been provided\n * strings as keyframes, we need to interpolate these.\n */\n let mapNumbersToKeyframes;\n if (generatorFactory !== keyframes &&\n typeof keyframes$1[0] !== \"number\") {\n if (process.env.NODE_ENV !== \"production\") {\n invariant(keyframes$1.length === 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`);\n }\n mapNumbersToKeyframes = interpolate([0, 100], keyframes$1, {\n clamp: false,\n });\n keyframes$1 = [0, 100];\n }\n const generator = generatorFactory({ ...options, keyframes: keyframes$1 });\n let mirroredGenerator;\n if (repeatType === \"mirror\") {\n mirroredGenerator = generatorFactory({\n ...options,\n keyframes: [...keyframes$1].reverse(),\n velocity: -(options.velocity || 0),\n });\n }\n let playState = \"idle\";\n let holdTime = null;\n let startTime = null;\n let cancelTime = null;\n /**\n * If duration is undefined and we have repeat options,\n * we need to calculate a duration from the generator.\n *\n * We set it to the generator itself to cache the duration.\n * Any timeline resolver will need to have already precalculated\n * the duration by this step.\n */\n if (generator.calculatedDuration === null && repeat) {\n generator.calculatedDuration = calcGeneratorDuration(generator);\n }\n const { calculatedDuration } = generator;\n let resolvedDuration = Infinity;\n let totalDuration = Infinity;\n if (calculatedDuration !== null) {\n resolvedDuration = calculatedDuration + repeatDelay;\n totalDuration = resolvedDuration * (repeat + 1) - repeatDelay;\n }\n let currentTime = 0;\n const tick = (timestamp) => {\n if (startTime === null)\n return;\n /**\n * requestAnimationFrame timestamps can come through as lower than\n * the startTime as set by performance.now(). Here we prevent this,\n * though in the future it could be possible to make setting startTime\n * a pending operation that gets resolved here.\n */\n if (speed > 0)\n startTime = Math.min(startTime, timestamp);\n if (speed < 0)\n startTime = Math.min(timestamp - totalDuration / speed, startTime);\n if (holdTime !== null) {\n currentTime = holdTime;\n }\n else {\n // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =\n // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for\n // example.\n currentTime = Math.round(timestamp - startTime) * speed;\n }\n // Rebase on delay\n const timeWithoutDelay = currentTime - delay * (speed >= 0 ? 1 : -1);\n const isInDelayPhase = speed >= 0 ? timeWithoutDelay < 0 : timeWithoutDelay > totalDuration;\n currentTime = Math.max(timeWithoutDelay, 0);\n /**\n * If this animation has finished, set the current time\n * to the total duration.\n */\n if (playState === \"finished\" && holdTime === null) {\n currentTime = totalDuration;\n }\n let elapsed = currentTime;\n let frameGenerator = generator;\n if (repeat) {\n /**\n * Get the current progress (0-1) of the animation. If t is >\n * than duration we'll get values like 2.5 (midway through the\n * third iteration)\n */\n const progress = Math.min(currentTime, totalDuration) / resolvedDuration;\n /**\n * Get the current iteration (0 indexed). For instance the floor of\n * 2.5 is 2.\n */\n let currentIteration = Math.floor(progress);\n /**\n * Get the current progress of the iteration by taking the remainder\n * so 2.5 is 0.5 through iteration 2\n */\n let iterationProgress = progress % 1.0;\n /**\n * If iteration progress is 1 we count that as the end\n * of the previous iteration.\n */\n if (!iterationProgress && progress >= 1) {\n iterationProgress = 1;\n }\n iterationProgress === 1 && currentIteration--;\n currentIteration = Math.min(currentIteration, repeat + 1);\n /**\n * Reverse progress if we're not running in \"normal\" direction\n */\n const isOddIteration = Boolean(currentIteration % 2);\n if (isOddIteration) {\n if (repeatType === \"reverse\") {\n iterationProgress = 1 - iterationProgress;\n if (repeatDelay) {\n iterationProgress -= repeatDelay / resolvedDuration;\n }\n }\n else if (repeatType === \"mirror\") {\n frameGenerator = mirroredGenerator;\n }\n }\n elapsed = clamp(0, 1, iterationProgress) * resolvedDuration;\n }\n /**\n * If we're in negative time, set state as the initial keyframe.\n * This prevents delay: x, duration: 0 animations from finishing\n * instantly.\n */\n const state = isInDelayPhase\n ? { done: false, value: keyframes$1[0] }\n : frameGenerator.next(elapsed);\n if (mapNumbersToKeyframes) {\n state.value = mapNumbersToKeyframes(state.value);\n }\n let { done } = state;\n if (!isInDelayPhase && calculatedDuration !== null) {\n done = speed >= 0 ? currentTime >= totalDuration : currentTime <= 0;\n }\n const isAnimationFinished = holdTime === null &&\n (playState === \"finished\" || (playState === \"running\" && done));\n if (onUpdate) {\n onUpdate(state.value);\n }\n if (isAnimationFinished) {\n finish();\n }\n return state;\n };\n const stopAnimationDriver = () => {\n animationDriver && animationDriver.stop();\n animationDriver = undefined;\n };\n const cancel = () => {\n playState = \"idle\";\n stopAnimationDriver();\n resolveFinishedPromise();\n updateFinishedPromise();\n startTime = cancelTime = null;\n };\n const finish = () => {\n playState = \"finished\";\n onComplete && onComplete();\n stopAnimationDriver();\n resolveFinishedPromise();\n };\n const play = () => {\n if (hasStopped)\n return;\n if (!animationDriver)\n animationDriver = driver(tick);\n const now = animationDriver.now();\n onPlay && onPlay();\n if (holdTime !== null) {\n startTime = now - holdTime;\n }\n else if (!startTime || playState === \"finished\") {\n startTime = now;\n }\n if (playState === \"finished\") {\n updateFinishedPromise();\n }\n cancelTime = startTime;\n holdTime = null;\n /**\n * Set playState to running only after we've used it in\n * the previous logic.\n */\n playState = \"running\";\n animationDriver.start();\n };\n if (autoplay) {\n play();\n }\n const controls = {\n then(resolve, reject) {\n return currentFinishedPromise.then(resolve, reject);\n },\n get time() {\n return millisecondsToSeconds(currentTime);\n },\n set time(newTime) {\n newTime = secondsToMilliseconds(newTime);\n currentTime = newTime;\n if (holdTime !== null || !animationDriver || speed === 0) {\n holdTime = newTime;\n }\n else {\n startTime = animationDriver.now() - newTime / speed;\n }\n },\n get duration() {\n const duration = generator.calculatedDuration === null\n ? calcGeneratorDuration(generator)\n : generator.calculatedDuration;\n return millisecondsToSeconds(duration);\n },\n get speed() {\n return speed;\n },\n set speed(newSpeed) {\n if (newSpeed === speed || !animationDriver)\n return;\n speed = newSpeed;\n controls.time = millisecondsToSeconds(currentTime);\n },\n get state() {\n return playState;\n },\n play,\n pause: () => {\n playState = \"paused\";\n holdTime = currentTime;\n },\n stop: () => {\n hasStopped = true;\n if (playState === \"idle\")\n return;\n playState = \"idle\";\n onStop && onStop();\n cancel();\n },\n cancel: () => {\n if (cancelTime !== null)\n tick(cancelTime);\n cancel();\n },\n complete: () => {\n playState = \"finished\";\n },\n sample: (elapsed) => {\n startTime = 0;\n return tick(elapsed);\n },\n };\n return controls;\n}\n\nexport { animateValue };\n","function memo(callback) {\n let result;\n return () => {\n if (result === undefined)\n result = callback();\n return result;\n };\n}\n\nexport { memo };\n","import { animateStyle } from './index.mjs';\nimport { isWaapiSupportedEasing } from './easing.mjs';\nimport { getFinalKeyframe } from './utils/get-final-keyframe.mjs';\nimport { animateValue } from '../js/index.mjs';\nimport { millisecondsToSeconds, secondsToMilliseconds } from '../../../utils/time-conversion.mjs';\nimport { memo } from '../../../utils/memo.mjs';\nimport { noop } from '../../../utils/noop.mjs';\nimport { frame, cancelFrame } from '../../../frameloop/frame.mjs';\n\nconst supportsWaapi = memo(() => Object.hasOwnProperty.call(Element.prototype, \"animate\"));\n/**\n * A list of values that can be hardware-accelerated.\n */\nconst acceleratedValues = new Set([\n \"opacity\",\n \"clipPath\",\n \"filter\",\n \"transform\",\n \"backgroundColor\",\n]);\n/**\n * 10ms is chosen here as it strikes a balance between smooth\n * results (more than one keyframe per frame at 60fps) and\n * keyframe quantity.\n */\nconst sampleDelta = 10; //ms\n/**\n * Implement a practical max duration for keyframe generation\n * to prevent infinite loops\n */\nconst maxDuration = 20000;\nconst requiresPregeneratedKeyframes = (valueName, options) => options.type === \"spring\" ||\n valueName === \"backgroundColor\" ||\n !isWaapiSupportedEasing(options.ease);\nfunction createAcceleratedAnimation(value, valueName, { onUpdate, onComplete, ...options }) {\n const canAccelerateAnimation = supportsWaapi() &&\n acceleratedValues.has(valueName) &&\n !options.repeatDelay &&\n options.repeatType !== \"mirror\" &&\n options.damping !== 0 &&\n options.type !== \"inertia\";\n if (!canAccelerateAnimation)\n return false;\n /**\n * TODO: Unify with js/index\n */\n let hasStopped = false;\n let resolveFinishedPromise;\n let currentFinishedPromise;\n /**\n * Cancelling an animation will write to the DOM. For safety we want to defer\n * this until the next `update` frame lifecycle. This flag tracks whether we\n * have a pending cancel, if so we shouldn't allow animations to finish.\n */\n let pendingCancel = false;\n /**\n * Resolve the current Promise every time we enter the\n * finished state. This is WAAPI-compatible behaviour.\n */\n const updateFinishedPromise = () => {\n currentFinishedPromise = new Promise((resolve) => {\n resolveFinishedPromise = resolve;\n });\n };\n // Create the first finished promise\n updateFinishedPromise();\n let { keyframes, duration = 300, ease, times } = options;\n /**\n * If this animation needs pre-generated keyframes then generate.\n */\n if (requiresPregeneratedKeyframes(valueName, options)) {\n const sampleAnimation = animateValue({\n ...options,\n repeat: 0,\n delay: 0,\n });\n let state = { done: false, value: keyframes[0] };\n const pregeneratedKeyframes = [];\n /**\n * Bail after 20 seconds of pre-generated keyframes as it's likely\n * we're heading for an infinite loop.\n */\n let t = 0;\n while (!state.done && t < maxDuration) {\n state = sampleAnimation.sample(t);\n pregeneratedKeyframes.push(state.value);\n t += sampleDelta;\n }\n times = undefined;\n keyframes = pregeneratedKeyframes;\n duration = t - sampleDelta;\n ease = \"linear\";\n }\n const animation = animateStyle(value.owner.current, valueName, keyframes, {\n ...options,\n duration,\n /**\n * This function is currently not called if ease is provided\n * as a function so the cast is safe.\n *\n * However it would be possible for a future refinement to port\n * in easing pregeneration from Motion One for browsers that\n * support the upcoming `linear()` easing function.\n */\n ease: ease,\n times,\n });\n const cancelAnimation = () => {\n pendingCancel = false;\n animation.cancel();\n };\n const safeCancel = () => {\n pendingCancel = true;\n frame.update(cancelAnimation);\n resolveFinishedPromise();\n updateFinishedPromise();\n };\n /**\n * Prefer the `onfinish` prop as it's more widely supported than\n * the `finished` promise.\n *\n * Here, we synchronously set the provided MotionValue to the end\n * keyframe. If we didn't, when the WAAPI animation is finished it would\n * be removed from the element which would then revert to its old styles.\n */\n animation.onfinish = () => {\n if (pendingCancel)\n return;\n value.set(getFinalKeyframe(keyframes, options));\n onComplete && onComplete();\n safeCancel();\n };\n /**\n * Animation interrupt callback.\n */\n const controls = {\n then(resolve, reject) {\n return currentFinishedPromise.then(resolve, reject);\n },\n attachTimeline(timeline) {\n animation.timeline = timeline;\n animation.onfinish = null;\n return noop;\n },\n get time() {\n return millisecondsToSeconds(animation.currentTime || 0);\n },\n set time(newTime) {\n animation.currentTime = secondsToMilliseconds(newTime);\n },\n get speed() {\n return animation.playbackRate;\n },\n set speed(newSpeed) {\n animation.playbackRate = newSpeed;\n },\n get duration() {\n return millisecondsToSeconds(duration);\n },\n play: () => {\n if (hasStopped)\n return;\n animation.play();\n /**\n * Cancel any pending cancel tasks\n */\n cancelFrame(cancelAnimation);\n },\n pause: () => animation.pause(),\n stop: () => {\n hasStopped = true;\n if (animation.playState === \"idle\")\n return;\n /**\n * WAAPI doesn't natively have any interruption capabilities.\n *\n * Rather than read commited styles back out of the DOM, we can\n * create a renderless JS animation and sample it twice to calculate\n * its current value, \"previous\" value, and therefore allow\n * Motion to calculate velocity for any subsequent animation.\n */\n const { currentTime } = animation;\n if (currentTime) {\n const sampleAnimation = animateValue({\n ...options,\n autoplay: false,\n });\n value.setWithVelocity(sampleAnimation.sample(currentTime - sampleDelta).value, sampleAnimation.sample(currentTime).value, sampleDelta);\n }\n safeCancel();\n },\n complete: () => {\n if (pendingCancel)\n return;\n animation.finish();\n },\n cancel: safeCancel,\n };\n return controls;\n}\n\nexport { createAcceleratedAnimation };\n","import { animateValue } from './js/index.mjs';\nimport { noop } from '../../utils/noop.mjs';\n\nfunction createInstantAnimation({ keyframes, delay, onUpdate, onComplete, }) {\n const setValue = () => {\n onUpdate && onUpdate(keyframes[keyframes.length - 1]);\n onComplete && onComplete();\n /**\n * TODO: As this API grows it could make sense to always return\n * animateValue. This will be a bigger project as animateValue\n * is frame-locked whereas this function resolves instantly.\n * This is a behavioural change and also has ramifications regarding\n * assumptions within tests.\n */\n return {\n time: 0,\n speed: 1,\n duration: 0,\n play: (noop),\n pause: (noop),\n stop: (noop),\n then: (resolve) => {\n resolve();\n return Promise.resolve();\n },\n cancel: (noop),\n complete: (noop),\n };\n };\n return delay\n ? animateValue({\n keyframes: [0, 1],\n duration: 0,\n delay,\n onComplete: setValue,\n })\n : setValue();\n}\n\nexport { createInstantAnimation };\n","import { transformProps } from '../../render/html/utils/transform.mjs';\n\nconst underDampedSpring = {\n type: \"spring\",\n stiffness: 500,\n damping: 25,\n restSpeed: 10,\n};\nconst criticallyDampedSpring = (target) => ({\n type: \"spring\",\n stiffness: 550,\n damping: target === 0 ? 2 * Math.sqrt(550) : 30,\n restSpeed: 10,\n});\nconst keyframesTransition = {\n type: \"keyframes\",\n duration: 0.8,\n};\n/**\n * Default easing curve is a slightly shallower version of\n * the default browser easing curve.\n */\nconst ease = {\n type: \"keyframes\",\n ease: [0.25, 0.1, 0.35, 1],\n duration: 0.3,\n};\nconst getDefaultTransition = (valueKey, { keyframes }) => {\n if (keyframes.length > 2) {\n return keyframesTransition;\n }\n else if (transformProps.has(valueKey)) {\n return valueKey.startsWith(\"scale\")\n ? criticallyDampedSpring(keyframes[1])\n : underDampedSpring;\n }\n return ease;\n};\n\nexport { getDefaultTransition };\n","import { complex } from '../../value/types/complex/index.mjs';\n\n/**\n * Check if a value is animatable. Examples:\n *\n * ✅: 100, \"100px\", \"#fff\"\n * ❌: \"block\", \"url(2.jpg)\"\n * @param value\n *\n * @internal\n */\nconst isAnimatable = (key, value) => {\n // If the list of keys tat might be non-animatable grows, replace with Set\n if (key === \"zIndex\")\n return false;\n // If it's a number or a keyframes array, we can animate it. We might at some point\n // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this,\n // but for now lets leave it like this for performance reasons\n if (typeof value === \"number\" || Array.isArray(value))\n return true;\n if (typeof value === \"string\" && // It's animatable if we have a string\n (complex.test(value) || value === \"0\") && // And it contains numbers and/or colors\n !value.startsWith(\"url(\") // Unless it starts with \"url(\"\n ) {\n return true;\n }\n return false;\n};\n\nexport { isAnimatable };\n","import { complex } from './index.mjs';\nimport { floatRegex } from '../utils.mjs';\n\n/**\n * Properties that should default to 1 or 100%\n */\nconst maxDefaults = new Set([\"brightness\", \"contrast\", \"saturate\", \"opacity\"]);\nfunction applyDefaultFilter(v) {\n const [name, value] = v.slice(0, -1).split(\"(\");\n if (name === \"drop-shadow\")\n return v;\n const [number] = value.match(floatRegex) || [];\n if (!number)\n return v;\n const unit = value.replace(number, \"\");\n let defaultValue = maxDefaults.has(name) ? 1 : 0;\n if (number !== value)\n defaultValue *= 100;\n return name + \"(\" + defaultValue + unit + \")\";\n}\nconst functionRegex = /([a-z-]*)\\(.*?\\)/g;\nconst filter = {\n ...complex,\n getAnimatableNone: (v) => {\n const functions = v.match(functionRegex);\n return functions ? functions.map(applyDefaultFilter).join(\" \") : v;\n },\n};\n\nexport { filter };\n","import { color } from '../../../value/types/color/index.mjs';\nimport { filter } from '../../../value/types/complex/filter.mjs';\nimport { numberValueTypes } from './number.mjs';\n\n/**\n * A map of default value types for common values\n */\nconst defaultValueTypes = {\n ...numberValueTypes,\n // Color props\n color,\n backgroundColor: color,\n outlineColor: color,\n fill: color,\n stroke: color,\n // Border props\n borderColor: color,\n borderTopColor: color,\n borderRightColor: color,\n borderBottomColor: color,\n borderLeftColor: color,\n filter,\n WebkitFilter: filter,\n};\n/**\n * Gets the default ValueType for the provided value key\n */\nconst getDefaultValueType = (key) => defaultValueTypes[key];\n\nexport { defaultValueTypes, getDefaultValueType };\n","import { complex } from '../../../value/types/complex/index.mjs';\nimport { filter } from '../../../value/types/complex/filter.mjs';\nimport { getDefaultValueType } from './defaults.mjs';\n\nfunction getAnimatableNone(key, value) {\n let defaultValueType = getDefaultValueType(key);\n if (defaultValueType !== filter)\n defaultValueType = complex;\n // If value is not recognised as animatable, ie \"none\", create an animatable version origin based on the target\n return defaultValueType.getAnimatableNone\n ? defaultValueType.getAnimatableNone(value)\n : undefined;\n}\n\nexport { getAnimatableNone };\n","/**\n * Check if the value is a zero value string like \"0px\" or \"0%\"\n */\nconst isZeroValueString = (v) => /^0[^.\\s]+$/.test(v);\n\nexport { isZeroValueString };\n","import { isZeroValueString } from '../../utils/is-zero-value-string.mjs';\n\nfunction isNone(value) {\n if (typeof value === \"number\") {\n return value === 0;\n }\n else if (value !== null) {\n return value === \"none\" || value === \"0\" || isZeroValueString(value);\n }\n}\n\nexport { isNone };\n","import { getAnimatableNone } from '../../render/dom/value-types/animatable-none.mjs';\nimport { isAnimatable } from './is-animatable.mjs';\nimport { isNone } from './is-none.mjs';\n\nfunction getKeyframes(value, valueName, target, transition) {\n const isTargetAnimatable = isAnimatable(valueName, target);\n let keyframes;\n if (Array.isArray(target)) {\n keyframes = [...target];\n }\n else {\n keyframes = [null, target];\n }\n const defaultOrigin = transition.from !== undefined ? transition.from : value.get();\n let animatableTemplateValue = undefined;\n const noneKeyframeIndexes = [];\n for (let i = 0; i < keyframes.length; i++) {\n /**\n * Fill null/wildcard keyframes\n */\n if (keyframes[i] === null) {\n keyframes[i] = i === 0 ? defaultOrigin : keyframes[i - 1];\n }\n if (isNone(keyframes[i])) {\n noneKeyframeIndexes.push(i);\n }\n // TODO: Clean this conditional, it works for now\n if (typeof keyframes[i] === \"string\" &&\n keyframes[i] !== \"none\" &&\n keyframes[i] !== \"0\") {\n animatableTemplateValue = keyframes[i];\n }\n }\n if (isTargetAnimatable &&\n noneKeyframeIndexes.length &&\n animatableTemplateValue) {\n for (let i = 0; i < noneKeyframeIndexes.length; i++) {\n const index = noneKeyframeIndexes[i];\n keyframes[index] = getAnimatableNone(valueName, animatableTemplateValue);\n }\n }\n return keyframes;\n}\n\nexport { getKeyframes };\n","/**\n * Decide whether a transition is defined on a given Transition.\n * This filters out orchestration options and returns true\n * if any options are left.\n */\nfunction isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) {\n return !!Object.keys(transition).length;\n}\nfunction getValueTransition(transition, key) {\n return transition[key] || transition[\"default\"] || transition;\n}\n\nexport { getValueTransition, isTransitionDefined };\n","const MotionGlobalConfig = {\n skipAnimations: false,\n};\n\nexport { MotionGlobalConfig };\n","import { warning } from '../../utils/errors.mjs';\nimport { secondsToMilliseconds } from '../../utils/time-conversion.mjs';\nimport { instantAnimationState } from '../../utils/use-instant-transition-state.mjs';\nimport { createAcceleratedAnimation } from '../animators/waapi/create-accelerated-animation.mjs';\nimport { createInstantAnimation } from '../animators/instant.mjs';\nimport { getDefaultTransition } from '../utils/default-transitions.mjs';\nimport { isAnimatable } from '../utils/is-animatable.mjs';\nimport { getKeyframes } from '../utils/keyframes.mjs';\nimport { getValueTransition, isTransitionDefined } from '../utils/transitions.mjs';\nimport { animateValue } from '../animators/js/index.mjs';\nimport { MotionGlobalConfig } from '../../utils/GlobalConfig.mjs';\n\nconst animateMotionValue = (valueName, value, target, transition = {}) => {\n return (onComplete) => {\n const valueTransition = getValueTransition(transition, valueName) || {};\n /**\n * Most transition values are currently completely overwritten by value-specific\n * transitions. In the future it'd be nicer to blend these transitions. But for now\n * delay actually does inherit from the root transition if not value-specific.\n */\n const delay = valueTransition.delay || transition.delay || 0;\n /**\n * Elapsed isn't a public transition option but can be passed through from\n * optimized appear effects in milliseconds.\n */\n let { elapsed = 0 } = transition;\n elapsed = elapsed - secondsToMilliseconds(delay);\n const keyframes = getKeyframes(value, valueName, target, valueTransition);\n /**\n * Check if we're able to animate between the start and end keyframes,\n * and throw a warning if we're attempting to animate between one that's\n * animatable and another that isn't.\n */\n const originKeyframe = keyframes[0];\n const targetKeyframe = keyframes[keyframes.length - 1];\n const isOriginAnimatable = isAnimatable(valueName, originKeyframe);\n const isTargetAnimatable = isAnimatable(valueName, targetKeyframe);\n warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${valueName} from \"${originKeyframe}\" to \"${targetKeyframe}\". ${originKeyframe} is not an animatable value - to enable this animation set ${originKeyframe} to a value animatable to ${targetKeyframe} via the \\`style\\` property.`);\n let options = {\n keyframes,\n velocity: value.getVelocity(),\n ease: \"easeOut\",\n ...valueTransition,\n delay: -elapsed,\n onUpdate: (v) => {\n value.set(v);\n valueTransition.onUpdate && valueTransition.onUpdate(v);\n },\n onComplete: () => {\n onComplete();\n valueTransition.onComplete && valueTransition.onComplete();\n },\n };\n /**\n * If there's no transition defined for this value, we can generate\n * unqiue transition settings for this value.\n */\n if (!isTransitionDefined(valueTransition)) {\n options = {\n ...options,\n ...getDefaultTransition(valueName, options),\n };\n }\n /**\n * Both WAAPI and our internal animation functions use durations\n * as defined by milliseconds, while our external API defines them\n * as seconds.\n */\n if (options.duration) {\n options.duration = secondsToMilliseconds(options.duration);\n }\n if (options.repeatDelay) {\n options.repeatDelay = secondsToMilliseconds(options.repeatDelay);\n }\n if (!isOriginAnimatable ||\n !isTargetAnimatable ||\n instantAnimationState.current ||\n valueTransition.type === false ||\n MotionGlobalConfig.skipAnimations) {\n /**\n * If we can't animate this value, or the global instant animation flag is set,\n * or this is simply defined as an instant transition, return an instant transition.\n */\n return createInstantAnimation(instantAnimationState.current\n ? { ...options, delay: 0 }\n : options);\n }\n /**\n * Animate via WAAPI if possible.\n */\n if (\n /**\n * If this is a handoff animation, the optimised animation will be running via\n * WAAPI. Therefore, this animation must be JS to ensure it runs \"under\" the\n * optimised animation.\n */\n !transition.isHandoff &&\n value.owner &&\n value.owner.current instanceof HTMLElement &&\n /**\n * If we're outputting values to onUpdate then we can't use WAAPI as there's\n * no way to read the value from WAAPI every frame.\n */\n !value.owner.getProps().onUpdate) {\n const acceleratedAnimation = createAcceleratedAnimation(value, valueName, options);\n if (acceleratedAnimation)\n return acceleratedAnimation;\n }\n /**\n * If we didn't create an accelerated animation, create a JS animation\n */\n return animateValue(options);\n };\n};\n\nexport { animateMotionValue };\n","import { isMotionValue } from '../utils/is-motion-value.mjs';\n\nfunction isWillChangeMotionValue(value) {\n return Boolean(isMotionValue(value) && value.add);\n}\n\nexport { isWillChangeMotionValue };\n","/**\n * Check if value is a numerical string, ie a string that is purely a number eg \"100\" or \"-100.1\"\n */\nconst isNumericalString = (v) => /^\\-?\\d*\\.?\\d+$/.test(v);\n\nexport { isNumericalString };\n","function addUniqueItem(arr, item) {\n if (arr.indexOf(item) === -1)\n arr.push(item);\n}\nfunction removeItem(arr, item) {\n const index = arr.indexOf(item);\n if (index > -1)\n arr.splice(index, 1);\n}\n// Adapted from array-move\nfunction moveItem([...arr], fromIndex, toIndex) {\n const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex;\n if (startIndex >= 0 && startIndex < arr.length) {\n const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex;\n const [item] = arr.splice(fromIndex, 1);\n arr.splice(endIndex, 0, item);\n }\n return arr;\n}\n\nexport { addUniqueItem, moveItem, removeItem };\n","import { addUniqueItem, removeItem } from './array.mjs';\n\nclass SubscriptionManager {\n constructor() {\n this.subscriptions = [];\n }\n add(handler) {\n addUniqueItem(this.subscriptions, handler);\n return () => removeItem(this.subscriptions, handler);\n }\n notify(a, b, c) {\n const numSubscriptions = this.subscriptions.length;\n if (!numSubscriptions)\n return;\n if (numSubscriptions === 1) {\n /**\n * If there's only a single handler we can just call it without invoking a loop.\n */\n this.subscriptions[0](a, b, c);\n }\n else {\n for (let i = 0; i < numSubscriptions; i++) {\n /**\n * Check whether the handler exists before firing as it's possible\n * the subscriptions were modified during this loop running.\n */\n const handler = this.subscriptions[i];\n handler && handler(a, b, c);\n }\n }\n }\n getSize() {\n return this.subscriptions.length;\n }\n clear() {\n this.subscriptions.length = 0;\n }\n}\n\nexport { SubscriptionManager };\n","import { SubscriptionManager } from '../utils/subscription-manager.mjs';\nimport { velocityPerSecond } from '../utils/velocity-per-second.mjs';\nimport { warnOnce } from '../utils/warn-once.mjs';\nimport { frame, frameData } from '../frameloop/frame.mjs';\n\nconst isFloat = (value) => {\n return !isNaN(parseFloat(value));\n};\nconst collectMotionValues = {\n current: undefined,\n};\n/**\n * `MotionValue` is used to track the state and velocity of motion values.\n *\n * @public\n */\nclass MotionValue {\n /**\n * @param init - The initiating value\n * @param config - Optional configuration options\n *\n * - `transformer`: A function to transform incoming values with.\n *\n * @internal\n */\n constructor(init, options = {}) {\n /**\n * This will be replaced by the build step with the latest version number.\n * When MotionValues are provided to motion components, warn if versions are mixed.\n */\n this.version = \"10.18.0\";\n /**\n * Duration, in milliseconds, since last updating frame.\n *\n * @internal\n */\n this.timeDelta = 0;\n /**\n * Timestamp of the last time this `MotionValue` was updated.\n *\n * @internal\n */\n this.lastUpdated = 0;\n /**\n * Tracks whether this value can output a velocity. Currently this is only true\n * if the value is numerical, but we might be able to widen the scope here and support\n * other value types.\n *\n * @internal\n */\n this.canTrackVelocity = false;\n /**\n * An object containing a SubscriptionManager for each active event.\n */\n this.events = {};\n this.updateAndNotify = (v, render = true) => {\n this.prev = this.current;\n this.current = v;\n // Update timestamp\n const { delta, timestamp } = frameData;\n if (this.lastUpdated !== timestamp) {\n this.timeDelta = delta;\n this.lastUpdated = timestamp;\n frame.postRender(this.scheduleVelocityCheck);\n }\n // Update update subscribers\n if (this.prev !== this.current && this.events.change) {\n this.events.change.notify(this.current);\n }\n // Update velocity subscribers\n if (this.events.velocityChange) {\n this.events.velocityChange.notify(this.getVelocity());\n }\n // Update render subscribers\n if (render && this.events.renderRequest) {\n this.events.renderRequest.notify(this.current);\n }\n };\n /**\n * Schedule a velocity check for the next frame.\n *\n * This is an instanced and bound function to prevent generating a new\n * function once per frame.\n *\n * @internal\n */\n this.scheduleVelocityCheck = () => frame.postRender(this.velocityCheck);\n /**\n * Updates `prev` with `current` if the value hasn't been updated this frame.\n * This ensures velocity calculations return `0`.\n *\n * This is an instanced and bound function to prevent generating a new\n * function once per frame.\n *\n * @internal\n */\n this.velocityCheck = ({ timestamp }) => {\n if (timestamp !== this.lastUpdated) {\n this.prev = this.current;\n if (this.events.velocityChange) {\n this.events.velocityChange.notify(this.getVelocity());\n }\n }\n };\n this.hasAnimated = false;\n this.prev = this.current = init;\n this.canTrackVelocity = isFloat(this.current);\n this.owner = options.owner;\n }\n /**\n * Adds a function that will be notified when the `MotionValue` is updated.\n *\n * It returns a function that, when called, will cancel the subscription.\n *\n * When calling `onChange` inside a React component, it should be wrapped with the\n * `useEffect` hook. As it returns an unsubscribe function, this should be returned\n * from the `useEffect` function to ensure you don't add duplicate subscribers..\n *\n * ```jsx\n * export const MyComponent = () => {\n * const x = useMotionValue(0)\n * const y = useMotionValue(0)\n * const opacity = useMotionValue(1)\n *\n * useEffect(() => {\n * function updateOpacity() {\n * const maxXY = Math.max(x.get(), y.get())\n * const newOpacity = transform(maxXY, [0, 100], [1, 0])\n * opacity.set(newOpacity)\n * }\n *\n * const unsubscribeX = x.on(\"change\", updateOpacity)\n * const unsubscribeY = y.on(\"change\", updateOpacity)\n *\n * return () => {\n * unsubscribeX()\n * unsubscribeY()\n * }\n * }, [])\n *\n * return \n * }\n * ```\n *\n * @param subscriber - A function that receives the latest value.\n * @returns A function that, when called, will cancel this subscription.\n *\n * @deprecated\n */\n onChange(subscription) {\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on(\"change\", callback).`);\n }\n return this.on(\"change\", subscription);\n }\n on(eventName, callback) {\n if (!this.events[eventName]) {\n this.events[eventName] = new SubscriptionManager();\n }\n const unsubscribe = this.events[eventName].add(callback);\n if (eventName === \"change\") {\n return () => {\n unsubscribe();\n /**\n * If we have no more change listeners by the start\n * of the next frame, stop active animations.\n */\n frame.read(() => {\n if (!this.events.change.getSize()) {\n this.stop();\n }\n });\n };\n }\n return unsubscribe;\n }\n clearListeners() {\n for (const eventManagers in this.events) {\n this.events[eventManagers].clear();\n }\n }\n /**\n * Attaches a passive effect to the `MotionValue`.\n *\n * @internal\n */\n attach(passiveEffect, stopPassiveEffect) {\n this.passiveEffect = passiveEffect;\n this.stopPassiveEffect = stopPassiveEffect;\n }\n /**\n * Sets the state of the `MotionValue`.\n *\n * @remarks\n *\n * ```jsx\n * const x = useMotionValue(0)\n * x.set(10)\n * ```\n *\n * @param latest - Latest value to set.\n * @param render - Whether to notify render subscribers. Defaults to `true`\n *\n * @public\n */\n set(v, render = true) {\n if (!render || !this.passiveEffect) {\n this.updateAndNotify(v, render);\n }\n else {\n this.passiveEffect(v, this.updateAndNotify);\n }\n }\n setWithVelocity(prev, current, delta) {\n this.set(current);\n this.prev = prev;\n this.timeDelta = delta;\n }\n /**\n * Set the state of the `MotionValue`, stopping any active animations,\n * effects, and resets velocity to `0`.\n */\n jump(v) {\n this.updateAndNotify(v);\n this.prev = v;\n this.stop();\n if (this.stopPassiveEffect)\n this.stopPassiveEffect();\n }\n /**\n * Returns the latest state of `MotionValue`\n *\n * @returns - The latest state of `MotionValue`\n *\n * @public\n */\n get() {\n if (collectMotionValues.current) {\n collectMotionValues.current.push(this);\n }\n return this.current;\n }\n /**\n * @public\n */\n getPrevious() {\n return this.prev;\n }\n /**\n * Returns the latest velocity of `MotionValue`\n *\n * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.\n *\n * @public\n */\n getVelocity() {\n // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful\n return this.canTrackVelocity\n ? // These casts could be avoided if parseFloat would be typed better\n velocityPerSecond(parseFloat(this.current) -\n parseFloat(this.prev), this.timeDelta)\n : 0;\n }\n /**\n * Registers a new animation to control this `MotionValue`. Only one\n * animation can drive a `MotionValue` at one time.\n *\n * ```jsx\n * value.start()\n * ```\n *\n * @param animation - A function that starts the provided animation\n *\n * @internal\n */\n start(startAnimation) {\n this.stop();\n return new Promise((resolve) => {\n this.hasAnimated = true;\n this.animation = startAnimation(resolve);\n if (this.events.animationStart) {\n this.events.animationStart.notify();\n }\n }).then(() => {\n if (this.events.animationComplete) {\n this.events.animationComplete.notify();\n }\n this.clearAnimation();\n });\n }\n /**\n * Stop the currently active animation.\n *\n * @public\n */\n stop() {\n if (this.animation) {\n this.animation.stop();\n if (this.events.animationCancel) {\n this.events.animationCancel.notify();\n }\n }\n this.clearAnimation();\n }\n /**\n * Returns `true` if this value is currently animating.\n *\n * @public\n */\n isAnimating() {\n return !!this.animation;\n }\n clearAnimation() {\n delete this.animation;\n }\n /**\n * Destroy and clean up subscribers to this `MotionValue`.\n *\n * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically\n * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually\n * created a `MotionValue` via the `motionValue` function.\n *\n * @public\n */\n destroy() {\n this.clearListeners();\n this.stop();\n if (this.stopPassiveEffect) {\n this.stopPassiveEffect();\n }\n }\n}\nfunction motionValue(init, options) {\n return new MotionValue(init, options);\n}\n\nexport { MotionValue, collectMotionValues, motionValue };\n","/**\n * Tests a provided value against a ValueType\n */\nconst testValueType = (v) => (type) => type.test(v);\n\nexport { testValueType };\n","/**\n * ValueType for \"auto\"\n */\nconst auto = {\n test: (v) => v === \"auto\",\n parse: (v) => v,\n};\n\nexport { auto };\n","import { number } from '../../../value/types/numbers/index.mjs';\nimport { px, percent, degrees, vw, vh } from '../../../value/types/numbers/units.mjs';\nimport { testValueType } from './test.mjs';\nimport { auto } from './type-auto.mjs';\n\n/**\n * A list of value types commonly used for dimensions\n */\nconst dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];\n/**\n * Tests a dimensional value against the list of dimension ValueTypes\n */\nconst findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));\n\nexport { dimensionValueTypes, findDimensionValueType };\n","import { color } from '../../../value/types/color/index.mjs';\nimport { complex } from '../../../value/types/complex/index.mjs';\nimport { dimensionValueTypes } from './dimensions.mjs';\nimport { testValueType } from './test.mjs';\n\n/**\n * A list of all ValueTypes\n */\nconst valueTypes = [...dimensionValueTypes, color, complex];\n/**\n * Tests a value against the list of ValueTypes\n */\nconst findValueType = (v) => valueTypes.find(testValueType(v));\n\nexport { findValueType };\n","import { isNumericalString } from '../../utils/is-numerical-string.mjs';\nimport { isZeroValueString } from '../../utils/is-zero-value-string.mjs';\nimport { resolveFinalValueInKeyframes } from '../../utils/resolve-value.mjs';\nimport { motionValue } from '../../value/index.mjs';\nimport { complex } from '../../value/types/complex/index.mjs';\nimport { getAnimatableNone } from '../dom/value-types/animatable-none.mjs';\nimport { findValueType } from '../dom/value-types/find.mjs';\nimport { resolveVariant } from './resolve-dynamic-variants.mjs';\n\n/**\n * Set VisualElement's MotionValue, creating a new MotionValue for it if\n * it doesn't exist.\n */\nfunction setMotionValue(visualElement, key, value) {\n if (visualElement.hasValue(key)) {\n visualElement.getValue(key).set(value);\n }\n else {\n visualElement.addValue(key, motionValue(value));\n }\n}\nfunction setTarget(visualElement, definition) {\n const resolved = resolveVariant(visualElement, definition);\n let { transitionEnd = {}, transition = {}, ...target } = resolved ? visualElement.makeTargetAnimatable(resolved, false) : {};\n target = { ...target, ...transitionEnd };\n for (const key in target) {\n const value = resolveFinalValueInKeyframes(target[key]);\n setMotionValue(visualElement, key, value);\n }\n}\nfunction setVariants(visualElement, variantLabels) {\n const reversedLabels = [...variantLabels].reverse();\n reversedLabels.forEach((key) => {\n const variant = visualElement.getVariant(key);\n variant && setTarget(visualElement, variant);\n if (visualElement.variantChildren) {\n visualElement.variantChildren.forEach((child) => {\n setVariants(child, variantLabels);\n });\n }\n });\n}\nfunction setValues(visualElement, definition) {\n if (Array.isArray(definition)) {\n return setVariants(visualElement, definition);\n }\n else if (typeof definition === \"string\") {\n return setVariants(visualElement, [definition]);\n }\n else {\n setTarget(visualElement, definition);\n }\n}\nfunction checkTargetForNewValues(visualElement, target, origin) {\n var _a, _b;\n const newValueKeys = Object.keys(target).filter((key) => !visualElement.hasValue(key));\n const numNewValues = newValueKeys.length;\n if (!numNewValues)\n return;\n for (let i = 0; i < numNewValues; i++) {\n const key = newValueKeys[i];\n const targetValue = target[key];\n let value = null;\n /**\n * If the target is a series of keyframes, we can use the first value\n * in the array. If this first value is null, we'll still need to read from the DOM.\n */\n if (Array.isArray(targetValue)) {\n value = targetValue[0];\n }\n /**\n * If the target isn't keyframes, or the first keyframe was null, we need to\n * first check if an origin value was explicitly defined in the transition as \"from\",\n * if not read the value from the DOM. As an absolute fallback, take the defined target value.\n */\n if (value === null) {\n value = (_b = (_a = origin[key]) !== null && _a !== void 0 ? _a : visualElement.readValue(key)) !== null && _b !== void 0 ? _b : target[key];\n }\n /**\n * If value is still undefined or null, ignore it. Preferably this would throw,\n * but this was causing issues in Framer.\n */\n if (value === undefined || value === null)\n continue;\n if (typeof value === \"string\" &&\n (isNumericalString(value) || isZeroValueString(value))) {\n // If this is a number read as a string, ie \"0\" or \"200\", convert it to a number\n value = parseFloat(value);\n }\n else if (!findValueType(value) && complex.test(targetValue)) {\n value = getAnimatableNone(key, targetValue);\n }\n visualElement.addValue(key, motionValue(value, { owner: visualElement }));\n if (origin[key] === undefined) {\n origin[key] = value;\n }\n if (value !== null)\n visualElement.setBaseTarget(key, value);\n }\n}\nfunction getOriginFromTransition(key, transition) {\n if (!transition)\n return;\n const valueTransition = transition[key] || transition[\"default\"] || transition;\n return valueTransition.from;\n}\nfunction getOrigin(target, transition, visualElement) {\n const origin = {};\n for (const key in target) {\n const transitionOrigin = getOriginFromTransition(key, transition);\n if (transitionOrigin !== undefined) {\n origin[key] = transitionOrigin;\n }\n else {\n const value = visualElement.getValue(key);\n if (value) {\n origin[key] = value.get();\n }\n }\n }\n return origin;\n}\n\nexport { checkTargetForNewValues, getOrigin, getOriginFromTransition, setTarget, setValues };\n","import { transformProps } from '../../render/html/utils/transform.mjs';\nimport { optimizedAppearDataAttribute } from '../optimized-appear/data-id.mjs';\nimport { animateMotionValue } from './motion-value.mjs';\nimport { isWillChangeMotionValue } from '../../value/use-will-change/is.mjs';\nimport { setTarget } from '../../render/utils/setters.mjs';\nimport { getValueTransition } from '../utils/transitions.mjs';\nimport { frame } from '../../frameloop/frame.mjs';\n\n/**\n * Decide whether we should block this animation. Previously, we achieved this\n * just by checking whether the key was listed in protectedKeys, but this\n * posed problems if an animation was triggered by afterChildren and protectedKeys\n * had been set to true in the meantime.\n */\nfunction shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {\n const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;\n needsAnimating[key] = false;\n return shouldBlock;\n}\nfunction hasKeyframesChanged(value, target) {\n const current = value.get();\n if (Array.isArray(target)) {\n for (let i = 0; i < target.length; i++) {\n if (target[i] !== current)\n return true;\n }\n }\n else {\n return current !== target;\n }\n}\nfunction animateTarget(visualElement, definition, { delay = 0, transitionOverride, type } = {}) {\n let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = visualElement.makeTargetAnimatable(definition);\n const willChange = visualElement.getValue(\"willChange\");\n if (transitionOverride)\n transition = transitionOverride;\n const animations = [];\n const animationTypeState = type &&\n visualElement.animationState &&\n visualElement.animationState.getState()[type];\n for (const key in target) {\n const value = visualElement.getValue(key);\n const valueTarget = target[key];\n if (!value ||\n valueTarget === undefined ||\n (animationTypeState &&\n shouldBlockAnimation(animationTypeState, key))) {\n continue;\n }\n const valueTransition = {\n delay,\n elapsed: 0,\n ...getValueTransition(transition || {}, key),\n };\n /**\n * If this is the first time a value is being animated, check\n * to see if we're handling off from an existing animation.\n */\n if (window.HandoffAppearAnimations) {\n const appearId = visualElement.getProps()[optimizedAppearDataAttribute];\n if (appearId) {\n const elapsed = window.HandoffAppearAnimations(appearId, key, value, frame);\n if (elapsed !== null) {\n valueTransition.elapsed = elapsed;\n valueTransition.isHandoff = true;\n }\n }\n }\n let canSkip = !valueTransition.isHandoff &&\n !hasKeyframesChanged(value, valueTarget);\n if (valueTransition.type === \"spring\" &&\n (value.getVelocity() || valueTransition.velocity)) {\n canSkip = false;\n }\n /**\n * Temporarily disable skipping animations if there's an animation in\n * progress. Better would be to track the current target of a value\n * and compare that against valueTarget.\n */\n if (value.animation) {\n canSkip = false;\n }\n if (canSkip)\n continue;\n value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && transformProps.has(key)\n ? { type: false }\n : valueTransition));\n const animation = value.animation;\n if (isWillChangeMotionValue(willChange)) {\n willChange.add(key);\n animation.then(() => willChange.remove(key));\n }\n animations.push(animation);\n }\n if (transitionEnd) {\n Promise.all(animations).then(() => {\n transitionEnd && setTarget(visualElement, transitionEnd);\n });\n }\n return animations;\n}\n\nexport { animateTarget };\n","import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs';\nimport { animateTarget } from './visual-element-target.mjs';\n\nfunction animateVariant(visualElement, variant, options = {}) {\n const resolved = resolveVariant(visualElement, variant, options.custom);\n let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};\n if (options.transitionOverride) {\n transition = options.transitionOverride;\n }\n /**\n * If we have a variant, create a callback that runs it as an animation.\n * Otherwise, we resolve a Promise immediately for a composable no-op.\n */\n const getAnimation = resolved\n ? () => Promise.all(animateTarget(visualElement, resolved, options))\n : () => Promise.resolve();\n /**\n * If we have children, create a callback that runs all their animations.\n * Otherwise, we resolve a Promise immediately for a composable no-op.\n */\n const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size\n ? (forwardDelay = 0) => {\n const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;\n return animateChildren(visualElement, variant, delayChildren + forwardDelay, staggerChildren, staggerDirection, options);\n }\n : () => Promise.resolve();\n /**\n * If the transition explicitly defines a \"when\" option, we need to resolve either\n * this animation or all children animations before playing the other.\n */\n const { when } = transition;\n if (when) {\n const [first, last] = when === \"beforeChildren\"\n ? [getAnimation, getChildAnimations]\n : [getChildAnimations, getAnimation];\n return first().then(() => last());\n }\n else {\n return Promise.all([getAnimation(), getChildAnimations(options.delay)]);\n }\n}\nfunction animateChildren(visualElement, variant, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {\n const animations = [];\n const maxStaggerDuration = (visualElement.variantChildren.size - 1) * staggerChildren;\n const generateStaggerDuration = staggerDirection === 1\n ? (i = 0) => i * staggerChildren\n : (i = 0) => maxStaggerDuration - i * staggerChildren;\n Array.from(visualElement.variantChildren)\n .sort(sortByTreeOrder)\n .forEach((child, i) => {\n child.notify(\"AnimationStart\", variant);\n animations.push(animateVariant(child, variant, {\n ...options,\n delay: delayChildren + generateStaggerDuration(i),\n }).then(() => child.notify(\"AnimationComplete\", variant)));\n });\n return Promise.all(animations);\n}\nfunction sortByTreeOrder(a, b) {\n return a.sortNodePosition(b);\n}\n\nexport { animateVariant, sortByTreeOrder };\n","import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs';\nimport { animateTarget } from './visual-element-target.mjs';\nimport { animateVariant } from './visual-element-variant.mjs';\n\nfunction animateVisualElement(visualElement, definition, options = {}) {\n visualElement.notify(\"AnimationStart\", definition);\n let animation;\n if (Array.isArray(definition)) {\n const animations = definition.map((variant) => animateVariant(visualElement, variant, options));\n animation = Promise.all(animations);\n }\n else if (typeof definition === \"string\") {\n animation = animateVariant(visualElement, definition, options);\n }\n else {\n const resolvedDefinition = typeof definition === \"function\"\n ? resolveVariant(visualElement, definition, options.custom)\n : definition;\n animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));\n }\n return animation.then(() => visualElement.notify(\"AnimationComplete\", definition));\n}\n\nexport { animateVisualElement };\n","import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';\nimport { isKeyframesTarget } from '../../animation/utils/is-keyframes-target.mjs';\nimport { shallowCompare } from '../../utils/shallow-compare.mjs';\nimport { isVariantLabel } from './is-variant-label.mjs';\nimport { resolveVariant } from './resolve-dynamic-variants.mjs';\nimport { variantPriorityOrder } from './variant-props.mjs';\nimport { animateVisualElement } from '../../animation/interfaces/visual-element.mjs';\n\nconst reversePriorityOrder = [...variantPriorityOrder].reverse();\nconst numAnimationTypes = variantPriorityOrder.length;\nfunction animateList(visualElement) {\n return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));\n}\nfunction createAnimationState(visualElement) {\n let animate = animateList(visualElement);\n const state = createState();\n let isInitialRender = true;\n /**\n * This function will be used to reduce the animation definitions for\n * each active animation type into an object of resolved values for it.\n */\n const buildResolvedTypeValues = (acc, definition) => {\n const resolved = resolveVariant(visualElement, definition);\n if (resolved) {\n const { transition, transitionEnd, ...target } = resolved;\n acc = { ...acc, ...target, ...transitionEnd };\n }\n return acc;\n };\n /**\n * This just allows us to inject mocked animation functions\n * @internal\n */\n function setAnimateFunction(makeAnimator) {\n animate = makeAnimator(visualElement);\n }\n /**\n * When we receive new props, we need to:\n * 1. Create a list of protected keys for each type. This is a directory of\n * value keys that are currently being \"handled\" by types of a higher priority\n * so that whenever an animation is played of a given type, these values are\n * protected from being animated.\n * 2. Determine if an animation type needs animating.\n * 3. Determine if any values have been removed from a type and figure out\n * what to animate those to.\n */\n function animateChanges(options, changedActiveType) {\n const props = visualElement.getProps();\n const context = visualElement.getVariantContext(true) || {};\n /**\n * A list of animations that we'll build into as we iterate through the animation\n * types. This will get executed at the end of the function.\n */\n const animations = [];\n /**\n * Keep track of which values have been removed. Then, as we hit lower priority\n * animation types, we can check if they contain removed values and animate to that.\n */\n const removedKeys = new Set();\n /**\n * A dictionary of all encountered keys. This is an object to let us build into and\n * copy it without iteration. Each time we hit an animation type we set its protected\n * keys - the keys its not allowed to animate - to the latest version of this object.\n */\n let encounteredKeys = {};\n /**\n * If a variant has been removed at a given index, and this component is controlling\n * variant animations, we want to ensure lower-priority variants are forced to animate.\n */\n let removedVariantIndex = Infinity;\n /**\n * Iterate through all animation types in reverse priority order. For each, we want to\n * detect which values it's handling and whether or not they've changed (and therefore\n * need to be animated). If any values have been removed, we want to detect those in\n * lower priority props and flag for animation.\n */\n for (let i = 0; i < numAnimationTypes; i++) {\n const type = reversePriorityOrder[i];\n const typeState = state[type];\n const prop = props[type] !== undefined ? props[type] : context[type];\n const propIsVariant = isVariantLabel(prop);\n /**\n * If this type has *just* changed isActive status, set activeDelta\n * to that status. Otherwise set to null.\n */\n const activeDelta = type === changedActiveType ? typeState.isActive : null;\n if (activeDelta === false)\n removedVariantIndex = i;\n /**\n * If this prop is an inherited variant, rather than been set directly on the\n * component itself, we want to make sure we allow the parent to trigger animations.\n *\n * TODO: Can probably change this to a !isControllingVariants check\n */\n let isInherited = prop === context[type] && prop !== props[type] && propIsVariant;\n /**\n *\n */\n if (isInherited &&\n isInitialRender &&\n visualElement.manuallyAnimateOnMount) {\n isInherited = false;\n }\n /**\n * Set all encountered keys so far as the protected keys for this type. This will\n * be any key that has been animated or otherwise handled by active, higher-priortiy types.\n */\n typeState.protectedKeys = { ...encounteredKeys };\n // Check if we can skip analysing this prop early\n if (\n // If it isn't active and hasn't *just* been set as inactive\n (!typeState.isActive && activeDelta === null) ||\n // If we didn't and don't have any defined prop for this animation type\n (!prop && !typeState.prevProp) ||\n // Or if the prop doesn't define an animation\n isAnimationControls(prop) ||\n typeof prop === \"boolean\") {\n continue;\n }\n /**\n * As we go look through the values defined on this type, if we detect\n * a changed value or a value that was removed in a higher priority, we set\n * this to true and add this prop to the animation list.\n */\n const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);\n let shouldAnimateType = variantDidChange ||\n // If we're making this variant active, we want to always make it active\n (type === changedActiveType &&\n typeState.isActive &&\n !isInherited &&\n propIsVariant) ||\n // If we removed a higher-priority variant (i is in reverse order)\n (i > removedVariantIndex && propIsVariant);\n let handledRemovedValues = false;\n /**\n * As animations can be set as variant lists, variants or target objects, we\n * coerce everything to an array if it isn't one already\n */\n const definitionList = Array.isArray(prop) ? prop : [prop];\n /**\n * Build an object of all the resolved values. We'll use this in the subsequent\n * animateChanges calls to determine whether a value has changed.\n */\n let resolvedValues = definitionList.reduce(buildResolvedTypeValues, {});\n if (activeDelta === false)\n resolvedValues = {};\n /**\n * Now we need to loop through all the keys in the prev prop and this prop,\n * and decide:\n * 1. If the value has changed, and needs animating\n * 2. If it has been removed, and needs adding to the removedKeys set\n * 3. If it has been removed in a higher priority type and needs animating\n * 4. If it hasn't been removed in a higher priority but hasn't changed, and\n * needs adding to the type's protectedKeys list.\n */\n const { prevResolvedValues = {} } = typeState;\n const allKeys = {\n ...prevResolvedValues,\n ...resolvedValues,\n };\n const markToAnimate = (key) => {\n shouldAnimateType = true;\n if (removedKeys.has(key)) {\n handledRemovedValues = true;\n removedKeys.delete(key);\n }\n typeState.needsAnimating[key] = true;\n };\n for (const key in allKeys) {\n const next = resolvedValues[key];\n const prev = prevResolvedValues[key];\n // If we've already handled this we can just skip ahead\n if (encounteredKeys.hasOwnProperty(key))\n continue;\n /**\n * If the value has changed, we probably want to animate it.\n */\n let valueHasChanged = false;\n if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {\n valueHasChanged = !shallowCompare(next, prev);\n }\n else {\n valueHasChanged = next !== prev;\n }\n if (valueHasChanged) {\n if (next !== undefined) {\n // If next is defined and doesn't equal prev, it needs animating\n markToAnimate(key);\n }\n else {\n // If it's undefined, it's been removed.\n removedKeys.add(key);\n }\n }\n else if (next !== undefined && removedKeys.has(key)) {\n /**\n * If next hasn't changed and it isn't undefined, we want to check if it's\n * been removed by a higher priority\n */\n markToAnimate(key);\n }\n else {\n /**\n * If it hasn't changed, we add it to the list of protected values\n * to ensure it doesn't get animated.\n */\n typeState.protectedKeys[key] = true;\n }\n }\n /**\n * Update the typeState so next time animateChanges is called we can compare the\n * latest prop and resolvedValues to these.\n */\n typeState.prevProp = prop;\n typeState.prevResolvedValues = resolvedValues;\n /**\n *\n */\n if (typeState.isActive) {\n encounteredKeys = { ...encounteredKeys, ...resolvedValues };\n }\n if (isInitialRender && visualElement.blockInitialAnimation) {\n shouldAnimateType = false;\n }\n /**\n * If this is an inherited prop we want to hard-block animations\n */\n if (shouldAnimateType && (!isInherited || handledRemovedValues)) {\n animations.push(...definitionList.map((animation) => ({\n animation: animation,\n options: { type, ...options },\n })));\n }\n }\n /**\n * If there are some removed value that haven't been dealt with,\n * we need to create a new animation that falls back either to the value\n * defined in the style prop, or the last read value.\n */\n if (removedKeys.size) {\n const fallbackAnimation = {};\n removedKeys.forEach((key) => {\n const fallbackTarget = visualElement.getBaseTarget(key);\n if (fallbackTarget !== undefined) {\n fallbackAnimation[key] = fallbackTarget;\n }\n });\n animations.push({ animation: fallbackAnimation });\n }\n let shouldAnimate = Boolean(animations.length);\n if (isInitialRender &&\n (props.initial === false || props.initial === props.animate) &&\n !visualElement.manuallyAnimateOnMount) {\n shouldAnimate = false;\n }\n isInitialRender = false;\n return shouldAnimate ? animate(animations) : Promise.resolve();\n }\n /**\n * Change whether a certain animation type is active.\n */\n function setActive(type, isActive, options) {\n var _a;\n // If the active state hasn't changed, we can safely do nothing here\n if (state[type].isActive === isActive)\n return Promise.resolve();\n // Propagate active change to children\n (_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach((child) => { var _a; return (_a = child.animationState) === null || _a === void 0 ? void 0 : _a.setActive(type, isActive); });\n state[type].isActive = isActive;\n const animations = animateChanges(options, type);\n for (const key in state) {\n state[key].protectedKeys = {};\n }\n return animations;\n }\n return {\n animateChanges,\n setActive,\n setAnimateFunction,\n getState: () => state,\n };\n}\nfunction checkVariantsDidChange(prev, next) {\n if (typeof next === \"string\") {\n return next !== prev;\n }\n else if (Array.isArray(next)) {\n return !shallowCompare(next, prev);\n }\n return false;\n}\nfunction createTypeState(isActive = false) {\n return {\n isActive,\n protectedKeys: {},\n needsAnimating: {},\n prevResolvedValues: {},\n };\n}\nfunction createState() {\n return {\n animate: createTypeState(true),\n whileInView: createTypeState(),\n whileHover: createTypeState(),\n whileTap: createTypeState(),\n whileDrag: createTypeState(),\n whileFocus: createTypeState(),\n exit: createTypeState(),\n };\n}\n\nexport { checkVariantsDidChange, createAnimationState };\n","import { isAnimationControls } from '../../../animation/utils/is-animation-controls.mjs';\nimport { createAnimationState } from '../../../render/utils/animation-state.mjs';\nimport { Feature } from '../Feature.mjs';\n\nclass AnimationFeature extends Feature {\n /**\n * We dynamically generate the AnimationState manager as it contains a reference\n * to the underlying animation library. We only want to load that if we load this,\n * so people can optionally code split it out using the `m` component.\n */\n constructor(node) {\n super(node);\n node.animationState || (node.animationState = createAnimationState(node));\n }\n updateAnimationControlsSubscription() {\n const { animate } = this.node.getProps();\n this.unmount();\n if (isAnimationControls(animate)) {\n this.unmount = animate.subscribe(this.node);\n }\n }\n /**\n * Subscribe any provided AnimationControls to the component's VisualElement\n */\n mount() {\n this.updateAnimationControlsSubscription();\n }\n update() {\n const { animate } = this.node.getProps();\n const { animate: prevAnimate } = this.node.prevProps || {};\n if (animate !== prevAnimate) {\n this.updateAnimationControlsSubscription();\n }\n }\n unmount() { }\n}\n\nexport { AnimationFeature };\n","import { Feature } from '../Feature.mjs';\n\nlet id = 0;\nclass ExitAnimationFeature extends Feature {\n constructor() {\n super(...arguments);\n this.id = id++;\n }\n update() {\n if (!this.node.presenceContext)\n return;\n const { isPresent, onExitComplete, custom } = this.node.presenceContext;\n const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};\n if (!this.node.animationState || isPresent === prevIsPresent) {\n return;\n }\n const exitAnimation = this.node.animationState.setActive(\"exit\", !isPresent, { custom: custom !== null && custom !== void 0 ? custom : this.node.getProps().custom });\n if (onExitComplete && !isPresent) {\n exitAnimation.then(() => onExitComplete(this.id));\n }\n }\n mount() {\n const { register } = this.node.presenceContext || {};\n if (register) {\n this.unmount = register(this.id);\n }\n }\n unmount() { }\n}\n\nexport { ExitAnimationFeature };\n","import { AnimationFeature } from './animation/index.mjs';\nimport { ExitAnimationFeature } from './animation/exit.mjs';\n\nconst animations = {\n animation: {\n Feature: AnimationFeature,\n },\n exit: {\n Feature: ExitAnimationFeature,\n },\n};\n\nexport { animations };\n","const distance = (a, b) => Math.abs(a - b);\nfunction distance2D(a, b) {\n // Multi-dimensional\n const xDelta = distance(a.x, b.x);\n const yDelta = distance(a.y, b.y);\n return Math.sqrt(xDelta ** 2 + yDelta ** 2);\n}\n\nexport { distance, distance2D };\n","import { extractEventInfo } from '../../events/event-info.mjs';\nimport { secondsToMilliseconds, millisecondsToSeconds } from '../../utils/time-conversion.mjs';\nimport { addPointerEvent } from '../../events/add-pointer-event.mjs';\nimport { pipe } from '../../utils/pipe.mjs';\nimport { distance2D } from '../../utils/distance.mjs';\nimport { isPrimaryPointer } from '../../events/utils/is-primary-pointer.mjs';\nimport { frame, cancelFrame, frameData } from '../../frameloop/frame.mjs';\n\n/**\n * @internal\n */\nclass PanSession {\n constructor(event, handlers, { transformPagePoint, contextWindow, dragSnapToOrigin = false } = {}) {\n /**\n * @internal\n */\n this.startEvent = null;\n /**\n * @internal\n */\n this.lastMoveEvent = null;\n /**\n * @internal\n */\n this.lastMoveEventInfo = null;\n /**\n * @internal\n */\n this.handlers = {};\n /**\n * @internal\n */\n this.contextWindow = window;\n this.updatePoint = () => {\n if (!(this.lastMoveEvent && this.lastMoveEventInfo))\n return;\n const info = getPanInfo(this.lastMoveEventInfo, this.history);\n const isPanStarted = this.startEvent !== null;\n // Only start panning if the offset is larger than 3 pixels. If we make it\n // any larger than this we'll want to reset the pointer history\n // on the first update to avoid visual snapping to the cursoe.\n const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= 3;\n if (!isPanStarted && !isDistancePastThreshold)\n return;\n const { point } = info;\n const { timestamp } = frameData;\n this.history.push({ ...point, timestamp });\n const { onStart, onMove } = this.handlers;\n if (!isPanStarted) {\n onStart && onStart(this.lastMoveEvent, info);\n this.startEvent = this.lastMoveEvent;\n }\n onMove && onMove(this.lastMoveEvent, info);\n };\n this.handlePointerMove = (event, info) => {\n this.lastMoveEvent = event;\n this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint);\n // Throttle mouse move event to once per frame\n frame.update(this.updatePoint, true);\n };\n this.handlePointerUp = (event, info) => {\n this.end();\n const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;\n if (this.dragSnapToOrigin)\n resumeAnimation && resumeAnimation();\n if (!(this.lastMoveEvent && this.lastMoveEventInfo))\n return;\n const panInfo = getPanInfo(event.type === \"pointercancel\"\n ? this.lastMoveEventInfo\n : transformPoint(info, this.transformPagePoint), this.history);\n if (this.startEvent && onEnd) {\n onEnd(event, panInfo);\n }\n onSessionEnd && onSessionEnd(event, panInfo);\n };\n // If we have more than one touch, don't start detecting this gesture\n if (!isPrimaryPointer(event))\n return;\n this.dragSnapToOrigin = dragSnapToOrigin;\n this.handlers = handlers;\n this.transformPagePoint = transformPagePoint;\n this.contextWindow = contextWindow || window;\n const info = extractEventInfo(event);\n const initialInfo = transformPoint(info, this.transformPagePoint);\n const { point } = initialInfo;\n const { timestamp } = frameData;\n this.history = [{ ...point, timestamp }];\n const { onSessionStart } = handlers;\n onSessionStart &&\n onSessionStart(event, getPanInfo(initialInfo, this.history));\n this.removeListeners = pipe(addPointerEvent(this.contextWindow, \"pointermove\", this.handlePointerMove), addPointerEvent(this.contextWindow, \"pointerup\", this.handlePointerUp), addPointerEvent(this.contextWindow, \"pointercancel\", this.handlePointerUp));\n }\n updateHandlers(handlers) {\n this.handlers = handlers;\n }\n end() {\n this.removeListeners && this.removeListeners();\n cancelFrame(this.updatePoint);\n }\n}\nfunction transformPoint(info, transformPagePoint) {\n return transformPagePoint ? { point: transformPagePoint(info.point) } : info;\n}\nfunction subtractPoint(a, b) {\n return { x: a.x - b.x, y: a.y - b.y };\n}\nfunction getPanInfo({ point }, history) {\n return {\n point,\n delta: subtractPoint(point, lastDevicePoint(history)),\n offset: subtractPoint(point, startDevicePoint(history)),\n velocity: getVelocity(history, 0.1),\n };\n}\nfunction startDevicePoint(history) {\n return history[0];\n}\nfunction lastDevicePoint(history) {\n return history[history.length - 1];\n}\nfunction getVelocity(history, timeDelta) {\n if (history.length < 2) {\n return { x: 0, y: 0 };\n }\n let i = history.length - 1;\n let timestampedPoint = null;\n const lastPoint = lastDevicePoint(history);\n while (i >= 0) {\n timestampedPoint = history[i];\n if (lastPoint.timestamp - timestampedPoint.timestamp >\n secondsToMilliseconds(timeDelta)) {\n break;\n }\n i--;\n }\n if (!timestampedPoint) {\n return { x: 0, y: 0 };\n }\n const time = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp);\n if (time === 0) {\n return { x: 0, y: 0 };\n }\n const currentVelocity = {\n x: (lastPoint.x - timestampedPoint.x) / time,\n y: (lastPoint.y - timestampedPoint.y) / time,\n };\n if (currentVelocity.x === Infinity) {\n currentVelocity.x = 0;\n }\n if (currentVelocity.y === Infinity) {\n currentVelocity.y = 0;\n }\n return currentVelocity;\n}\n\nexport { PanSession };\n","import { mix } from '../../utils/mix.mjs';\n\nfunction calcLength(axis) {\n return axis.max - axis.min;\n}\nfunction isNear(value, target = 0, maxDistance = 0.01) {\n return Math.abs(value - target) <= maxDistance;\n}\nfunction calcAxisDelta(delta, source, target, origin = 0.5) {\n delta.origin = origin;\n delta.originPoint = mix(source.min, source.max, delta.origin);\n delta.scale = calcLength(target) / calcLength(source);\n if (isNear(delta.scale, 1, 0.0001) || isNaN(delta.scale))\n delta.scale = 1;\n delta.translate =\n mix(target.min, target.max, delta.origin) - delta.originPoint;\n if (isNear(delta.translate) || isNaN(delta.translate))\n delta.translate = 0;\n}\nfunction calcBoxDelta(delta, source, target, origin) {\n calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);\n calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);\n}\nfunction calcRelativeAxis(target, relative, parent) {\n target.min = parent.min + relative.min;\n target.max = target.min + calcLength(relative);\n}\nfunction calcRelativeBox(target, relative, parent) {\n calcRelativeAxis(target.x, relative.x, parent.x);\n calcRelativeAxis(target.y, relative.y, parent.y);\n}\nfunction calcRelativeAxisPosition(target, layout, parent) {\n target.min = layout.min - parent.min;\n target.max = target.min + calcLength(layout);\n}\nfunction calcRelativePosition(target, layout, parent) {\n calcRelativeAxisPosition(target.x, layout.x, parent.x);\n calcRelativeAxisPosition(target.y, layout.y, parent.y);\n}\n\nexport { calcAxisDelta, calcBoxDelta, calcLength, calcRelativeAxis, calcRelativeAxisPosition, calcRelativeBox, calcRelativePosition, isNear };\n","import { progress } from '../../../utils/progress.mjs';\nimport { calcLength } from '../../../projection/geometry/delta-calc.mjs';\nimport { clamp } from '../../../utils/clamp.mjs';\nimport { mix } from '../../../utils/mix.mjs';\n\n/**\n * Apply constraints to a point. These constraints are both physical along an\n * axis, and an elastic factor that determines how much to constrain the point\n * by if it does lie outside the defined parameters.\n */\nfunction applyConstraints(point, { min, max }, elastic) {\n if (min !== undefined && point < min) {\n // If we have a min point defined, and this is outside of that, constrain\n point = elastic ? mix(min, point, elastic.min) : Math.max(point, min);\n }\n else if (max !== undefined && point > max) {\n // If we have a max point defined, and this is outside of that, constrain\n point = elastic ? mix(max, point, elastic.max) : Math.min(point, max);\n }\n return point;\n}\n/**\n * Calculate constraints in terms of the viewport when defined relatively to the\n * measured axis. This is measured from the nearest edge, so a max constraint of 200\n * on an axis with a max value of 300 would return a constraint of 500 - axis length\n */\nfunction calcRelativeAxisConstraints(axis, min, max) {\n return {\n min: min !== undefined ? axis.min + min : undefined,\n max: max !== undefined\n ? axis.max + max - (axis.max - axis.min)\n : undefined,\n };\n}\n/**\n * Calculate constraints in terms of the viewport when\n * defined relatively to the measured bounding box.\n */\nfunction calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {\n return {\n x: calcRelativeAxisConstraints(layoutBox.x, left, right),\n y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),\n };\n}\n/**\n * Calculate viewport constraints when defined as another viewport-relative axis\n */\nfunction calcViewportAxisConstraints(layoutAxis, constraintsAxis) {\n let min = constraintsAxis.min - layoutAxis.min;\n let max = constraintsAxis.max - layoutAxis.max;\n // If the constraints axis is actually smaller than the layout axis then we can\n // flip the constraints\n if (constraintsAxis.max - constraintsAxis.min <\n layoutAxis.max - layoutAxis.min) {\n [min, max] = [max, min];\n }\n return { min, max };\n}\n/**\n * Calculate viewport constraints when defined as another viewport-relative box\n */\nfunction calcViewportConstraints(layoutBox, constraintsBox) {\n return {\n x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),\n y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),\n };\n}\n/**\n * Calculate a transform origin relative to the source axis, between 0-1, that results\n * in an asthetically pleasing scale/transform needed to project from source to target.\n */\nfunction calcOrigin(source, target) {\n let origin = 0.5;\n const sourceLength = calcLength(source);\n const targetLength = calcLength(target);\n if (targetLength > sourceLength) {\n origin = progress(target.min, target.max - sourceLength, source.min);\n }\n else if (sourceLength > targetLength) {\n origin = progress(source.min, source.max - targetLength, target.min);\n }\n return clamp(0, 1, origin);\n}\n/**\n * Rebase the calculated viewport constraints relative to the layout.min point.\n */\nfunction rebaseAxisConstraints(layout, constraints) {\n const relativeConstraints = {};\n if (constraints.min !== undefined) {\n relativeConstraints.min = constraints.min - layout.min;\n }\n if (constraints.max !== undefined) {\n relativeConstraints.max = constraints.max - layout.min;\n }\n return relativeConstraints;\n}\nconst defaultElastic = 0.35;\n/**\n * Accepts a dragElastic prop and returns resolved elastic values for each axis.\n */\nfunction resolveDragElastic(dragElastic = defaultElastic) {\n if (dragElastic === false) {\n dragElastic = 0;\n }\n else if (dragElastic === true) {\n dragElastic = defaultElastic;\n }\n return {\n x: resolveAxisElastic(dragElastic, \"left\", \"right\"),\n y: resolveAxisElastic(dragElastic, \"top\", \"bottom\"),\n };\n}\nfunction resolveAxisElastic(dragElastic, minLabel, maxLabel) {\n return {\n min: resolvePointElastic(dragElastic, minLabel),\n max: resolvePointElastic(dragElastic, maxLabel),\n };\n}\nfunction resolvePointElastic(dragElastic, label) {\n return typeof dragElastic === \"number\"\n ? dragElastic\n : dragElastic[label] || 0;\n}\n\nexport { applyConstraints, calcOrigin, calcRelativeAxisConstraints, calcRelativeConstraints, calcViewportAxisConstraints, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, resolveAxisElastic, resolveDragElastic, resolvePointElastic };\n","const createAxisDelta = () => ({\n translate: 0,\n scale: 1,\n origin: 0,\n originPoint: 0,\n});\nconst createDelta = () => ({\n x: createAxisDelta(),\n y: createAxisDelta(),\n});\nconst createAxis = () => ({ min: 0, max: 0 });\nconst createBox = () => ({\n x: createAxis(),\n y: createAxis(),\n});\n\nexport { createAxis, createAxisDelta, createBox, createDelta };\n","function eachAxis(callback) {\n return [callback(\"x\"), callback(\"y\")];\n}\n\nexport { eachAxis };\n","/**\n * Bounding boxes tend to be defined as top, left, right, bottom. For various operations\n * it's easier to consider each axis individually. This function returns a bounding box\n * as a map of single-axis min/max values.\n */\nfunction convertBoundingBoxToBox({ top, left, right, bottom, }) {\n return {\n x: { min: left, max: right },\n y: { min: top, max: bottom },\n };\n}\nfunction convertBoxToBoundingBox({ x, y }) {\n return { top: y.min, right: x.max, bottom: y.max, left: x.min };\n}\n/**\n * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function\n * provided by Framer to allow measured points to be corrected for device scaling. This is used\n * when measuring DOM elements and DOM event points.\n */\nfunction transformBoxPoints(point, transformPoint) {\n if (!transformPoint)\n return point;\n const topLeft = transformPoint({ x: point.left, y: point.top });\n const bottomRight = transformPoint({ x: point.right, y: point.bottom });\n return {\n top: topLeft.y,\n left: topLeft.x,\n bottom: bottomRight.y,\n right: bottomRight.x,\n };\n}\n\nexport { convertBoundingBoxToBox, convertBoxToBoundingBox, transformBoxPoints };\n","function isIdentityScale(scale) {\n return scale === undefined || scale === 1;\n}\nfunction hasScale({ scale, scaleX, scaleY }) {\n return (!isIdentityScale(scale) ||\n !isIdentityScale(scaleX) ||\n !isIdentityScale(scaleY));\n}\nfunction hasTransform(values) {\n return (hasScale(values) ||\n has2DTranslate(values) ||\n values.z ||\n values.rotate ||\n values.rotateX ||\n values.rotateY);\n}\nfunction has2DTranslate(values) {\n return is2DTranslate(values.x) || is2DTranslate(values.y);\n}\nfunction is2DTranslate(value) {\n return value && value !== \"0%\";\n}\n\nexport { has2DTranslate, hasScale, hasTransform };\n","import { mix } from '../../utils/mix.mjs';\nimport { hasTransform } from '../utils/has-transform.mjs';\n\n/**\n * Scales a point based on a factor and an originPoint\n */\nfunction scalePoint(point, scale, originPoint) {\n const distanceFromOrigin = point - originPoint;\n const scaled = scale * distanceFromOrigin;\n return originPoint + scaled;\n}\n/**\n * Applies a translate/scale delta to a point\n */\nfunction applyPointDelta(point, translate, scale, originPoint, boxScale) {\n if (boxScale !== undefined) {\n point = scalePoint(point, boxScale, originPoint);\n }\n return scalePoint(point, scale, originPoint) + translate;\n}\n/**\n * Applies a translate/scale delta to an axis\n */\nfunction applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) {\n axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale);\n axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale);\n}\n/**\n * Applies a translate/scale delta to a box\n */\nfunction applyBoxDelta(box, { x, y }) {\n applyAxisDelta(box.x, x.translate, x.scale, x.originPoint);\n applyAxisDelta(box.y, y.translate, y.scale, y.originPoint);\n}\n/**\n * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms\n * in a tree upon our box before then calculating how to project it into our desired viewport-relative box\n *\n * This is the final nested loop within updateLayoutDelta for future refactoring\n */\nfunction applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {\n const treeLength = treePath.length;\n if (!treeLength)\n return;\n // Reset the treeScale\n treeScale.x = treeScale.y = 1;\n let node;\n let delta;\n for (let i = 0; i < treeLength; i++) {\n node = treePath[i];\n delta = node.projectionDelta;\n /**\n * TODO: Prefer to remove this, but currently we have motion components with\n * display: contents in Framer.\n */\n const instance = node.instance;\n if (instance &&\n instance.style &&\n instance.style.display === \"contents\") {\n continue;\n }\n if (isSharedTransition &&\n node.options.layoutScroll &&\n node.scroll &&\n node !== node.root) {\n transformBox(box, {\n x: -node.scroll.offset.x,\n y: -node.scroll.offset.y,\n });\n }\n if (delta) {\n // Incoporate each ancestor's scale into a culmulative treeScale for this component\n treeScale.x *= delta.x.scale;\n treeScale.y *= delta.y.scale;\n // Apply each ancestor's calculated delta into this component's recorded layout box\n applyBoxDelta(box, delta);\n }\n if (isSharedTransition && hasTransform(node.latestValues)) {\n transformBox(box, node.latestValues);\n }\n }\n /**\n * Snap tree scale back to 1 if it's within a non-perceivable threshold.\n * This will help reduce useless scales getting rendered.\n */\n treeScale.x = snapToDefault(treeScale.x);\n treeScale.y = snapToDefault(treeScale.y);\n}\nfunction snapToDefault(scale) {\n if (Number.isInteger(scale))\n return scale;\n return scale > 1.0000000000001 || scale < 0.999999999999 ? scale : 1;\n}\nfunction translateAxis(axis, distance) {\n axis.min = axis.min + distance;\n axis.max = axis.max + distance;\n}\n/**\n * Apply a transform to an axis from the latest resolved motion values.\n * This function basically acts as a bridge between a flat motion value map\n * and applyAxisDelta\n */\nfunction transformAxis(axis, transforms, [key, scaleKey, originKey]) {\n const axisOrigin = transforms[originKey] !== undefined ? transforms[originKey] : 0.5;\n const originPoint = mix(axis.min, axis.max, axisOrigin);\n // Apply the axis delta to the final axis\n applyAxisDelta(axis, transforms[key], transforms[scaleKey], originPoint, transforms.scale);\n}\n/**\n * The names of the motion values we want to apply as translation, scale and origin.\n */\nconst xKeys = [\"x\", \"scaleX\", \"originX\"];\nconst yKeys = [\"y\", \"scaleY\", \"originY\"];\n/**\n * Apply a transform to a box from the latest resolved motion values.\n */\nfunction transformBox(box, transform) {\n transformAxis(box.x, transform, xKeys);\n transformAxis(box.y, transform, yKeys);\n}\n\nexport { applyAxisDelta, applyBoxDelta, applyPointDelta, applyTreeDeltas, scalePoint, transformAxis, transformBox, translateAxis };\n","import { convertBoundingBoxToBox, transformBoxPoints } from '../geometry/conversion.mjs';\nimport { translateAxis } from '../geometry/delta-apply.mjs';\n\nfunction measureViewportBox(instance, transformPoint) {\n return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));\n}\nfunction measurePageBox(element, rootProjectionNode, transformPagePoint) {\n const viewportBox = measureViewportBox(element, transformPagePoint);\n const { scroll } = rootProjectionNode;\n if (scroll) {\n translateAxis(viewportBox.x, scroll.offset.x);\n translateAxis(viewportBox.y, scroll.offset.y);\n }\n return viewportBox;\n}\n\nexport { measurePageBox, measureViewportBox };\n","// Fixes https://github.com/framer/motion/issues/2270\nconst getContextWindow = ({ current }) => {\n return current ? current.ownerDocument.defaultView : null;\n};\n\nexport { getContextWindow };\n","import { invariant } from '../../utils/errors.mjs';\nimport { PanSession } from '../pan/PanSession.mjs';\nimport { getGlobalLock } from './utils/lock.mjs';\nimport { isRefObject } from '../../utils/is-ref-object.mjs';\nimport { addPointerEvent } from '../../events/add-pointer-event.mjs';\nimport { applyConstraints, calcRelativeConstraints, resolveDragElastic, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, calcOrigin } from './utils/constraints.mjs';\nimport { createBox } from '../../projection/geometry/models.mjs';\nimport { eachAxis } from '../../projection/utils/each-axis.mjs';\nimport { measurePageBox } from '../../projection/utils/measure.mjs';\nimport { extractEventInfo } from '../../events/event-info.mjs';\nimport { convertBoxToBoundingBox, convertBoundingBoxToBox } from '../../projection/geometry/conversion.mjs';\nimport { addDomEvent } from '../../events/add-dom-event.mjs';\nimport { calcLength } from '../../projection/geometry/delta-calc.mjs';\nimport { mix } from '../../utils/mix.mjs';\nimport { percent } from '../../value/types/numbers/units.mjs';\nimport { animateMotionValue } from '../../animation/interfaces/motion-value.mjs';\nimport { getContextWindow } from '../../utils/get-context-window.mjs';\nimport { frame } from '../../frameloop/frame.mjs';\n\nconst elementDragControls = new WeakMap();\n/**\n *\n */\n// let latestPointerEvent: PointerEvent\nclass VisualElementDragControls {\n constructor(visualElement) {\n // This is a reference to the global drag gesture lock, ensuring only one component\n // can \"capture\" the drag of one or both axes.\n // TODO: Look into moving this into pansession?\n this.openGlobalLock = null;\n this.isDragging = false;\n this.currentDirection = null;\n this.originPoint = { x: 0, y: 0 };\n /**\n * The permitted boundaries of travel, in pixels.\n */\n this.constraints = false;\n this.hasMutatedConstraints = false;\n /**\n * The per-axis resolved elastic values.\n */\n this.elastic = createBox();\n this.visualElement = visualElement;\n }\n start(originEvent, { snapToCursor = false } = {}) {\n /**\n * Don't start dragging if this component is exiting\n */\n const { presenceContext } = this.visualElement;\n if (presenceContext && presenceContext.isPresent === false)\n return;\n const onSessionStart = (event) => {\n const { dragSnapToOrigin } = this.getProps();\n // Stop or pause any animations on both axis values immediately. This allows the user to throw and catch\n // the component.\n dragSnapToOrigin ? this.pauseAnimation() : this.stopAnimation();\n if (snapToCursor) {\n this.snapToCursor(extractEventInfo(event, \"page\").point);\n }\n };\n const onStart = (event, info) => {\n // Attempt to grab the global drag gesture lock - maybe make this part of PanSession\n const { drag, dragPropagation, onDragStart } = this.getProps();\n if (drag && !dragPropagation) {\n if (this.openGlobalLock)\n this.openGlobalLock();\n this.openGlobalLock = getGlobalLock(drag);\n // If we don 't have the lock, don't start dragging\n if (!this.openGlobalLock)\n return;\n }\n this.isDragging = true;\n this.currentDirection = null;\n this.resolveConstraints();\n if (this.visualElement.projection) {\n this.visualElement.projection.isAnimationBlocked = true;\n this.visualElement.projection.target = undefined;\n }\n /**\n * Record gesture origin\n */\n eachAxis((axis) => {\n let current = this.getAxisMotionValue(axis).get() || 0;\n /**\n * If the MotionValue is a percentage value convert to px\n */\n if (percent.test(current)) {\n const { projection } = this.visualElement;\n if (projection && projection.layout) {\n const measuredAxis = projection.layout.layoutBox[axis];\n if (measuredAxis) {\n const length = calcLength(measuredAxis);\n current = length * (parseFloat(current) / 100);\n }\n }\n }\n this.originPoint[axis] = current;\n });\n // Fire onDragStart event\n if (onDragStart) {\n frame.update(() => onDragStart(event, info), false, true);\n }\n const { animationState } = this.visualElement;\n animationState && animationState.setActive(\"whileDrag\", true);\n };\n const onMove = (event, info) => {\n // latestPointerEvent = event\n const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps();\n // If we didn't successfully receive the gesture lock, early return.\n if (!dragPropagation && !this.openGlobalLock)\n return;\n const { offset } = info;\n // Attempt to detect drag direction if directionLock is true\n if (dragDirectionLock && this.currentDirection === null) {\n this.currentDirection = getCurrentDirection(offset);\n // If we've successfully set a direction, notify listener\n if (this.currentDirection !== null) {\n onDirectionLock && onDirectionLock(this.currentDirection);\n }\n return;\n }\n // Update each point with the latest position\n this.updateAxis(\"x\", info.point, offset);\n this.updateAxis(\"y\", info.point, offset);\n /**\n * Ideally we would leave the renderer to fire naturally at the end of\n * this frame but if the element is about to change layout as the result\n * of a re-render we want to ensure the browser can read the latest\n * bounding box to ensure the pointer and element don't fall out of sync.\n */\n this.visualElement.render();\n /**\n * This must fire after the render call as it might trigger a state\n * change which itself might trigger a layout update.\n */\n onDrag && onDrag(event, info);\n };\n const onSessionEnd = (event, info) => this.stop(event, info);\n const resumeAnimation = () => eachAxis((axis) => {\n var _a;\n return this.getAnimationState(axis) === \"paused\" &&\n ((_a = this.getAxisMotionValue(axis).animation) === null || _a === void 0 ? void 0 : _a.play());\n });\n const { dragSnapToOrigin } = this.getProps();\n this.panSession = new PanSession(originEvent, {\n onSessionStart,\n onStart,\n onMove,\n onSessionEnd,\n resumeAnimation,\n }, {\n transformPagePoint: this.visualElement.getTransformPagePoint(),\n dragSnapToOrigin,\n contextWindow: getContextWindow(this.visualElement),\n });\n }\n stop(event, info) {\n const isDragging = this.isDragging;\n this.cancel();\n if (!isDragging)\n return;\n const { velocity } = info;\n this.startAnimation(velocity);\n const { onDragEnd } = this.getProps();\n if (onDragEnd) {\n frame.update(() => onDragEnd(event, info));\n }\n }\n cancel() {\n this.isDragging = false;\n const { projection, animationState } = this.visualElement;\n if (projection) {\n projection.isAnimationBlocked = false;\n }\n this.panSession && this.panSession.end();\n this.panSession = undefined;\n const { dragPropagation } = this.getProps();\n if (!dragPropagation && this.openGlobalLock) {\n this.openGlobalLock();\n this.openGlobalLock = null;\n }\n animationState && animationState.setActive(\"whileDrag\", false);\n }\n updateAxis(axis, _point, offset) {\n const { drag } = this.getProps();\n // If we're not dragging this axis, do an early return.\n if (!offset || !shouldDrag(axis, drag, this.currentDirection))\n return;\n const axisValue = this.getAxisMotionValue(axis);\n let next = this.originPoint[axis] + offset[axis];\n // Apply constraints\n if (this.constraints && this.constraints[axis]) {\n next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);\n }\n axisValue.set(next);\n }\n resolveConstraints() {\n var _a;\n const { dragConstraints, dragElastic } = this.getProps();\n const layout = this.visualElement.projection &&\n !this.visualElement.projection.layout\n ? this.visualElement.projection.measure(false)\n : (_a = this.visualElement.projection) === null || _a === void 0 ? void 0 : _a.layout;\n const prevConstraints = this.constraints;\n if (dragConstraints && isRefObject(dragConstraints)) {\n if (!this.constraints) {\n this.constraints = this.resolveRefConstraints();\n }\n }\n else {\n if (dragConstraints && layout) {\n this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints);\n }\n else {\n this.constraints = false;\n }\n }\n this.elastic = resolveDragElastic(dragElastic);\n /**\n * If we're outputting to external MotionValues, we want to rebase the measured constraints\n * from viewport-relative to component-relative.\n */\n if (prevConstraints !== this.constraints &&\n layout &&\n this.constraints &&\n !this.hasMutatedConstraints) {\n eachAxis((axis) => {\n if (this.getAxisMotionValue(axis)) {\n this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]);\n }\n });\n }\n }\n resolveRefConstraints() {\n const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();\n if (!constraints || !isRefObject(constraints))\n return false;\n const constraintsElement = constraints.current;\n invariant(constraintsElement !== null, \"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.\");\n const { projection } = this.visualElement;\n // TODO\n if (!projection || !projection.layout)\n return false;\n const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());\n let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);\n /**\n * If there's an onMeasureDragConstraints listener we call it and\n * if different constraints are returned, set constraints to that\n */\n if (onMeasureDragConstraints) {\n const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints));\n this.hasMutatedConstraints = !!userConstraints;\n if (userConstraints) {\n measuredConstraints = convertBoundingBoxToBox(userConstraints);\n }\n }\n return measuredConstraints;\n }\n startAnimation(velocity) {\n const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps();\n const constraints = this.constraints || {};\n const momentumAnimations = eachAxis((axis) => {\n if (!shouldDrag(axis, drag, this.currentDirection)) {\n return;\n }\n let transition = (constraints && constraints[axis]) || {};\n if (dragSnapToOrigin)\n transition = { min: 0, max: 0 };\n /**\n * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame\n * of spring animations so we should look into adding a disable spring option to `inertia`.\n * We could do something here where we affect the `bounceStiffness` and `bounceDamping`\n * using the value of `dragElastic`.\n */\n const bounceStiffness = dragElastic ? 200 : 1000000;\n const bounceDamping = dragElastic ? 40 : 10000000;\n const inertia = {\n type: \"inertia\",\n velocity: dragMomentum ? velocity[axis] : 0,\n bounceStiffness,\n bounceDamping,\n timeConstant: 750,\n restDelta: 1,\n restSpeed: 10,\n ...dragTransition,\n ...transition,\n };\n // If we're not animating on an externally-provided `MotionValue` we can use the\n // component's animation controls which will handle interactions with whileHover (etc),\n // otherwise we just have to animate the `MotionValue` itself.\n return this.startAxisValueAnimation(axis, inertia);\n });\n // Run all animations and then resolve the new drag constraints.\n return Promise.all(momentumAnimations).then(onDragTransitionEnd);\n }\n startAxisValueAnimation(axis, transition) {\n const axisValue = this.getAxisMotionValue(axis);\n return axisValue.start(animateMotionValue(axis, axisValue, 0, transition));\n }\n stopAnimation() {\n eachAxis((axis) => this.getAxisMotionValue(axis).stop());\n }\n pauseAnimation() {\n eachAxis((axis) => { var _a; return (_a = this.getAxisMotionValue(axis).animation) === null || _a === void 0 ? void 0 : _a.pause(); });\n }\n getAnimationState(axis) {\n var _a;\n return (_a = this.getAxisMotionValue(axis).animation) === null || _a === void 0 ? void 0 : _a.state;\n }\n /**\n * Drag works differently depending on which props are provided.\n *\n * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.\n * - Otherwise, we apply the delta to the x/y motion values.\n */\n getAxisMotionValue(axis) {\n const dragKey = \"_drag\" + axis.toUpperCase();\n const props = this.visualElement.getProps();\n const externalMotionValue = props[dragKey];\n return externalMotionValue\n ? externalMotionValue\n : this.visualElement.getValue(axis, (props.initial ? props.initial[axis] : undefined) || 0);\n }\n snapToCursor(point) {\n eachAxis((axis) => {\n const { drag } = this.getProps();\n // If we're not dragging this axis, do an early return.\n if (!shouldDrag(axis, drag, this.currentDirection))\n return;\n const { projection } = this.visualElement;\n const axisValue = this.getAxisMotionValue(axis);\n if (projection && projection.layout) {\n const { min, max } = projection.layout.layoutBox[axis];\n axisValue.set(point[axis] - mix(min, max, 0.5));\n }\n });\n }\n /**\n * When the viewport resizes we want to check if the measured constraints\n * have changed and, if so, reposition the element within those new constraints\n * relative to where it was before the resize.\n */\n scalePositionWithinConstraints() {\n if (!this.visualElement.current)\n return;\n const { drag, dragConstraints } = this.getProps();\n const { projection } = this.visualElement;\n if (!isRefObject(dragConstraints) || !projection || !this.constraints)\n return;\n /**\n * Stop current animations as there can be visual glitching if we try to do\n * this mid-animation\n */\n this.stopAnimation();\n /**\n * Record the relative position of the dragged element relative to the\n * constraints box and save as a progress value.\n */\n const boxProgress = { x: 0, y: 0 };\n eachAxis((axis) => {\n const axisValue = this.getAxisMotionValue(axis);\n if (axisValue) {\n const latest = axisValue.get();\n boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]);\n }\n });\n /**\n * Update the layout of this element and resolve the latest drag constraints\n */\n const { transformTemplate } = this.visualElement.getProps();\n this.visualElement.current.style.transform = transformTemplate\n ? transformTemplate({}, \"\")\n : \"none\";\n projection.root && projection.root.updateScroll();\n projection.updateLayout();\n this.resolveConstraints();\n /**\n * For each axis, calculate the current progress of the layout axis\n * within the new constraints.\n */\n eachAxis((axis) => {\n if (!shouldDrag(axis, drag, null))\n return;\n /**\n * Calculate a new transform based on the previous box progress\n */\n const axisValue = this.getAxisMotionValue(axis);\n const { min, max } = this.constraints[axis];\n axisValue.set(mix(min, max, boxProgress[axis]));\n });\n }\n addListeners() {\n if (!this.visualElement.current)\n return;\n elementDragControls.set(this.visualElement, this);\n const element = this.visualElement.current;\n /**\n * Attach a pointerdown event listener on this DOM element to initiate drag tracking.\n */\n const stopPointerListener = addPointerEvent(element, \"pointerdown\", (event) => {\n const { drag, dragListener = true } = this.getProps();\n drag && dragListener && this.start(event);\n });\n const measureDragConstraints = () => {\n const { dragConstraints } = this.getProps();\n if (isRefObject(dragConstraints)) {\n this.constraints = this.resolveRefConstraints();\n }\n };\n const { projection } = this.visualElement;\n const stopMeasureLayoutListener = projection.addEventListener(\"measure\", measureDragConstraints);\n if (projection && !projection.layout) {\n projection.root && projection.root.updateScroll();\n projection.updateLayout();\n }\n measureDragConstraints();\n /**\n * Attach a window resize listener to scale the draggable target within its defined\n * constraints as the window resizes.\n */\n const stopResizeListener = addDomEvent(window, \"resize\", () => this.scalePositionWithinConstraints());\n /**\n * If the element's layout changes, calculate the delta and apply that to\n * the drag gesture's origin point.\n */\n const stopLayoutUpdateListener = projection.addEventListener(\"didUpdate\", (({ delta, hasLayoutChanged }) => {\n if (this.isDragging && hasLayoutChanged) {\n eachAxis((axis) => {\n const motionValue = this.getAxisMotionValue(axis);\n if (!motionValue)\n return;\n this.originPoint[axis] += delta[axis].translate;\n motionValue.set(motionValue.get() + delta[axis].translate);\n });\n this.visualElement.render();\n }\n }));\n return () => {\n stopResizeListener();\n stopPointerListener();\n stopMeasureLayoutListener();\n stopLayoutUpdateListener && stopLayoutUpdateListener();\n };\n }\n getProps() {\n const props = this.visualElement.getProps();\n const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;\n return {\n ...props,\n drag,\n dragDirectionLock,\n dragPropagation,\n dragConstraints,\n dragElastic,\n dragMomentum,\n };\n }\n}\nfunction shouldDrag(direction, drag, currentDirection) {\n return ((drag === true || drag === direction) &&\n (currentDirection === null || currentDirection === direction));\n}\n/**\n * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower\n * than the provided threshold, return `null`.\n *\n * @param offset - The x/y offset from origin.\n * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.\n */\nfunction getCurrentDirection(offset, lockThreshold = 10) {\n let direction = null;\n if (Math.abs(offset.y) > lockThreshold) {\n direction = \"y\";\n }\n else if (Math.abs(offset.x) > lockThreshold) {\n direction = \"x\";\n }\n return direction;\n}\n\nexport { VisualElementDragControls, elementDragControls };\n","import { Feature } from '../../motion/features/Feature.mjs';\nimport { noop } from '../../utils/noop.mjs';\nimport { VisualElementDragControls } from './VisualElementDragControls.mjs';\n\nclass DragGesture extends Feature {\n constructor(node) {\n super(node);\n this.removeGroupControls = noop;\n this.removeListeners = noop;\n this.controls = new VisualElementDragControls(node);\n }\n mount() {\n // If we've been provided a DragControls for manual control over the drag gesture,\n // subscribe this component to it on mount.\n const { dragControls } = this.node.getProps();\n if (dragControls) {\n this.removeGroupControls = dragControls.subscribe(this.controls);\n }\n this.removeListeners = this.controls.addListeners() || noop;\n }\n unmount() {\n this.removeGroupControls();\n this.removeListeners();\n }\n}\n\nexport { DragGesture };\n","import { PanSession } from './PanSession.mjs';\nimport { addPointerEvent } from '../../events/add-pointer-event.mjs';\nimport { Feature } from '../../motion/features/Feature.mjs';\nimport { noop } from '../../utils/noop.mjs';\nimport { getContextWindow } from '../../utils/get-context-window.mjs';\nimport { frame } from '../../frameloop/frame.mjs';\n\nconst asyncHandler = (handler) => (event, info) => {\n if (handler) {\n frame.update(() => handler(event, info));\n }\n};\nclass PanGesture extends Feature {\n constructor() {\n super(...arguments);\n this.removePointerDownListener = noop;\n }\n onPointerDown(pointerDownEvent) {\n this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), {\n transformPagePoint: this.node.getTransformPagePoint(),\n contextWindow: getContextWindow(this.node),\n });\n }\n createPanHandlers() {\n const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps();\n return {\n onSessionStart: asyncHandler(onPanSessionStart),\n onStart: asyncHandler(onPanStart),\n onMove: onPan,\n onEnd: (event, info) => {\n delete this.session;\n if (onPanEnd) {\n frame.update(() => onPanEnd(event, info));\n }\n },\n };\n }\n mount() {\n this.removePointerDownListener = addPointerEvent(this.node.current, \"pointerdown\", (event) => this.onPointerDown(event));\n }\n update() {\n this.session && this.session.updateHandlers(this.createPanHandlers());\n }\n unmount() {\n this.removePointerDownListener();\n this.session && this.session.end();\n }\n}\n\nexport { PanGesture };\n","import { useContext, useId, useEffect } from 'react';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\n\n/**\n * When a component is the child of `AnimatePresence`, it can use `usePresence`\n * to access information about whether it's still present in the React tree.\n *\n * ```jsx\n * import { usePresence } from \"framer-motion\"\n *\n * export const Component = () => {\n * const [isPresent, safeToRemove] = usePresence()\n *\n * useEffect(() => {\n * !isPresent && setTimeout(safeToRemove, 1000)\n * }, [isPresent])\n *\n * return \n * }\n * ```\n *\n * If `isPresent` is `false`, it means that a component has been removed the tree, but\n * `AnimatePresence` won't really remove it until `safeToRemove` has been called.\n *\n * @public\n */\nfunction usePresence() {\n const context = useContext(PresenceContext);\n if (context === null)\n return [true, null];\n const { isPresent, onExitComplete, register } = context;\n // It's safe to call the following hooks conditionally (after an early return) because the context will always\n // either be null or non-null for the lifespan of the component.\n const id = useId();\n useEffect(() => register(id), []);\n const safeToRemove = () => onExitComplete && onExitComplete(id);\n return !isPresent && onExitComplete ? [false, safeToRemove] : [true];\n}\n/**\n * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present.\n * There is no `safeToRemove` function.\n *\n * ```jsx\n * import { useIsPresent } from \"framer-motion\"\n *\n * export const Component = () => {\n * const isPresent = useIsPresent()\n *\n * useEffect(() => {\n * !isPresent && console.log(\"I've been removed!\")\n * }, [isPresent])\n *\n * return \n * }\n * ```\n *\n * @public\n */\nfunction useIsPresent() {\n return isPresent(useContext(PresenceContext));\n}\nfunction isPresent(context) {\n return context === null ? true : context.isPresent;\n}\n\nexport { isPresent, useIsPresent, usePresence };\n","/**\n * This should only ever be modified on the client otherwise it'll\n * persist through server requests. If we need instanced states we\n * could lazy-init via root.\n */\nconst globalProjectionState = {\n /**\n * Global flag as to whether the tree has animated since the last time\n * we resized the window\n */\n hasAnimatedSinceResize: true,\n /**\n * We set this to true once, on the first update. Any nodes added to the tree beyond that\n * update will be given a `data-projection-id` attribute.\n */\n hasEverUpdated: false,\n};\n\nexport { globalProjectionState };\n","import { px } from '../../value/types/numbers/units.mjs';\n\nfunction pixelsToPercent(pixels, axis) {\n if (axis.max === axis.min)\n return 0;\n return (pixels / (axis.max - axis.min)) * 100;\n}\n/**\n * We always correct borderRadius as a percentage rather than pixels to reduce paints.\n * For example, if you are projecting a box that is 100px wide with a 10px borderRadius\n * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%\n * borderRadius in both states. If we animate between the two in pixels that will trigger\n * a paint each time. If we animate between the two in percentage we'll avoid a paint.\n */\nconst correctBorderRadius = {\n correct: (latest, node) => {\n if (!node.target)\n return latest;\n /**\n * If latest is a string, if it's a percentage we can return immediately as it's\n * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.\n */\n if (typeof latest === \"string\") {\n if (px.test(latest)) {\n latest = parseFloat(latest);\n }\n else {\n return latest;\n }\n }\n /**\n * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that\n * pixel value as a percentage of each axis\n */\n const x = pixelsToPercent(latest, node.target.x);\n const y = pixelsToPercent(latest, node.target.y);\n return `${x}% ${y}%`;\n },\n};\n\nexport { correctBorderRadius, pixelsToPercent };\n","import { mix } from '../../utils/mix.mjs';\nimport { complex } from '../../value/types/complex/index.mjs';\n\nconst correctBoxShadow = {\n correct: (latest, { treeScale, projectionDelta }) => {\n const original = latest;\n const shadow = complex.parse(latest);\n // TODO: Doesn't support multiple shadows\n if (shadow.length > 5)\n return original;\n const template = complex.createTransformer(latest);\n const offset = typeof shadow[0] !== \"number\" ? 1 : 0;\n // Calculate the overall context scale\n const xScale = projectionDelta.x.scale * treeScale.x;\n const yScale = projectionDelta.y.scale * treeScale.y;\n shadow[0 + offset] /= xScale;\n shadow[1 + offset] /= yScale;\n /**\n * Ideally we'd correct x and y scales individually, but because blur and\n * spread apply to both we have to take a scale average and apply that instead.\n * We could potentially improve the outcome of this by incorporating the ratio between\n * the two scales.\n */\n const averageScale = mix(xScale, yScale, 0.5);\n // Blur\n if (typeof shadow[2 + offset] === \"number\")\n shadow[2 + offset] /= averageScale;\n // Spread\n if (typeof shadow[3 + offset] === \"number\")\n shadow[3 + offset] /= averageScale;\n return template(shadow);\n },\n};\n\nexport { correctBoxShadow };\n","import React__default, { useContext } from 'react';\nimport { usePresence } from '../../../components/AnimatePresence/use-presence.mjs';\nimport { LayoutGroupContext } from '../../../context/LayoutGroupContext.mjs';\nimport { SwitchLayoutGroupContext } from '../../../context/SwitchLayoutGroupContext.mjs';\nimport { globalProjectionState } from '../../../projection/node/state.mjs';\nimport { correctBorderRadius } from '../../../projection/styles/scale-border-radius.mjs';\nimport { correctBoxShadow } from '../../../projection/styles/scale-box-shadow.mjs';\nimport { addScaleCorrector } from '../../../projection/styles/scale-correction.mjs';\nimport { frame } from '../../../frameloop/frame.mjs';\n\nclass MeasureLayoutWithContext extends React__default.Component {\n /**\n * This only mounts projection nodes for components that\n * need measuring, we might want to do it for all components\n * in order to incorporate transforms\n */\n componentDidMount() {\n const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props;\n const { projection } = visualElement;\n addScaleCorrector(defaultScaleCorrectors);\n if (projection) {\n if (layoutGroup.group)\n layoutGroup.group.add(projection);\n if (switchLayoutGroup && switchLayoutGroup.register && layoutId) {\n switchLayoutGroup.register(projection);\n }\n projection.root.didUpdate();\n projection.addEventListener(\"animationComplete\", () => {\n this.safeToRemove();\n });\n projection.setOptions({\n ...projection.options,\n onExitComplete: () => this.safeToRemove(),\n });\n }\n globalProjectionState.hasEverUpdated = true;\n }\n getSnapshotBeforeUpdate(prevProps) {\n const { layoutDependency, visualElement, drag, isPresent } = this.props;\n const projection = visualElement.projection;\n if (!projection)\n return null;\n /**\n * TODO: We use this data in relegate to determine whether to\n * promote a previous element. There's no guarantee its presence data\n * will have updated by this point - if a bug like this arises it will\n * have to be that we markForRelegation and then find a new lead some other way,\n * perhaps in didUpdate\n */\n projection.isPresent = isPresent;\n if (drag ||\n prevProps.layoutDependency !== layoutDependency ||\n layoutDependency === undefined) {\n projection.willUpdate();\n }\n else {\n this.safeToRemove();\n }\n if (prevProps.isPresent !== isPresent) {\n if (isPresent) {\n projection.promote();\n }\n else if (!projection.relegate()) {\n /**\n * If there's another stack member taking over from this one,\n * it's in charge of the exit animation and therefore should\n * be in charge of the safe to remove. Otherwise we call it here.\n */\n frame.postRender(() => {\n const stack = projection.getStack();\n if (!stack || !stack.members.length) {\n this.safeToRemove();\n }\n });\n }\n }\n return null;\n }\n componentDidUpdate() {\n const { projection } = this.props.visualElement;\n if (projection) {\n projection.root.didUpdate();\n queueMicrotask(() => {\n if (!projection.currentAnimation && projection.isLead()) {\n this.safeToRemove();\n }\n });\n }\n }\n componentWillUnmount() {\n const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props;\n const { projection } = visualElement;\n if (projection) {\n projection.scheduleCheckAfterUnmount();\n if (layoutGroup && layoutGroup.group)\n layoutGroup.group.remove(projection);\n if (promoteContext && promoteContext.deregister)\n promoteContext.deregister(projection);\n }\n }\n safeToRemove() {\n const { safeToRemove } = this.props;\n safeToRemove && safeToRemove();\n }\n render() {\n return null;\n }\n}\nfunction MeasureLayout(props) {\n const [isPresent, safeToRemove] = usePresence();\n const layoutGroup = useContext(LayoutGroupContext);\n return (React__default.createElement(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: useContext(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove }));\n}\nconst defaultScaleCorrectors = {\n borderRadius: {\n ...correctBorderRadius,\n applyTo: [\n \"borderTopLeftRadius\",\n \"borderTopRightRadius\",\n \"borderBottomLeftRadius\",\n \"borderBottomRightRadius\",\n ],\n },\n borderTopLeftRadius: correctBorderRadius,\n borderTopRightRadius: correctBorderRadius,\n borderBottomLeftRadius: correctBorderRadius,\n borderBottomRightRadius: correctBorderRadius,\n boxShadow: correctBoxShadow,\n};\n\nexport { MeasureLayout };\n","import { circOut } from '../../easing/circ.mjs';\nimport { progress } from '../../utils/progress.mjs';\nimport { mix } from '../../utils/mix.mjs';\nimport { noop } from '../../utils/noop.mjs';\nimport { percent, px } from '../../value/types/numbers/units.mjs';\n\nconst borders = [\"TopLeft\", \"TopRight\", \"BottomLeft\", \"BottomRight\"];\nconst numBorders = borders.length;\nconst asNumber = (value) => typeof value === \"string\" ? parseFloat(value) : value;\nconst isPx = (value) => typeof value === \"number\" || px.test(value);\nfunction mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {\n if (shouldCrossfadeOpacity) {\n target.opacity = mix(0, \n // TODO Reinstate this if only child\n lead.opacity !== undefined ? lead.opacity : 1, easeCrossfadeIn(progress));\n target.opacityExit = mix(follow.opacity !== undefined ? follow.opacity : 1, 0, easeCrossfadeOut(progress));\n }\n else if (isOnlyMember) {\n target.opacity = mix(follow.opacity !== undefined ? follow.opacity : 1, lead.opacity !== undefined ? lead.opacity : 1, progress);\n }\n /**\n * Mix border radius\n */\n for (let i = 0; i < numBorders; i++) {\n const borderLabel = `border${borders[i]}Radius`;\n let followRadius = getRadius(follow, borderLabel);\n let leadRadius = getRadius(lead, borderLabel);\n if (followRadius === undefined && leadRadius === undefined)\n continue;\n followRadius || (followRadius = 0);\n leadRadius || (leadRadius = 0);\n const canMix = followRadius === 0 ||\n leadRadius === 0 ||\n isPx(followRadius) === isPx(leadRadius);\n if (canMix) {\n target[borderLabel] = Math.max(mix(asNumber(followRadius), asNumber(leadRadius), progress), 0);\n if (percent.test(leadRadius) || percent.test(followRadius)) {\n target[borderLabel] += \"%\";\n }\n }\n else {\n target[borderLabel] = leadRadius;\n }\n }\n /**\n * Mix rotation\n */\n if (follow.rotate || lead.rotate) {\n target.rotate = mix(follow.rotate || 0, lead.rotate || 0, progress);\n }\n}\nfunction getRadius(values, radiusName) {\n return values[radiusName] !== undefined\n ? values[radiusName]\n : values.borderRadius;\n}\n// /**\n// * We only want to mix the background color if there's a follow element\n// * that we're not crossfading opacity between. For instance with switch\n// * AnimateSharedLayout animations, this helps the illusion of a continuous\n// * element being animated but also cuts down on the number of paints triggered\n// * for elements where opacity is doing that work for us.\n// */\n// if (\n// !hasFollowElement &&\n// latestLeadValues.backgroundColor &&\n// latestFollowValues.backgroundColor\n// ) {\n// /**\n// * This isn't ideal performance-wise as mixColor is creating a new function every frame.\n// * We could probably create a mixer that runs at the start of the animation but\n// * the idea behind the crossfader is that it runs dynamically between two potentially\n// * changing targets (ie opacity or borderRadius may be animating independently via variants)\n// */\n// leadState.backgroundColor = followState.backgroundColor = mixColor(\n// latestFollowValues.backgroundColor as string,\n// latestLeadValues.backgroundColor as string\n// )(p)\n// }\nconst easeCrossfadeIn = compress(0, 0.5, circOut);\nconst easeCrossfadeOut = compress(0.5, 0.95, noop);\nfunction compress(min, max, easing) {\n return (p) => {\n // Could replace ifs with clamp\n if (p < min)\n return 0;\n if (p > max)\n return 1;\n return easing(progress(min, max, p));\n };\n}\n\nexport { mixValues };\n","/**\n * Reset an axis to the provided origin box.\n *\n * This is a mutative operation.\n */\nfunction copyAxisInto(axis, originAxis) {\n axis.min = originAxis.min;\n axis.max = originAxis.max;\n}\n/**\n * Reset a box to the provided origin box.\n *\n * This is a mutative operation.\n */\nfunction copyBoxInto(box, originBox) {\n copyAxisInto(box.x, originBox.x);\n copyAxisInto(box.y, originBox.y);\n}\n\nexport { copyAxisInto, copyBoxInto };\n","import { mix } from '../../utils/mix.mjs';\nimport { percent } from '../../value/types/numbers/units.mjs';\nimport { scalePoint } from './delta-apply.mjs';\n\n/**\n * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse\n */\nfunction removePointDelta(point, translate, scale, originPoint, boxScale) {\n point -= translate;\n point = scalePoint(point, 1 / scale, originPoint);\n if (boxScale !== undefined) {\n point = scalePoint(point, 1 / boxScale, originPoint);\n }\n return point;\n}\n/**\n * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse\n */\nfunction removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) {\n if (percent.test(translate)) {\n translate = parseFloat(translate);\n const relativeProgress = mix(sourceAxis.min, sourceAxis.max, translate / 100);\n translate = relativeProgress - sourceAxis.min;\n }\n if (typeof translate !== \"number\")\n return;\n let originPoint = mix(originAxis.min, originAxis.max, origin);\n if (axis === originAxis)\n originPoint -= translate;\n axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale);\n axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale);\n}\n/**\n * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse\n * and acts as a bridge between motion values and removeAxisDelta\n */\nfunction removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) {\n removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis);\n}\n/**\n * The names of the motion values we want to apply as translation, scale and origin.\n */\nconst xKeys = [\"x\", \"scaleX\", \"originX\"];\nconst yKeys = [\"y\", \"scaleY\", \"originY\"];\n/**\n * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse\n * and acts as a bridge between motion values and removeAxisDelta\n */\nfunction removeBoxTransforms(box, transforms, originBox, sourceBox) {\n removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);\n removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);\n}\n\nexport { removeAxisDelta, removeAxisTransforms, removeBoxTransforms, removePointDelta };\n","import { calcLength } from './delta-calc.mjs';\n\nfunction isAxisDeltaZero(delta) {\n return delta.translate === 0 && delta.scale === 1;\n}\nfunction isDeltaZero(delta) {\n return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y);\n}\nfunction boxEquals(a, b) {\n return (a.x.min === b.x.min &&\n a.x.max === b.x.max &&\n a.y.min === b.y.min &&\n a.y.max === b.y.max);\n}\nfunction boxEqualsRounded(a, b) {\n return (Math.round(a.x.min) === Math.round(b.x.min) &&\n Math.round(a.x.max) === Math.round(b.x.max) &&\n Math.round(a.y.min) === Math.round(b.y.min) &&\n Math.round(a.y.max) === Math.round(b.y.max));\n}\nfunction aspectRatio(box) {\n return calcLength(box.x) / calcLength(box.y);\n}\n\nexport { aspectRatio, boxEquals, boxEqualsRounded, isDeltaZero };\n","import { addUniqueItem, removeItem } from '../../utils/array.mjs';\n\nclass NodeStack {\n constructor() {\n this.members = [];\n }\n add(node) {\n addUniqueItem(this.members, node);\n node.scheduleRender();\n }\n remove(node) {\n removeItem(this.members, node);\n if (node === this.prevLead) {\n this.prevLead = undefined;\n }\n if (node === this.lead) {\n const prevLead = this.members[this.members.length - 1];\n if (prevLead) {\n this.promote(prevLead);\n }\n }\n }\n relegate(node) {\n const indexOfNode = this.members.findIndex((member) => node === member);\n if (indexOfNode === 0)\n return false;\n /**\n * Find the next projection node that is present\n */\n let prevLead;\n for (let i = indexOfNode; i >= 0; i--) {\n const member = this.members[i];\n if (member.isPresent !== false) {\n prevLead = member;\n break;\n }\n }\n if (prevLead) {\n this.promote(prevLead);\n return true;\n }\n else {\n return false;\n }\n }\n promote(node, preserveFollowOpacity) {\n const prevLead = this.lead;\n if (node === prevLead)\n return;\n this.prevLead = prevLead;\n this.lead = node;\n node.show();\n if (prevLead) {\n prevLead.instance && prevLead.scheduleRender();\n node.scheduleRender();\n node.resumeFrom = prevLead;\n if (preserveFollowOpacity) {\n node.resumeFrom.preserveOpacity = true;\n }\n if (prevLead.snapshot) {\n node.snapshot = prevLead.snapshot;\n node.snapshot.latestValues =\n prevLead.animationValues || prevLead.latestValues;\n }\n if (node.root && node.root.isUpdating) {\n node.isLayoutDirty = true;\n }\n const { crossfade } = node.options;\n if (crossfade === false) {\n prevLead.hide();\n }\n /**\n * TODO:\n * - Test border radius when previous node was deleted\n * - boxShadow mixing\n * - Shared between element A in scrolled container and element B (scroll stays the same or changes)\n * - Shared between element A in transformed container and element B (transform stays the same or changes)\n * - Shared between element A in scrolled page and element B (scroll stays the same or changes)\n * ---\n * - Crossfade opacity of root nodes\n * - layoutId changes after animation\n * - layoutId changes mid animation\n */\n }\n }\n exitAnimationComplete() {\n this.members.forEach((node) => {\n const { options, resumingFrom } = node;\n options.onExitComplete && options.onExitComplete();\n if (resumingFrom) {\n resumingFrom.options.onExitComplete &&\n resumingFrom.options.onExitComplete();\n }\n });\n }\n scheduleRender() {\n this.members.forEach((node) => {\n node.instance && node.scheduleRender(false);\n });\n }\n /**\n * Clear any leads that have been removed this render to prevent them from being\n * used in future animations and to prevent memory leaks\n */\n removeLeadSnapshot() {\n if (this.lead && this.lead.snapshot) {\n this.lead.snapshot = undefined;\n }\n }\n}\n\nexport { NodeStack };\n","function buildProjectionTransform(delta, treeScale, latestTransform) {\n let transform = \"\";\n /**\n * The translations we use to calculate are always relative to the viewport coordinate space.\n * But when we apply scales, we also scale the coordinate space of an element and its children.\n * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need\n * to move an element 100 pixels, we actually need to move it 200 in within that scaled space.\n */\n const xTranslate = delta.x.translate / treeScale.x;\n const yTranslate = delta.y.translate / treeScale.y;\n if (xTranslate || yTranslate) {\n transform = `translate3d(${xTranslate}px, ${yTranslate}px, 0) `;\n }\n /**\n * Apply scale correction for the tree transform.\n * This will apply scale to the screen-orientated axes.\n */\n if (treeScale.x !== 1 || treeScale.y !== 1) {\n transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;\n }\n if (latestTransform) {\n const { rotate, rotateX, rotateY } = latestTransform;\n if (rotate)\n transform += `rotate(${rotate}deg) `;\n if (rotateX)\n transform += `rotateX(${rotateX}deg) `;\n if (rotateY)\n transform += `rotateY(${rotateY}deg) `;\n }\n /**\n * Apply scale to match the size of the element to the size we want it.\n * This will apply scale to the element-orientated axes.\n */\n const elementScaleX = delta.x.scale * treeScale.x;\n const elementScaleY = delta.y.scale * treeScale.y;\n if (elementScaleX !== 1 || elementScaleY !== 1) {\n transform += `scale(${elementScaleX}, ${elementScaleY})`;\n }\n return transform || \"none\";\n}\n\nexport { buildProjectionTransform };\n","const compareByDepth = (a, b) => a.depth - b.depth;\n\nexport { compareByDepth };\n","import { addUniqueItem, removeItem } from '../../utils/array.mjs';\nimport { compareByDepth } from './compare-by-depth.mjs';\n\nclass FlatTree {\n constructor() {\n this.children = [];\n this.isDirty = false;\n }\n add(child) {\n addUniqueItem(this.children, child);\n this.isDirty = true;\n }\n remove(child) {\n removeItem(this.children, child);\n this.isDirty = true;\n }\n forEach(callback) {\n this.isDirty && this.children.sort(compareByDepth);\n this.isDirty = false;\n this.children.forEach(callback);\n }\n}\n\nexport { FlatTree };\n","import { frame, cancelFrame } from '../frameloop/frame.mjs';\n\n/**\n * Timeout defined in ms\n */\nfunction delay(callback, timeout) {\n const start = performance.now();\n const checkElapsed = ({ timestamp }) => {\n const elapsed = timestamp - start;\n if (elapsed >= timeout) {\n cancelFrame(checkElapsed);\n callback(elapsed - timeout);\n }\n };\n frame.read(checkElapsed, true);\n return () => cancelFrame(checkElapsed);\n}\n\nexport { delay };\n","function record(data) {\n if (window.MotionDebug) {\n window.MotionDebug.record(data);\n }\n}\n\nexport { record };\n","function isSVGElement(element) {\n return element instanceof SVGElement && element.tagName !== \"svg\";\n}\n\nexport { isSVGElement };\n","import { animateMotionValue } from './motion-value.mjs';\nimport { motionValue } from '../../value/index.mjs';\nimport { isMotionValue } from '../../value/utils/is-motion-value.mjs';\n\nfunction animateSingleValue(value, keyframes, options) {\n const motionValue$1 = isMotionValue(value) ? value : motionValue(value);\n motionValue$1.start(animateMotionValue(\"\", motionValue$1, keyframes, options));\n return motionValue$1.animation;\n}\n\nexport { animateSingleValue };\n","import { SubscriptionManager } from '../../utils/subscription-manager.mjs';\nimport { mixValues } from '../animation/mix-values.mjs';\nimport { copyBoxInto } from '../geometry/copy.mjs';\nimport { translateAxis, transformBox, applyBoxDelta, applyTreeDeltas } from '../geometry/delta-apply.mjs';\nimport { calcRelativePosition, calcRelativeBox, calcBoxDelta, calcLength, isNear } from '../geometry/delta-calc.mjs';\nimport { removeBoxTransforms } from '../geometry/delta-remove.mjs';\nimport { createBox, createDelta } from '../geometry/models.mjs';\nimport { getValueTransition } from '../../animation/utils/transitions.mjs';\nimport { boxEqualsRounded, isDeltaZero, aspectRatio, boxEquals } from '../geometry/utils.mjs';\nimport { NodeStack } from '../shared/stack.mjs';\nimport { scaleCorrectors } from '../styles/scale-correction.mjs';\nimport { buildProjectionTransform } from '../styles/transform.mjs';\nimport { eachAxis } from '../utils/each-axis.mjs';\nimport { hasTransform, hasScale, has2DTranslate } from '../utils/has-transform.mjs';\nimport { FlatTree } from '../../render/utils/flat-tree.mjs';\nimport { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs';\nimport { globalProjectionState } from './state.mjs';\nimport { delay } from '../../utils/delay.mjs';\nimport { mix } from '../../utils/mix.mjs';\nimport { record } from '../../debug/record.mjs';\nimport { isSVGElement } from '../../render/dom/utils/is-svg-element.mjs';\nimport { animateSingleValue } from '../../animation/interfaces/single-value.mjs';\nimport { clamp } from '../../utils/clamp.mjs';\nimport { cancelFrame, frameData, steps, frame } from '../../frameloop/frame.mjs';\nimport { noop } from '../../utils/noop.mjs';\n\nconst transformAxes = [\"\", \"X\", \"Y\", \"Z\"];\nconst hiddenVisibility = { visibility: \"hidden\" };\n/**\n * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1\n * which has a noticeable difference in spring animations\n */\nconst animationTarget = 1000;\nlet id = 0;\n/**\n * Use a mutable data object for debug data so as to not create a new\n * object every frame.\n */\nconst projectionFrameData = {\n type: \"projectionFrame\",\n totalNodes: 0,\n resolvedTargetDeltas: 0,\n recalculatedProjection: 0,\n};\nfunction createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {\n return class ProjectionNode {\n constructor(latestValues = {}, parent = defaultParent === null || defaultParent === void 0 ? void 0 : defaultParent()) {\n /**\n * A unique ID generated for every projection node.\n */\n this.id = id++;\n /**\n * An id that represents a unique session instigated by startUpdate.\n */\n this.animationId = 0;\n /**\n * A Set containing all this component's children. This is used to iterate\n * through the children.\n *\n * TODO: This could be faster to iterate as a flat array stored on the root node.\n */\n this.children = new Set();\n /**\n * Options for the node. We use this to configure what kind of layout animations\n * we should perform (if any).\n */\n this.options = {};\n /**\n * We use this to detect when its safe to shut down part of a projection tree.\n * We have to keep projecting children for scale correction and relative projection\n * until all their parents stop performing layout animations.\n */\n this.isTreeAnimating = false;\n this.isAnimationBlocked = false;\n /**\n * Flag to true if we think this layout has been changed. We can't always know this,\n * currently we set it to true every time a component renders, or if it has a layoutDependency\n * if that has changed between renders. Additionally, components can be grouped by LayoutGroup\n * and if one node is dirtied, they all are.\n */\n this.isLayoutDirty = false;\n /**\n * Flag to true if we think the projection calculations for this node needs\n * recalculating as a result of an updated transform or layout animation.\n */\n this.isProjectionDirty = false;\n /**\n * Flag to true if the layout *or* transform has changed. This then gets propagated\n * throughout the projection tree, forcing any element below to recalculate on the next frame.\n */\n this.isSharedProjectionDirty = false;\n /**\n * Flag transform dirty. This gets propagated throughout the whole tree but is only\n * respected by shared nodes.\n */\n this.isTransformDirty = false;\n /**\n * Block layout updates for instant layout transitions throughout the tree.\n */\n this.updateManuallyBlocked = false;\n this.updateBlockedByResize = false;\n /**\n * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate`\n * call.\n */\n this.isUpdating = false;\n /**\n * If this is an SVG element we currently disable projection transforms\n */\n this.isSVG = false;\n /**\n * Flag to true (during promotion) if a node doing an instant layout transition needs to reset\n * its projection styles.\n */\n this.needsReset = false;\n /**\n * Flags whether this node should have its transform reset prior to measuring.\n */\n this.shouldResetTransform = false;\n /**\n * An object representing the calculated contextual/accumulated/tree scale.\n * This will be used to scale calculcated projection transforms, as these are\n * calculated in screen-space but need to be scaled for elements to layoutly\n * make it to their calculated destinations.\n *\n * TODO: Lazy-init\n */\n this.treeScale = { x: 1, y: 1 };\n /**\n *\n */\n this.eventHandlers = new Map();\n this.hasTreeAnimated = false;\n // Note: Currently only running on root node\n this.updateScheduled = false;\n this.projectionUpdateScheduled = false;\n this.checkUpdateFailed = () => {\n if (this.isUpdating) {\n this.isUpdating = false;\n this.clearAllSnapshots();\n }\n };\n /**\n * This is a multi-step process as shared nodes might be of different depths. Nodes\n * are sorted by depth order, so we need to resolve the entire tree before moving to\n * the next step.\n */\n this.updateProjection = () => {\n this.projectionUpdateScheduled = false;\n /**\n * Reset debug counts. Manually resetting rather than creating a new\n * object each frame.\n */\n projectionFrameData.totalNodes =\n projectionFrameData.resolvedTargetDeltas =\n projectionFrameData.recalculatedProjection =\n 0;\n this.nodes.forEach(propagateDirtyNodes);\n this.nodes.forEach(resolveTargetDelta);\n this.nodes.forEach(calcProjection);\n this.nodes.forEach(cleanDirtyNodes);\n record(projectionFrameData);\n };\n this.hasProjected = false;\n this.isVisible = true;\n this.animationProgress = 0;\n /**\n * Shared layout\n */\n // TODO Only running on root node\n this.sharedNodes = new Map();\n this.latestValues = latestValues;\n this.root = parent ? parent.root || parent : this;\n this.path = parent ? [...parent.path, parent] : [];\n this.parent = parent;\n this.depth = parent ? parent.depth + 1 : 0;\n for (let i = 0; i < this.path.length; i++) {\n this.path[i].shouldResetTransform = true;\n }\n if (this.root === this)\n this.nodes = new FlatTree();\n }\n addEventListener(name, handler) {\n if (!this.eventHandlers.has(name)) {\n this.eventHandlers.set(name, new SubscriptionManager());\n }\n return this.eventHandlers.get(name).add(handler);\n }\n notifyListeners(name, ...args) {\n const subscriptionManager = this.eventHandlers.get(name);\n subscriptionManager && subscriptionManager.notify(...args);\n }\n hasListeners(name) {\n return this.eventHandlers.has(name);\n }\n /**\n * Lifecycles\n */\n mount(instance, isLayoutDirty = this.root.hasTreeAnimated) {\n if (this.instance)\n return;\n this.isSVG = isSVGElement(instance);\n this.instance = instance;\n const { layoutId, layout, visualElement } = this.options;\n if (visualElement && !visualElement.current) {\n visualElement.mount(instance);\n }\n this.root.nodes.add(this);\n this.parent && this.parent.children.add(this);\n if (isLayoutDirty && (layout || layoutId)) {\n this.isLayoutDirty = true;\n }\n if (attachResizeListener) {\n let cancelDelay;\n const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false);\n attachResizeListener(instance, () => {\n this.root.updateBlockedByResize = true;\n cancelDelay && cancelDelay();\n cancelDelay = delay(resizeUnblockUpdate, 250);\n if (globalProjectionState.hasAnimatedSinceResize) {\n globalProjectionState.hasAnimatedSinceResize = false;\n this.nodes.forEach(finishAnimation);\n }\n });\n }\n if (layoutId) {\n this.root.registerSharedNode(layoutId, this);\n }\n // Only register the handler if it requires layout animation\n if (this.options.animate !== false &&\n visualElement &&\n (layoutId || layout)) {\n this.addEventListener(\"didUpdate\", ({ delta, hasLayoutChanged, hasRelativeTargetChanged, layout: newLayout, }) => {\n if (this.isTreeAnimationBlocked()) {\n this.target = undefined;\n this.relativeTarget = undefined;\n return;\n }\n // TODO: Check here if an animation exists\n const layoutTransition = this.options.transition ||\n visualElement.getDefaultTransition() ||\n defaultLayoutTransition;\n const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps();\n /**\n * The target layout of the element might stay the same,\n * but its position relative to its parent has changed.\n */\n const targetChanged = !this.targetLayout ||\n !boxEqualsRounded(this.targetLayout, newLayout) ||\n hasRelativeTargetChanged;\n /**\n * If the layout hasn't seemed to have changed, it might be that the\n * element is visually in the same place in the document but its position\n * relative to its parent has indeed changed. So here we check for that.\n */\n const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeTargetChanged;\n if (this.options.layoutRoot ||\n (this.resumeFrom && this.resumeFrom.instance) ||\n hasOnlyRelativeTargetChanged ||\n (hasLayoutChanged &&\n (targetChanged || !this.currentAnimation))) {\n if (this.resumeFrom) {\n this.resumingFrom = this.resumeFrom;\n this.resumingFrom.resumingFrom = undefined;\n }\n this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);\n const animationOptions = {\n ...getValueTransition(layoutTransition, \"layout\"),\n onPlay: onLayoutAnimationStart,\n onComplete: onLayoutAnimationComplete,\n };\n if (visualElement.shouldReduceMotion ||\n this.options.layoutRoot) {\n animationOptions.delay = 0;\n animationOptions.type = false;\n }\n this.startAnimation(animationOptions);\n }\n else {\n /**\n * If the layout hasn't changed and we have an animation that hasn't started yet,\n * finish it immediately. Otherwise it will be animating from a location\n * that was probably never commited to screen and look like a jumpy box.\n */\n if (!hasLayoutChanged) {\n finishAnimation(this);\n }\n if (this.isLead() && this.options.onExitComplete) {\n this.options.onExitComplete();\n }\n }\n this.targetLayout = newLayout;\n });\n }\n }\n unmount() {\n this.options.layoutId && this.willUpdate();\n this.root.nodes.remove(this);\n const stack = this.getStack();\n stack && stack.remove(this);\n this.parent && this.parent.children.delete(this);\n this.instance = undefined;\n cancelFrame(this.updateProjection);\n }\n // only on the root\n blockUpdate() {\n this.updateManuallyBlocked = true;\n }\n unblockUpdate() {\n this.updateManuallyBlocked = false;\n }\n isUpdateBlocked() {\n return this.updateManuallyBlocked || this.updateBlockedByResize;\n }\n isTreeAnimationBlocked() {\n return (this.isAnimationBlocked ||\n (this.parent && this.parent.isTreeAnimationBlocked()) ||\n false);\n }\n // Note: currently only running on root node\n startUpdate() {\n if (this.isUpdateBlocked())\n return;\n this.isUpdating = true;\n this.nodes && this.nodes.forEach(resetRotation);\n this.animationId++;\n }\n getTransformTemplate() {\n const { visualElement } = this.options;\n return visualElement && visualElement.getProps().transformTemplate;\n }\n willUpdate(shouldNotifyListeners = true) {\n this.root.hasTreeAnimated = true;\n if (this.root.isUpdateBlocked()) {\n this.options.onExitComplete && this.options.onExitComplete();\n return;\n }\n !this.root.isUpdating && this.root.startUpdate();\n if (this.isLayoutDirty)\n return;\n this.isLayoutDirty = true;\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n node.shouldResetTransform = true;\n node.updateScroll(\"snapshot\");\n if (node.options.layoutRoot) {\n node.willUpdate(false);\n }\n }\n const { layoutId, layout } = this.options;\n if (layoutId === undefined && !layout)\n return;\n const transformTemplate = this.getTransformTemplate();\n this.prevTransformTemplateValue = transformTemplate\n ? transformTemplate(this.latestValues, \"\")\n : undefined;\n this.updateSnapshot();\n shouldNotifyListeners && this.notifyListeners(\"willUpdate\");\n }\n update() {\n this.updateScheduled = false;\n const updateWasBlocked = this.isUpdateBlocked();\n // When doing an instant transition, we skip the layout update,\n // but should still clean up the measurements so that the next\n // snapshot could be taken correctly.\n if (updateWasBlocked) {\n this.unblockUpdate();\n this.clearAllSnapshots();\n this.nodes.forEach(clearMeasurements);\n return;\n }\n if (!this.isUpdating) {\n this.nodes.forEach(clearIsLayoutDirty);\n }\n this.isUpdating = false;\n /**\n * Write\n */\n this.nodes.forEach(resetTransformStyle);\n /**\n * Read ==================\n */\n // Update layout measurements of updated children\n this.nodes.forEach(updateLayout);\n /**\n * Write\n */\n // Notify listeners that the layout is updated\n this.nodes.forEach(notifyLayoutUpdate);\n this.clearAllSnapshots();\n /**\n * Manually flush any pending updates. Ideally\n * we could leave this to the following requestAnimationFrame but this seems\n * to leave a flash of incorrectly styled content.\n */\n const now = performance.now();\n frameData.delta = clamp(0, 1000 / 60, now - frameData.timestamp);\n frameData.timestamp = now;\n frameData.isProcessing = true;\n steps.update.process(frameData);\n steps.preRender.process(frameData);\n steps.render.process(frameData);\n frameData.isProcessing = false;\n }\n didUpdate() {\n if (!this.updateScheduled) {\n this.updateScheduled = true;\n queueMicrotask(() => this.update());\n }\n }\n clearAllSnapshots() {\n this.nodes.forEach(clearSnapshot);\n this.sharedNodes.forEach(removeLeadSnapshots);\n }\n scheduleUpdateProjection() {\n if (!this.projectionUpdateScheduled) {\n this.projectionUpdateScheduled = true;\n frame.preRender(this.updateProjection, false, true);\n }\n }\n scheduleCheckAfterUnmount() {\n /**\n * If the unmounting node is in a layoutGroup and did trigger a willUpdate,\n * we manually call didUpdate to give a chance to the siblings to animate.\n * Otherwise, cleanup all snapshots to prevents future nodes from reusing them.\n */\n frame.postRender(() => {\n if (this.isLayoutDirty) {\n this.root.didUpdate();\n }\n else {\n this.root.checkUpdateFailed();\n }\n });\n }\n /**\n * Update measurements\n */\n updateSnapshot() {\n if (this.snapshot || !this.instance)\n return;\n this.snapshot = this.measure();\n }\n updateLayout() {\n if (!this.instance)\n return;\n // TODO: Incorporate into a forwarded scroll offset\n this.updateScroll();\n if (!(this.options.alwaysMeasureLayout && this.isLead()) &&\n !this.isLayoutDirty) {\n return;\n }\n /**\n * When a node is mounted, it simply resumes from the prevLead's\n * snapshot instead of taking a new one, but the ancestors scroll\n * might have updated while the prevLead is unmounted. We need to\n * update the scroll again to make sure the layout we measure is\n * up to date.\n */\n if (this.resumeFrom && !this.resumeFrom.instance) {\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n node.updateScroll();\n }\n }\n const prevLayout = this.layout;\n this.layout = this.measure(false);\n this.layoutCorrected = createBox();\n this.isLayoutDirty = false;\n this.projectionDelta = undefined;\n this.notifyListeners(\"measure\", this.layout.layoutBox);\n const { visualElement } = this.options;\n visualElement &&\n visualElement.notify(\"LayoutMeasure\", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined);\n }\n updateScroll(phase = \"measure\") {\n let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);\n if (this.scroll &&\n this.scroll.animationId === this.root.animationId &&\n this.scroll.phase === phase) {\n needsMeasurement = false;\n }\n if (needsMeasurement) {\n this.scroll = {\n animationId: this.root.animationId,\n phase,\n isRoot: checkIsScrollRoot(this.instance),\n offset: measureScroll(this.instance),\n };\n }\n }\n resetTransform() {\n if (!resetTransform)\n return;\n const isResetRequested = this.isLayoutDirty || this.shouldResetTransform;\n const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);\n const transformTemplate = this.getTransformTemplate();\n const transformTemplateValue = transformTemplate\n ? transformTemplate(this.latestValues, \"\")\n : undefined;\n const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue;\n if (isResetRequested &&\n (hasProjection ||\n hasTransform(this.latestValues) ||\n transformTemplateHasChanged)) {\n resetTransform(this.instance, transformTemplateValue);\n this.shouldResetTransform = false;\n this.scheduleRender();\n }\n }\n measure(removeTransform = true) {\n const pageBox = this.measurePageBox();\n let layoutBox = this.removeElementScroll(pageBox);\n /**\n * Measurements taken during the pre-render stage\n * still have transforms applied so we remove them\n * via calculation.\n */\n if (removeTransform) {\n layoutBox = this.removeTransform(layoutBox);\n }\n roundBox(layoutBox);\n return {\n animationId: this.root.animationId,\n measuredBox: pageBox,\n layoutBox,\n latestValues: {},\n source: this.id,\n };\n }\n measurePageBox() {\n const { visualElement } = this.options;\n if (!visualElement)\n return createBox();\n const box = visualElement.measureViewportBox();\n // Remove viewport scroll to give page-relative coordinates\n const { scroll } = this.root;\n if (scroll) {\n translateAxis(box.x, scroll.offset.x);\n translateAxis(box.y, scroll.offset.y);\n }\n return box;\n }\n removeElementScroll(box) {\n const boxWithoutScroll = createBox();\n copyBoxInto(boxWithoutScroll, box);\n /**\n * Performance TODO: Keep a cumulative scroll offset down the tree\n * rather than loop back up the path.\n */\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n const { scroll, options } = node;\n if (node !== this.root && scroll && options.layoutScroll) {\n /**\n * If this is a new scroll root, we want to remove all previous scrolls\n * from the viewport box.\n */\n if (scroll.isRoot) {\n copyBoxInto(boxWithoutScroll, box);\n const { scroll: rootScroll } = this.root;\n /**\n * Undo the application of page scroll that was originally added\n * to the measured bounding box.\n */\n if (rootScroll) {\n translateAxis(boxWithoutScroll.x, -rootScroll.offset.x);\n translateAxis(boxWithoutScroll.y, -rootScroll.offset.y);\n }\n }\n translateAxis(boxWithoutScroll.x, scroll.offset.x);\n translateAxis(boxWithoutScroll.y, scroll.offset.y);\n }\n }\n return boxWithoutScroll;\n }\n applyTransform(box, transformOnly = false) {\n const withTransforms = createBox();\n copyBoxInto(withTransforms, box);\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n if (!transformOnly &&\n node.options.layoutScroll &&\n node.scroll &&\n node !== node.root) {\n transformBox(withTransforms, {\n x: -node.scroll.offset.x,\n y: -node.scroll.offset.y,\n });\n }\n if (!hasTransform(node.latestValues))\n continue;\n transformBox(withTransforms, node.latestValues);\n }\n if (hasTransform(this.latestValues)) {\n transformBox(withTransforms, this.latestValues);\n }\n return withTransforms;\n }\n removeTransform(box) {\n const boxWithoutTransform = createBox();\n copyBoxInto(boxWithoutTransform, box);\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n if (!node.instance)\n continue;\n if (!hasTransform(node.latestValues))\n continue;\n hasScale(node.latestValues) && node.updateSnapshot();\n const sourceBox = createBox();\n const nodeBox = node.measurePageBox();\n copyBoxInto(sourceBox, nodeBox);\n removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot ? node.snapshot.layoutBox : undefined, sourceBox);\n }\n if (hasTransform(this.latestValues)) {\n removeBoxTransforms(boxWithoutTransform, this.latestValues);\n }\n return boxWithoutTransform;\n }\n setTargetDelta(delta) {\n this.targetDelta = delta;\n this.root.scheduleUpdateProjection();\n this.isProjectionDirty = true;\n }\n setOptions(options) {\n this.options = {\n ...this.options,\n ...options,\n crossfade: options.crossfade !== undefined ? options.crossfade : true,\n };\n }\n clearMeasurements() {\n this.scroll = undefined;\n this.layout = undefined;\n this.snapshot = undefined;\n this.prevTransformTemplateValue = undefined;\n this.targetDelta = undefined;\n this.target = undefined;\n this.isLayoutDirty = false;\n }\n forceRelativeParentToResolveTarget() {\n if (!this.relativeParent)\n return;\n /**\n * If the parent target isn't up-to-date, force it to update.\n * This is an unfortunate de-optimisation as it means any updating relative\n * projection will cause all the relative parents to recalculate back\n * up the tree.\n */\n if (this.relativeParent.resolvedRelativeTargetAt !==\n frameData.timestamp) {\n this.relativeParent.resolveTargetDelta(true);\n }\n }\n resolveTargetDelta(forceRecalculation = false) {\n var _a;\n /**\n * Once the dirty status of nodes has been spread through the tree, we also\n * need to check if we have a shared node of a different depth that has itself\n * been dirtied.\n */\n const lead = this.getLead();\n this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty);\n this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty);\n this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty);\n const isShared = Boolean(this.resumingFrom) || this !== lead;\n /**\n * We don't use transform for this step of processing so we don't\n * need to check whether any nodes have changed transform.\n */\n const canSkip = !(forceRecalculation ||\n (isShared && this.isSharedProjectionDirty) ||\n this.isProjectionDirty ||\n ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isProjectionDirty) ||\n this.attemptToResolveRelativeTarget);\n if (canSkip)\n return;\n const { layout, layoutId } = this.options;\n /**\n * If we have no layout, we can't perform projection, so early return\n */\n if (!this.layout || !(layout || layoutId))\n return;\n this.resolvedRelativeTargetAt = frameData.timestamp;\n /**\n * If we don't have a targetDelta but do have a layout, we can attempt to resolve\n * a relativeParent. This will allow a component to perform scale correction\n * even if no animation has started.\n */\n // TODO If this is unsuccessful this currently happens every frame\n if (!this.targetDelta && !this.relativeTarget) {\n // TODO: This is a semi-repetition of further down this function, make DRY\n const relativeParent = this.getClosestProjectingParent();\n if (relativeParent &&\n relativeParent.layout &&\n this.animationProgress !== 1) {\n this.relativeParent = relativeParent;\n this.forceRelativeParentToResolveTarget();\n this.relativeTarget = createBox();\n this.relativeTargetOrigin = createBox();\n calcRelativePosition(this.relativeTargetOrigin, this.layout.layoutBox, relativeParent.layout.layoutBox);\n copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);\n }\n else {\n this.relativeParent = this.relativeTarget = undefined;\n }\n }\n /**\n * If we have no relative target or no target delta our target isn't valid\n * for this frame.\n */\n if (!this.relativeTarget && !this.targetDelta)\n return;\n /**\n * Lazy-init target data structure\n */\n if (!this.target) {\n this.target = createBox();\n this.targetWithTransforms = createBox();\n }\n /**\n * If we've got a relative box for this component, resolve it into a target relative to the parent.\n */\n if (this.relativeTarget &&\n this.relativeTargetOrigin &&\n this.relativeParent &&\n this.relativeParent.target) {\n this.forceRelativeParentToResolveTarget();\n calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target);\n /**\n * If we've only got a targetDelta, resolve it into a target\n */\n }\n else if (this.targetDelta) {\n if (Boolean(this.resumingFrom)) {\n // TODO: This is creating a new object every frame\n this.target = this.applyTransform(this.layout.layoutBox);\n }\n else {\n copyBoxInto(this.target, this.layout.layoutBox);\n }\n applyBoxDelta(this.target, this.targetDelta);\n }\n else {\n /**\n * If no target, use own layout as target\n */\n copyBoxInto(this.target, this.layout.layoutBox);\n }\n /**\n * If we've been told to attempt to resolve a relative target, do so.\n */\n if (this.attemptToResolveRelativeTarget) {\n this.attemptToResolveRelativeTarget = false;\n const relativeParent = this.getClosestProjectingParent();\n if (relativeParent &&\n Boolean(relativeParent.resumingFrom) ===\n Boolean(this.resumingFrom) &&\n !relativeParent.options.layoutScroll &&\n relativeParent.target &&\n this.animationProgress !== 1) {\n this.relativeParent = relativeParent;\n this.forceRelativeParentToResolveTarget();\n this.relativeTarget = createBox();\n this.relativeTargetOrigin = createBox();\n calcRelativePosition(this.relativeTargetOrigin, this.target, relativeParent.target);\n copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);\n }\n else {\n this.relativeParent = this.relativeTarget = undefined;\n }\n }\n /**\n * Increase debug counter for resolved target deltas\n */\n projectionFrameData.resolvedTargetDeltas++;\n }\n getClosestProjectingParent() {\n if (!this.parent ||\n hasScale(this.parent.latestValues) ||\n has2DTranslate(this.parent.latestValues)) {\n return undefined;\n }\n if (this.parent.isProjecting()) {\n return this.parent;\n }\n else {\n return this.parent.getClosestProjectingParent();\n }\n }\n isProjecting() {\n return Boolean((this.relativeTarget ||\n this.targetDelta ||\n this.options.layoutRoot) &&\n this.layout);\n }\n calcProjection() {\n var _a;\n const lead = this.getLead();\n const isShared = Boolean(this.resumingFrom) || this !== lead;\n let canSkip = true;\n /**\n * If this is a normal layout animation and neither this node nor its nearest projecting\n * is dirty then we can't skip.\n */\n if (this.isProjectionDirty || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isProjectionDirty)) {\n canSkip = false;\n }\n /**\n * If this is a shared layout animation and this node's shared projection is dirty then\n * we can't skip.\n */\n if (isShared &&\n (this.isSharedProjectionDirty || this.isTransformDirty)) {\n canSkip = false;\n }\n /**\n * If we have resolved the target this frame we must recalculate the\n * projection to ensure it visually represents the internal calculations.\n */\n if (this.resolvedRelativeTargetAt === frameData.timestamp) {\n canSkip = false;\n }\n if (canSkip)\n return;\n const { layout, layoutId } = this.options;\n /**\n * If this section of the tree isn't animating we can\n * delete our target sources for the following frame.\n */\n this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) ||\n this.currentAnimation ||\n this.pendingAnimation);\n if (!this.isTreeAnimating) {\n this.targetDelta = this.relativeTarget = undefined;\n }\n if (!this.layout || !(layout || layoutId))\n return;\n /**\n * Reset the corrected box with the latest values from box, as we're then going\n * to perform mutative operations on it.\n */\n copyBoxInto(this.layoutCorrected, this.layout.layoutBox);\n /**\n * Record previous tree scales before updating.\n */\n const prevTreeScaleX = this.treeScale.x;\n const prevTreeScaleY = this.treeScale.y;\n /**\n * Apply all the parent deltas to this box to produce the corrected box. This\n * is the layout box, as it will appear on screen as a result of the transforms of its parents.\n */\n applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);\n /**\n * If this layer needs to perform scale correction but doesn't have a target,\n * use the layout as the target.\n */\n if (lead.layout &&\n !lead.target &&\n (this.treeScale.x !== 1 || this.treeScale.y !== 1)) {\n lead.target = lead.layout.layoutBox;\n }\n const { target } = lead;\n if (!target) {\n /**\n * If we don't have a target to project into, but we were previously\n * projecting, we want to remove the stored transform and schedule\n * a render to ensure the elements reflect the removed transform.\n */\n if (this.projectionTransform) {\n this.projectionDelta = createDelta();\n this.projectionTransform = \"none\";\n this.scheduleRender();\n }\n return;\n }\n if (!this.projectionDelta) {\n this.projectionDelta = createDelta();\n this.projectionDeltaWithTransform = createDelta();\n }\n const prevProjectionTransform = this.projectionTransform;\n /**\n * Update the delta between the corrected box and the target box before user-set transforms were applied.\n * This will allow us to calculate the corrected borderRadius and boxShadow to compensate\n * for our layout reprojection, but still allow them to be scaled correctly by the user.\n * It might be that to simplify this we may want to accept that user-set scale is also corrected\n * and we wouldn't have to keep and calc both deltas, OR we could support a user setting\n * to allow people to choose whether these styles are corrected based on just the\n * layout reprojection or the final bounding box.\n */\n calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues);\n this.projectionTransform = buildProjectionTransform(this.projectionDelta, this.treeScale);\n if (this.projectionTransform !== prevProjectionTransform ||\n this.treeScale.x !== prevTreeScaleX ||\n this.treeScale.y !== prevTreeScaleY) {\n this.hasProjected = true;\n this.scheduleRender();\n this.notifyListeners(\"projectionUpdate\", target);\n }\n /**\n * Increase debug counter for recalculated projections\n */\n projectionFrameData.recalculatedProjection++;\n }\n hide() {\n this.isVisible = false;\n // TODO: Schedule render\n }\n show() {\n this.isVisible = true;\n // TODO: Schedule render\n }\n scheduleRender(notifyAll = true) {\n this.options.scheduleRender && this.options.scheduleRender();\n if (notifyAll) {\n const stack = this.getStack();\n stack && stack.scheduleRender();\n }\n if (this.resumingFrom && !this.resumingFrom.instance) {\n this.resumingFrom = undefined;\n }\n }\n setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) {\n const snapshot = this.snapshot;\n const snapshotLatestValues = snapshot\n ? snapshot.latestValues\n : {};\n const mixedValues = { ...this.latestValues };\n const targetDelta = createDelta();\n if (!this.relativeParent ||\n !this.relativeParent.options.layoutRoot) {\n this.relativeTarget = this.relativeTargetOrigin = undefined;\n }\n this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;\n const relativeLayout = createBox();\n const snapshotSource = snapshot ? snapshot.source : undefined;\n const layoutSource = this.layout ? this.layout.source : undefined;\n const isSharedLayoutAnimation = snapshotSource !== layoutSource;\n const stack = this.getStack();\n const isOnlyMember = !stack || stack.members.length <= 1;\n const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&\n !isOnlyMember &&\n this.options.crossfade === true &&\n !this.path.some(hasOpacityCrossfade));\n this.animationProgress = 0;\n let prevRelativeTarget;\n this.mixTargetDelta = (latest) => {\n const progress = latest / 1000;\n mixAxisDelta(targetDelta.x, delta.x, progress);\n mixAxisDelta(targetDelta.y, delta.y, progress);\n this.setTargetDelta(targetDelta);\n if (this.relativeTarget &&\n this.relativeTargetOrigin &&\n this.layout &&\n this.relativeParent &&\n this.relativeParent.layout) {\n calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox);\n mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress);\n /**\n * If this is an unchanged relative target we can consider the\n * projection not dirty.\n */\n if (prevRelativeTarget &&\n boxEquals(this.relativeTarget, prevRelativeTarget)) {\n this.isProjectionDirty = false;\n }\n if (!prevRelativeTarget)\n prevRelativeTarget = createBox();\n copyBoxInto(prevRelativeTarget, this.relativeTarget);\n }\n if (isSharedLayoutAnimation) {\n this.animationValues = mixedValues;\n mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);\n }\n this.root.scheduleUpdateProjection();\n this.scheduleRender();\n this.animationProgress = progress;\n };\n this.mixTargetDelta(this.options.layoutRoot ? 1000 : 0);\n }\n startAnimation(options) {\n this.notifyListeners(\"animationStart\");\n this.currentAnimation && this.currentAnimation.stop();\n if (this.resumingFrom && this.resumingFrom.currentAnimation) {\n this.resumingFrom.currentAnimation.stop();\n }\n if (this.pendingAnimation) {\n cancelFrame(this.pendingAnimation);\n this.pendingAnimation = undefined;\n }\n /**\n * Start the animation in the next frame to have a frame with progress 0,\n * where the target is the same as when the animation started, so we can\n * calculate the relative positions correctly for instant transitions.\n */\n this.pendingAnimation = frame.update(() => {\n globalProjectionState.hasAnimatedSinceResize = true;\n this.currentAnimation = animateSingleValue(0, animationTarget, {\n ...options,\n onUpdate: (latest) => {\n this.mixTargetDelta(latest);\n options.onUpdate && options.onUpdate(latest);\n },\n onComplete: () => {\n options.onComplete && options.onComplete();\n this.completeAnimation();\n },\n });\n if (this.resumingFrom) {\n this.resumingFrom.currentAnimation = this.currentAnimation;\n }\n this.pendingAnimation = undefined;\n });\n }\n completeAnimation() {\n if (this.resumingFrom) {\n this.resumingFrom.currentAnimation = undefined;\n this.resumingFrom.preserveOpacity = undefined;\n }\n const stack = this.getStack();\n stack && stack.exitAnimationComplete();\n this.resumingFrom =\n this.currentAnimation =\n this.animationValues =\n undefined;\n this.notifyListeners(\"animationComplete\");\n }\n finishAnimation() {\n if (this.currentAnimation) {\n this.mixTargetDelta && this.mixTargetDelta(animationTarget);\n this.currentAnimation.stop();\n }\n this.completeAnimation();\n }\n applyTransformsToTarget() {\n const lead = this.getLead();\n let { targetWithTransforms, target, layout, latestValues } = lead;\n if (!targetWithTransforms || !target || !layout)\n return;\n /**\n * If we're only animating position, and this element isn't the lead element,\n * then instead of projecting into the lead box we instead want to calculate\n * a new target that aligns the two boxes but maintains the layout shape.\n */\n if (this !== lead &&\n this.layout &&\n layout &&\n shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {\n target = this.target || createBox();\n const xLength = calcLength(this.layout.layoutBox.x);\n target.x.min = lead.target.x.min;\n target.x.max = target.x.min + xLength;\n const yLength = calcLength(this.layout.layoutBox.y);\n target.y.min = lead.target.y.min;\n target.y.max = target.y.min + yLength;\n }\n copyBoxInto(targetWithTransforms, target);\n /**\n * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal.\n * This is the final box that we will then project into by calculating a transform delta and\n * applying it to the corrected box.\n */\n transformBox(targetWithTransforms, latestValues);\n /**\n * Update the delta between the corrected box and the final target box, after\n * user-set transforms are applied to it. This will be used by the renderer to\n * create a transform style that will reproject the element from its layout layout\n * into the desired bounding box.\n */\n calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues);\n }\n registerSharedNode(layoutId, node) {\n if (!this.sharedNodes.has(layoutId)) {\n this.sharedNodes.set(layoutId, new NodeStack());\n }\n const stack = this.sharedNodes.get(layoutId);\n stack.add(node);\n const config = node.options.initialPromotionConfig;\n node.promote({\n transition: config ? config.transition : undefined,\n preserveFollowOpacity: config && config.shouldPreserveFollowOpacity\n ? config.shouldPreserveFollowOpacity(node)\n : undefined,\n });\n }\n isLead() {\n const stack = this.getStack();\n return stack ? stack.lead === this : true;\n }\n getLead() {\n var _a;\n const { layoutId } = this.options;\n return layoutId ? ((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.lead) || this : this;\n }\n getPrevLead() {\n var _a;\n const { layoutId } = this.options;\n return layoutId ? (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.prevLead : undefined;\n }\n getStack() {\n const { layoutId } = this.options;\n if (layoutId)\n return this.root.sharedNodes.get(layoutId);\n }\n promote({ needsReset, transition, preserveFollowOpacity, } = {}) {\n const stack = this.getStack();\n if (stack)\n stack.promote(this, preserveFollowOpacity);\n if (needsReset) {\n this.projectionDelta = undefined;\n this.needsReset = true;\n }\n if (transition)\n this.setOptions({ transition });\n }\n relegate() {\n const stack = this.getStack();\n if (stack) {\n return stack.relegate(this);\n }\n else {\n return false;\n }\n }\n resetRotation() {\n const { visualElement } = this.options;\n if (!visualElement)\n return;\n // If there's no detected rotation values, we can early return without a forced render.\n let hasRotate = false;\n /**\n * An unrolled check for rotation values. Most elements don't have any rotation and\n * skipping the nested loop and new object creation is 50% faster.\n */\n const { latestValues } = visualElement;\n if (latestValues.rotate ||\n latestValues.rotateX ||\n latestValues.rotateY ||\n latestValues.rotateZ) {\n hasRotate = true;\n }\n // If there's no rotation values, we don't need to do any more.\n if (!hasRotate)\n return;\n const resetValues = {};\n // Check the rotate value of all axes and reset to 0\n for (let i = 0; i < transformAxes.length; i++) {\n const key = \"rotate\" + transformAxes[i];\n // Record the rotation and then temporarily set it to 0\n if (latestValues[key]) {\n resetValues[key] = latestValues[key];\n visualElement.setStaticValue(key, 0);\n }\n }\n // Force a render of this element to apply the transform with all rotations\n // set to 0.\n visualElement.render();\n // Put back all the values we reset\n for (const key in resetValues) {\n visualElement.setStaticValue(key, resetValues[key]);\n }\n // Schedule a render for the next frame. This ensures we won't visually\n // see the element with the reset rotate value applied.\n visualElement.scheduleRender();\n }\n getProjectionStyles(styleProp) {\n var _a, _b;\n if (!this.instance || this.isSVG)\n return undefined;\n if (!this.isVisible) {\n return hiddenVisibility;\n }\n const styles = {\n visibility: \"\",\n };\n const transformTemplate = this.getTransformTemplate();\n if (this.needsReset) {\n this.needsReset = false;\n styles.opacity = \"\";\n styles.pointerEvents =\n resolveMotionValue(styleProp === null || styleProp === void 0 ? void 0 : styleProp.pointerEvents) || \"\";\n styles.transform = transformTemplate\n ? transformTemplate(this.latestValues, \"\")\n : \"none\";\n return styles;\n }\n const lead = this.getLead();\n if (!this.projectionDelta || !this.layout || !lead.target) {\n const emptyStyles = {};\n if (this.options.layoutId) {\n emptyStyles.opacity =\n this.latestValues.opacity !== undefined\n ? this.latestValues.opacity\n : 1;\n emptyStyles.pointerEvents =\n resolveMotionValue(styleProp === null || styleProp === void 0 ? void 0 : styleProp.pointerEvents) || \"\";\n }\n if (this.hasProjected && !hasTransform(this.latestValues)) {\n emptyStyles.transform = transformTemplate\n ? transformTemplate({}, \"\")\n : \"none\";\n this.hasProjected = false;\n }\n return emptyStyles;\n }\n const valuesToRender = lead.animationValues || lead.latestValues;\n this.applyTransformsToTarget();\n styles.transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender);\n if (transformTemplate) {\n styles.transform = transformTemplate(valuesToRender, styles.transform);\n }\n const { x, y } = this.projectionDelta;\n styles.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`;\n if (lead.animationValues) {\n /**\n * If the lead component is animating, assign this either the entering/leaving\n * opacity\n */\n styles.opacity =\n lead === this\n ? (_b = (_a = valuesToRender.opacity) !== null && _a !== void 0 ? _a : this.latestValues.opacity) !== null && _b !== void 0 ? _b : 1\n : this.preserveOpacity\n ? this.latestValues.opacity\n : valuesToRender.opacityExit;\n }\n else {\n /**\n * Or we're not animating at all, set the lead component to its layout\n * opacity and other components to hidden.\n */\n styles.opacity =\n lead === this\n ? valuesToRender.opacity !== undefined\n ? valuesToRender.opacity\n : \"\"\n : valuesToRender.opacityExit !== undefined\n ? valuesToRender.opacityExit\n : 0;\n }\n /**\n * Apply scale correction\n */\n for (const key in scaleCorrectors) {\n if (valuesToRender[key] === undefined)\n continue;\n const { correct, applyTo } = scaleCorrectors[key];\n /**\n * Only apply scale correction to the value if we have an\n * active projection transform. Otherwise these values become\n * vulnerable to distortion if the element changes size without\n * a corresponding layout animation.\n */\n const corrected = styles.transform === \"none\"\n ? valuesToRender[key]\n : correct(valuesToRender[key], lead);\n if (applyTo) {\n const num = applyTo.length;\n for (let i = 0; i < num; i++) {\n styles[applyTo[i]] = corrected;\n }\n }\n else {\n styles[key] = corrected;\n }\n }\n /**\n * Disable pointer events on follow components. This is to ensure\n * that if a follow component covers a lead component it doesn't block\n * pointer events on the lead.\n */\n if (this.options.layoutId) {\n styles.pointerEvents =\n lead === this\n ? resolveMotionValue(styleProp === null || styleProp === void 0 ? void 0 : styleProp.pointerEvents) || \"\"\n : \"none\";\n }\n return styles;\n }\n clearSnapshot() {\n this.resumeFrom = this.snapshot = undefined;\n }\n // Only run on root\n resetTree() {\n this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });\n this.root.nodes.forEach(clearMeasurements);\n this.root.sharedNodes.clear();\n }\n };\n}\nfunction updateLayout(node) {\n node.updateLayout();\n}\nfunction notifyLayoutUpdate(node) {\n var _a;\n const snapshot = ((_a = node.resumeFrom) === null || _a === void 0 ? void 0 : _a.snapshot) || node.snapshot;\n if (node.isLead() &&\n node.layout &&\n snapshot &&\n node.hasListeners(\"didUpdate\")) {\n const { layoutBox: layout, measuredBox: measuredLayout } = node.layout;\n const { animationType } = node.options;\n const isShared = snapshot.source !== node.layout.source;\n // TODO Maybe we want to also resize the layout snapshot so we don't trigger\n // animations for instance if layout=\"size\" and an element has only changed position\n if (animationType === \"size\") {\n eachAxis((axis) => {\n const axisSnapshot = isShared\n ? snapshot.measuredBox[axis]\n : snapshot.layoutBox[axis];\n const length = calcLength(axisSnapshot);\n axisSnapshot.min = layout[axis].min;\n axisSnapshot.max = axisSnapshot.min + length;\n });\n }\n else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {\n eachAxis((axis) => {\n const axisSnapshot = isShared\n ? snapshot.measuredBox[axis]\n : snapshot.layoutBox[axis];\n const length = calcLength(layout[axis]);\n axisSnapshot.max = axisSnapshot.min + length;\n /**\n * Ensure relative target gets resized and rerendererd\n */\n if (node.relativeTarget && !node.currentAnimation) {\n node.isProjectionDirty = true;\n node.relativeTarget[axis].max =\n node.relativeTarget[axis].min + length;\n }\n });\n }\n const layoutDelta = createDelta();\n calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);\n const visualDelta = createDelta();\n if (isShared) {\n calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);\n }\n else {\n calcBoxDelta(visualDelta, layout, snapshot.layoutBox);\n }\n const hasLayoutChanged = !isDeltaZero(layoutDelta);\n let hasRelativeTargetChanged = false;\n if (!node.resumeFrom) {\n const relativeParent = node.getClosestProjectingParent();\n /**\n * If the relativeParent is itself resuming from a different element then\n * the relative snapshot is not relavent\n */\n if (relativeParent && !relativeParent.resumeFrom) {\n const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;\n if (parentSnapshot && parentLayout) {\n const relativeSnapshot = createBox();\n calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox);\n const relativeLayout = createBox();\n calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox);\n if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) {\n hasRelativeTargetChanged = true;\n }\n if (relativeParent.options.layoutRoot) {\n node.relativeTarget = relativeLayout;\n node.relativeTargetOrigin = relativeSnapshot;\n node.relativeParent = relativeParent;\n }\n }\n }\n }\n node.notifyListeners(\"didUpdate\", {\n layout,\n snapshot,\n delta: visualDelta,\n layoutDelta,\n hasLayoutChanged,\n hasRelativeTargetChanged,\n });\n }\n else if (node.isLead()) {\n const { onExitComplete } = node.options;\n onExitComplete && onExitComplete();\n }\n /**\n * Clearing transition\n * TODO: Investigate why this transition is being passed in as {type: false } from Framer\n * and why we need it at all\n */\n node.options.transition = undefined;\n}\nfunction propagateDirtyNodes(node) {\n /**\n * Increase debug counter for nodes encountered this frame\n */\n projectionFrameData.totalNodes++;\n if (!node.parent)\n return;\n /**\n * If this node isn't projecting, propagate isProjectionDirty. It will have\n * no performance impact but it will allow the next child that *is* projecting\n * but *isn't* dirty to just check its parent to see if *any* ancestor needs\n * correcting.\n */\n if (!node.isProjecting()) {\n node.isProjectionDirty = node.parent.isProjectionDirty;\n }\n /**\n * Propagate isSharedProjectionDirty and isTransformDirty\n * throughout the whole tree. A future revision can take another look at\n * this but for safety we still recalcualte shared nodes.\n */\n node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty ||\n node.parent.isProjectionDirty ||\n node.parent.isSharedProjectionDirty));\n node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty);\n}\nfunction cleanDirtyNodes(node) {\n node.isProjectionDirty =\n node.isSharedProjectionDirty =\n node.isTransformDirty =\n false;\n}\nfunction clearSnapshot(node) {\n node.clearSnapshot();\n}\nfunction clearMeasurements(node) {\n node.clearMeasurements();\n}\nfunction clearIsLayoutDirty(node) {\n node.isLayoutDirty = false;\n}\nfunction resetTransformStyle(node) {\n const { visualElement } = node.options;\n if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {\n visualElement.notify(\"BeforeLayoutMeasure\");\n }\n node.resetTransform();\n}\nfunction finishAnimation(node) {\n node.finishAnimation();\n node.targetDelta = node.relativeTarget = node.target = undefined;\n node.isProjectionDirty = true;\n}\nfunction resolveTargetDelta(node) {\n node.resolveTargetDelta();\n}\nfunction calcProjection(node) {\n node.calcProjection();\n}\nfunction resetRotation(node) {\n node.resetRotation();\n}\nfunction removeLeadSnapshots(stack) {\n stack.removeLeadSnapshot();\n}\nfunction mixAxisDelta(output, delta, p) {\n output.translate = mix(delta.translate, 0, p);\n output.scale = mix(delta.scale, 1, p);\n output.origin = delta.origin;\n output.originPoint = delta.originPoint;\n}\nfunction mixAxis(output, from, to, p) {\n output.min = mix(from.min, to.min, p);\n output.max = mix(from.max, to.max, p);\n}\nfunction mixBox(output, from, to, p) {\n mixAxis(output.x, from.x, to.x, p);\n mixAxis(output.y, from.y, to.y, p);\n}\nfunction hasOpacityCrossfade(node) {\n return (node.animationValues && node.animationValues.opacityExit !== undefined);\n}\nconst defaultLayoutTransition = {\n duration: 0.45,\n ease: [0.4, 0, 0.1, 1],\n};\nconst userAgentContains = (string) => typeof navigator !== \"undefined\" &&\n navigator.userAgent.toLowerCase().includes(string);\n/**\n * Measured bounding boxes must be rounded in Safari and\n * left untouched in Chrome, otherwise non-integer layouts within scaled-up elements\n * can appear to jump.\n */\nconst roundPoint = userAgentContains(\"applewebkit/\") && !userAgentContains(\"chrome/\")\n ? Math.round\n : noop;\nfunction roundAxis(axis) {\n // Round to the nearest .5 pixels to support subpixel layouts\n axis.min = roundPoint(axis.min);\n axis.max = roundPoint(axis.max);\n}\nfunction roundBox(box) {\n roundAxis(box.x);\n roundAxis(box.y);\n}\nfunction shouldAnimatePositionOnly(animationType, snapshot, layout) {\n return (animationType === \"position\" ||\n (animationType === \"preserve-aspect\" &&\n !isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2)));\n}\n\nexport { cleanDirtyNodes, createProjectionNode, mixAxis, mixAxisDelta, mixBox, propagateDirtyNodes };\n","import { createProjectionNode } from './create-projection-node.mjs';\nimport { addDomEvent } from '../../events/add-dom-event.mjs';\n\nconst DocumentProjectionNode = createProjectionNode({\n attachResizeListener: (ref, notify) => addDomEvent(ref, \"resize\", notify),\n measureScroll: () => ({\n x: document.documentElement.scrollLeft || document.body.scrollLeft,\n y: document.documentElement.scrollTop || document.body.scrollTop,\n }),\n checkIsScrollRoot: () => true,\n});\n\nexport { DocumentProjectionNode };\n","import { createProjectionNode } from './create-projection-node.mjs';\nimport { DocumentProjectionNode } from './DocumentProjectionNode.mjs';\n\nconst rootProjectionNode = {\n current: undefined,\n};\nconst HTMLProjectionNode = createProjectionNode({\n measureScroll: (instance) => ({\n x: instance.scrollLeft,\n y: instance.scrollTop,\n }),\n defaultParent: () => {\n if (!rootProjectionNode.current) {\n const documentNode = new DocumentProjectionNode({});\n documentNode.mount(window);\n documentNode.setOptions({ layoutScroll: true });\n rootProjectionNode.current = documentNode;\n }\n return rootProjectionNode.current;\n },\n resetTransform: (instance, value) => {\n instance.style.transform = value !== undefined ? value : \"none\";\n },\n checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === \"fixed\"),\n});\n\nexport { HTMLProjectionNode, rootProjectionNode };\n","import { DragGesture } from '../../gestures/drag/index.mjs';\nimport { PanGesture } from '../../gestures/pan/index.mjs';\nimport { MeasureLayout } from './layout/MeasureLayout.mjs';\nimport { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs';\n\nconst drag = {\n pan: {\n Feature: PanGesture,\n },\n drag: {\n Feature: DragGesture,\n ProjectionNode: HTMLProjectionNode,\n MeasureLayout,\n },\n};\n\nexport { drag };\n","import { invariant } from '../../../utils/errors.mjs';\nimport { isNumericalString } from '../../../utils/is-numerical-string.mjs';\nimport { isCSSVariableToken } from './is-css-variable.mjs';\n\n/**\n * Parse Framer's special CSS variable format into a CSS token and a fallback.\n *\n * ```\n * `var(--foo, #fff)` => [`--foo`, '#fff']\n * ```\n *\n * @param current\n */\nconst splitCSSVariableRegex = /var\\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\\)/;\nfunction parseCSSVariable(current) {\n const match = splitCSSVariableRegex.exec(current);\n if (!match)\n return [,];\n const [, token, fallback] = match;\n return [token, fallback];\n}\nconst maxDepth = 4;\nfunction getVariableValue(current, element, depth = 1) {\n invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property \"${current}\". This may indicate a circular fallback dependency.`);\n const [token, fallback] = parseCSSVariable(current);\n // No CSS variable detected\n if (!token)\n return;\n // Attempt to read this CSS variable off the element\n const resolved = window.getComputedStyle(element).getPropertyValue(token);\n if (resolved) {\n const trimmed = resolved.trim();\n return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;\n }\n else if (isCSSVariableToken(fallback)) {\n // The fallback might itself be a CSS variable, in which case we attempt to resolve it too.\n return getVariableValue(fallback, element, depth + 1);\n }\n else {\n return fallback;\n }\n}\n/**\n * Resolve CSS variables from\n *\n * @internal\n */\nfunction resolveCSSVariables(visualElement, { ...target }, transitionEnd) {\n const element = visualElement.current;\n if (!(element instanceof Element))\n return { target, transitionEnd };\n // If `transitionEnd` isn't `undefined`, clone it. We could clone `target` and `transitionEnd`\n // only if they change but I think this reads clearer and this isn't a performance-critical path.\n if (transitionEnd) {\n transitionEnd = { ...transitionEnd };\n }\n // Go through existing `MotionValue`s and ensure any existing CSS variables are resolved\n visualElement.values.forEach((value) => {\n const current = value.get();\n if (!isCSSVariableToken(current))\n return;\n const resolved = getVariableValue(current, element);\n if (resolved)\n value.set(resolved);\n });\n // Cycle through every target property and resolve CSS variables. Currently\n // we only read single-var properties like `var(--foo)`, not `calc(var(--foo) + 20px)`\n for (const key in target) {\n const current = target[key];\n if (!isCSSVariableToken(current))\n continue;\n const resolved = getVariableValue(current, element);\n if (!resolved)\n continue;\n // Clone target if it hasn't already been\n target[key] = resolved;\n if (!transitionEnd)\n transitionEnd = {};\n // If the user hasn't already set this key on `transitionEnd`, set it to the unresolved\n // CSS variable. This will ensure that after the animation the component will reflect\n // changes in the value of the CSS variable.\n if (transitionEnd[key] === undefined) {\n transitionEnd[key] = current;\n }\n }\n return { target, transitionEnd };\n}\n\nexport { parseCSSVariable, resolveCSSVariables };\n","import { isKeyframesTarget } from '../../../animation/utils/is-keyframes-target.mjs';\nimport { invariant } from '../../../utils/errors.mjs';\nimport { transformPropOrder } from '../../html/utils/transform.mjs';\nimport { findDimensionValueType } from '../value-types/dimensions.mjs';\nimport { isBrowser } from '../../../utils/is-browser.mjs';\nimport { number } from '../../../value/types/numbers/index.mjs';\nimport { px } from '../../../value/types/numbers/units.mjs';\n\nconst positionalKeys = new Set([\n \"width\",\n \"height\",\n \"top\",\n \"left\",\n \"right\",\n \"bottom\",\n \"x\",\n \"y\",\n \"translateX\",\n \"translateY\",\n]);\nconst isPositionalKey = (key) => positionalKeys.has(key);\nconst hasPositionalKey = (target) => {\n return Object.keys(target).some(isPositionalKey);\n};\nconst isNumOrPxType = (v) => v === number || v === px;\nconst getPosFromMatrix = (matrix, pos) => parseFloat(matrix.split(\", \")[pos]);\nconst getTranslateFromMatrix = (pos2, pos3) => (_bbox, { transform }) => {\n if (transform === \"none\" || !transform)\n return 0;\n const matrix3d = transform.match(/^matrix3d\\((.+)\\)$/);\n if (matrix3d) {\n return getPosFromMatrix(matrix3d[1], pos3);\n }\n else {\n const matrix = transform.match(/^matrix\\((.+)\\)$/);\n if (matrix) {\n return getPosFromMatrix(matrix[1], pos2);\n }\n else {\n return 0;\n }\n }\n};\nconst transformKeys = new Set([\"x\", \"y\", \"z\"]);\nconst nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));\nfunction removeNonTranslationalTransform(visualElement) {\n const removedTransforms = [];\n nonTranslationalTransformKeys.forEach((key) => {\n const value = visualElement.getValue(key);\n if (value !== undefined) {\n removedTransforms.push([key, value.get()]);\n value.set(key.startsWith(\"scale\") ? 1 : 0);\n }\n });\n // Apply changes to element before measurement\n if (removedTransforms.length)\n visualElement.render();\n return removedTransforms;\n}\nconst positionalValues = {\n // Dimensions\n width: ({ x }, { paddingLeft = \"0\", paddingRight = \"0\" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),\n height: ({ y }, { paddingTop = \"0\", paddingBottom = \"0\" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),\n top: (_bbox, { top }) => parseFloat(top),\n left: (_bbox, { left }) => parseFloat(left),\n bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),\n right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),\n // Transform\n x: getTranslateFromMatrix(4, 13),\n y: getTranslateFromMatrix(5, 14),\n};\n// Alias translate longform names\npositionalValues.translateX = positionalValues.x;\npositionalValues.translateY = positionalValues.y;\nconst convertChangedValueTypes = (target, visualElement, changedKeys) => {\n const originBbox = visualElement.measureViewportBox();\n const element = visualElement.current;\n const elementComputedStyle = getComputedStyle(element);\n const { display } = elementComputedStyle;\n const origin = {};\n // If the element is currently set to display: \"none\", make it visible before\n // measuring the target bounding box\n if (display === \"none\") {\n visualElement.setStaticValue(\"display\", target.display || \"block\");\n }\n /**\n * Record origins before we render and update styles\n */\n changedKeys.forEach((key) => {\n origin[key] = positionalValues[key](originBbox, elementComputedStyle);\n });\n // Apply the latest values (as set in checkAndConvertChangedValueTypes)\n visualElement.render();\n const targetBbox = visualElement.measureViewportBox();\n changedKeys.forEach((key) => {\n // Restore styles to their **calculated computed style**, not their actual\n // originally set style. This allows us to animate between equivalent pixel units.\n const value = visualElement.getValue(key);\n value && value.jump(origin[key]);\n target[key] = positionalValues[key](targetBbox, elementComputedStyle);\n });\n return target;\n};\nconst checkAndConvertChangedValueTypes = (visualElement, target, origin = {}, transitionEnd = {}) => {\n target = { ...target };\n transitionEnd = { ...transitionEnd };\n const targetPositionalKeys = Object.keys(target).filter(isPositionalKey);\n // We want to remove any transform values that could affect the element's bounding box before\n // it's measured. We'll reapply these later.\n let removedTransformValues = [];\n let hasAttemptedToRemoveTransformValues = false;\n const changedValueTypeKeys = [];\n targetPositionalKeys.forEach((key) => {\n const value = visualElement.getValue(key);\n if (!visualElement.hasValue(key))\n return;\n let from = origin[key];\n let fromType = findDimensionValueType(from);\n const to = target[key];\n let toType;\n // TODO: The current implementation of this basically throws an error\n // if you try and do value conversion via keyframes. There's probably\n // a way of doing this but the performance implications would need greater scrutiny,\n // as it'd be doing multiple resize-remeasure operations.\n if (isKeyframesTarget(to)) {\n const numKeyframes = to.length;\n const fromIndex = to[0] === null ? 1 : 0;\n from = to[fromIndex];\n fromType = findDimensionValueType(from);\n for (let i = fromIndex; i < numKeyframes; i++) {\n /**\n * Don't allow wildcard keyframes to be used to detect\n * a difference in value types.\n */\n if (to[i] === null)\n break;\n if (!toType) {\n toType = findDimensionValueType(to[i]);\n invariant(toType === fromType ||\n (isNumOrPxType(fromType) && isNumOrPxType(toType)), \"Keyframes must be of the same dimension as the current value\");\n }\n else {\n invariant(findDimensionValueType(to[i]) === toType, \"All keyframes must be of the same type\");\n }\n }\n }\n else {\n toType = findDimensionValueType(to);\n }\n if (fromType !== toType) {\n // If they're both just number or px, convert them both to numbers rather than\n // relying on resize/remeasure to convert (which is wasteful in this situation)\n if (isNumOrPxType(fromType) && isNumOrPxType(toType)) {\n const current = value.get();\n if (typeof current === \"string\") {\n value.set(parseFloat(current));\n }\n if (typeof to === \"string\") {\n target[key] = parseFloat(to);\n }\n else if (Array.isArray(to) && toType === px) {\n target[key] = to.map(parseFloat);\n }\n }\n else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) &&\n (toType === null || toType === void 0 ? void 0 : toType.transform) &&\n (from === 0 || to === 0)) {\n // If one or the other value is 0, it's safe to coerce it to the\n // type of the other without measurement\n if (from === 0) {\n value.set(toType.transform(from));\n }\n else {\n target[key] = fromType.transform(to);\n }\n }\n else {\n // If we're going to do value conversion via DOM measurements, we first\n // need to remove non-positional transform values that could affect the bbox measurements.\n if (!hasAttemptedToRemoveTransformValues) {\n removedTransformValues =\n removeNonTranslationalTransform(visualElement);\n hasAttemptedToRemoveTransformValues = true;\n }\n changedValueTypeKeys.push(key);\n transitionEnd[key] =\n transitionEnd[key] !== undefined\n ? transitionEnd[key]\n : target[key];\n value.jump(to);\n }\n }\n });\n if (changedValueTypeKeys.length) {\n const scrollY = changedValueTypeKeys.indexOf(\"height\") >= 0\n ? window.pageYOffset\n : null;\n const convertedTarget = convertChangedValueTypes(target, visualElement, changedValueTypeKeys);\n // If we removed transform values, reapply them before the next render\n if (removedTransformValues.length) {\n removedTransformValues.forEach(([key, value]) => {\n visualElement.getValue(key).set(value);\n });\n }\n // Reapply original values\n visualElement.render();\n // Restore scroll position\n if (isBrowser && scrollY !== null) {\n window.scrollTo({ top: scrollY });\n }\n return { target: convertedTarget, transitionEnd };\n }\n else {\n return { target, transitionEnd };\n }\n};\n/**\n * Convert value types for x/y/width/height/top/left/bottom/right\n *\n * Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'`\n *\n * @internal\n */\nfunction unitConversion(visualElement, target, origin, transitionEnd) {\n return hasPositionalKey(target)\n ? checkAndConvertChangedValueTypes(visualElement, target, origin, transitionEnd)\n : { target, transitionEnd };\n}\n\nexport { positionalValues, unitConversion };\n","import { resolveCSSVariables } from './css-variables-conversion.mjs';\nimport { unitConversion } from './unit-conversion.mjs';\n\n/**\n * Parse a DOM variant to make it animatable. This involves resolving CSS variables\n * and ensuring animations like \"20%\" => \"calc(50vw)\" are performed in pixels.\n */\nconst parseDomVariant = (visualElement, target, origin, transitionEnd) => {\n const resolved = resolveCSSVariables(visualElement, target, transitionEnd);\n target = resolved.target;\n transitionEnd = resolved.transitionEnd;\n return unitConversion(visualElement, target, origin, transitionEnd);\n};\n\nexport { parseDomVariant };\n","// Does this device prefer reduced motion? Returns `null` server-side.\nconst prefersReducedMotion = { current: null };\nconst hasReducedMotionListener = { current: false };\n\nexport { hasReducedMotionListener, prefersReducedMotion };\n","import { isBrowser } from '../is-browser.mjs';\nimport { hasReducedMotionListener, prefersReducedMotion } from './state.mjs';\n\nfunction initPrefersReducedMotion() {\n hasReducedMotionListener.current = true;\n if (!isBrowser)\n return;\n if (window.matchMedia) {\n const motionMediaQuery = window.matchMedia(\"(prefers-reduced-motion)\");\n const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches);\n motionMediaQuery.addListener(setReducedMotionPreferences);\n setReducedMotionPreferences();\n }\n else {\n prefersReducedMotion.current = false;\n }\n}\n\nexport { initPrefersReducedMotion };\n","import { isWillChangeMotionValue } from '../../value/use-will-change/is.mjs';\nimport { warnOnce } from '../../utils/warn-once.mjs';\nimport { motionValue } from '../../value/index.mjs';\nimport { isMotionValue } from '../../value/utils/is-motion-value.mjs';\n\nfunction updateMotionValuesFromProps(element, next, prev) {\n const { willChange } = next;\n for (const key in next) {\n const nextValue = next[key];\n const prevValue = prev[key];\n if (isMotionValue(nextValue)) {\n /**\n * If this is a motion value found in props or style, we want to add it\n * to our visual element's motion value map.\n */\n element.addValue(key, nextValue);\n if (isWillChangeMotionValue(willChange)) {\n willChange.add(key);\n }\n /**\n * Check the version of the incoming motion value with this version\n * and warn against mismatches.\n */\n if (process.env.NODE_ENV === \"development\") {\n warnOnce(nextValue.version === \"10.18.0\", `Attempting to mix Framer Motion versions ${nextValue.version} with 10.18.0 may not work as expected.`);\n }\n }\n else if (isMotionValue(prevValue)) {\n /**\n * If we're swapping from a motion value to a static value,\n * create a new motion value from that\n */\n element.addValue(key, motionValue(nextValue, { owner: element }));\n if (isWillChangeMotionValue(willChange)) {\n willChange.remove(key);\n }\n }\n else if (prevValue !== nextValue) {\n /**\n * If this is a flat value that has changed, update the motion value\n * or create one if it doesn't exist. We only want to do this if we're\n * not handling the value with our animation state.\n */\n if (element.hasValue(key)) {\n const existingValue = element.getValue(key);\n // TODO: Only update values that aren't being animated or even looked at\n !existingValue.hasAnimated && existingValue.set(nextValue);\n }\n else {\n const latestValue = element.getStaticValue(key);\n element.addValue(key, motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element }));\n }\n }\n }\n // Handle removed values\n for (const key in prev) {\n if (next[key] === undefined)\n element.removeValue(key);\n }\n return next;\n}\n\nexport { updateMotionValuesFromProps };\n","const visualElementStore = new WeakMap();\n\nexport { visualElementStore };\n","import { warning, invariant } from '../utils/errors.mjs';\nimport { createBox } from '../projection/geometry/models.mjs';\nimport { isRefObject } from '../utils/is-ref-object.mjs';\nimport { initPrefersReducedMotion } from '../utils/reduced-motion/index.mjs';\nimport { hasReducedMotionListener, prefersReducedMotion } from '../utils/reduced-motion/state.mjs';\nimport { SubscriptionManager } from '../utils/subscription-manager.mjs';\nimport { motionValue } from '../value/index.mjs';\nimport { isWillChangeMotionValue } from '../value/use-will-change/is.mjs';\nimport { isMotionValue } from '../value/utils/is-motion-value.mjs';\nimport { transformProps } from './html/utils/transform.mjs';\nimport { isControllingVariants, isVariantNode } from './utils/is-controlling-variants.mjs';\nimport { isVariantLabel } from './utils/is-variant-label.mjs';\nimport { updateMotionValuesFromProps } from './utils/motion-values.mjs';\nimport { resolveVariantFromProps } from './utils/resolve-variants.mjs';\nimport { warnOnce } from '../utils/warn-once.mjs';\nimport { featureDefinitions } from '../motion/features/definitions.mjs';\nimport { variantProps } from './utils/variant-props.mjs';\nimport { visualElementStore } from './store.mjs';\nimport { frame, cancelFrame } from '../frameloop/frame.mjs';\n\nconst featureNames = Object.keys(featureDefinitions);\nconst numFeatures = featureNames.length;\nconst propEventHandlers = [\n \"AnimationStart\",\n \"AnimationComplete\",\n \"Update\",\n \"BeforeLayoutMeasure\",\n \"LayoutMeasure\",\n \"LayoutAnimationStart\",\n \"LayoutAnimationComplete\",\n];\nconst numVariantProps = variantProps.length;\n/**\n * A VisualElement is an imperative abstraction around UI elements such as\n * HTMLElement, SVGElement, Three.Object3D etc.\n */\nclass VisualElement {\n constructor({ parent, props, presenceContext, reducedMotionConfig, visualState, }, options = {}) {\n /**\n * A reference to the current underlying Instance, e.g. a HTMLElement\n * or Three.Mesh etc.\n */\n this.current = null;\n /**\n * A set containing references to this VisualElement's children.\n */\n this.children = new Set();\n /**\n * Determine what role this visual element should take in the variant tree.\n */\n this.isVariantNode = false;\n this.isControllingVariants = false;\n /**\n * Decides whether this VisualElement should animate in reduced motion\n * mode.\n *\n * TODO: This is currently set on every individual VisualElement but feels\n * like it could be set globally.\n */\n this.shouldReduceMotion = null;\n /**\n * A map of all motion values attached to this visual element. Motion\n * values are source of truth for any given animated value. A motion\n * value might be provided externally by the component via props.\n */\n this.values = new Map();\n /**\n * Cleanup functions for active features (hover/tap/exit etc)\n */\n this.features = {};\n /**\n * A map of every subscription that binds the provided or generated\n * motion values onChange listeners to this visual element.\n */\n this.valueSubscriptions = new Map();\n /**\n * A reference to the previously-provided motion values as returned\n * from scrapeMotionValuesFromProps. We use the keys in here to determine\n * if any motion values need to be removed after props are updated.\n */\n this.prevMotionValues = {};\n /**\n * An object containing a SubscriptionManager for each active event.\n */\n this.events = {};\n /**\n * An object containing an unsubscribe function for each prop event subscription.\n * For example, every \"Update\" event can have multiple subscribers via\n * VisualElement.on(), but only one of those can be defined via the onUpdate prop.\n */\n this.propEventSubscriptions = {};\n this.notifyUpdate = () => this.notify(\"Update\", this.latestValues);\n this.render = () => {\n if (!this.current)\n return;\n this.triggerBuild();\n this.renderInstance(this.current, this.renderState, this.props.style, this.projection);\n };\n this.scheduleRender = () => frame.render(this.render, false, true);\n const { latestValues, renderState } = visualState;\n this.latestValues = latestValues;\n this.baseTarget = { ...latestValues };\n this.initialValues = props.initial ? { ...latestValues } : {};\n this.renderState = renderState;\n this.parent = parent;\n this.props = props;\n this.presenceContext = presenceContext;\n this.depth = parent ? parent.depth + 1 : 0;\n this.reducedMotionConfig = reducedMotionConfig;\n this.options = options;\n this.isControllingVariants = isControllingVariants(props);\n this.isVariantNode = isVariantNode(props);\n if (this.isVariantNode) {\n this.variantChildren = new Set();\n }\n this.manuallyAnimateOnMount = Boolean(parent && parent.current);\n /**\n * Any motion values that are provided to the element when created\n * aren't yet bound to the element, as this would technically be impure.\n * However, we iterate through the motion values and set them to the\n * initial values for this component.\n *\n * TODO: This is impure and we should look at changing this to run on mount.\n * Doing so will break some tests but this isn't neccessarily a breaking change,\n * more a reflection of the test.\n */\n const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {});\n for (const key in initialMotionValues) {\n const value = initialMotionValues[key];\n if (latestValues[key] !== undefined && isMotionValue(value)) {\n value.set(latestValues[key], false);\n if (isWillChangeMotionValue(willChange)) {\n willChange.add(key);\n }\n }\n }\n }\n /**\n * This method takes React props and returns found MotionValues. For example, HTML\n * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.\n *\n * This isn't an abstract method as it needs calling in the constructor, but it is\n * intended to be one.\n */\n scrapeMotionValuesFromProps(_props, _prevProps) {\n return {};\n }\n mount(instance) {\n this.current = instance;\n visualElementStore.set(instance, this);\n if (this.projection && !this.projection.instance) {\n this.projection.mount(instance);\n }\n if (this.parent && this.isVariantNode && !this.isControllingVariants) {\n this.removeFromVariantTree = this.parent.addVariantChild(this);\n }\n this.values.forEach((value, key) => this.bindToMotionValue(key, value));\n if (!hasReducedMotionListener.current) {\n initPrefersReducedMotion();\n }\n this.shouldReduceMotion =\n this.reducedMotionConfig === \"never\"\n ? false\n : this.reducedMotionConfig === \"always\"\n ? true\n : prefersReducedMotion.current;\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(this.shouldReduceMotion !== true, \"You have Reduced Motion enabled on your device. Animations may not appear as expected.\");\n }\n if (this.parent)\n this.parent.children.add(this);\n this.update(this.props, this.presenceContext);\n }\n unmount() {\n visualElementStore.delete(this.current);\n this.projection && this.projection.unmount();\n cancelFrame(this.notifyUpdate);\n cancelFrame(this.render);\n this.valueSubscriptions.forEach((remove) => remove());\n this.removeFromVariantTree && this.removeFromVariantTree();\n this.parent && this.parent.children.delete(this);\n for (const key in this.events) {\n this.events[key].clear();\n }\n for (const key in this.features) {\n this.features[key].unmount();\n }\n this.current = null;\n }\n bindToMotionValue(key, value) {\n const valueIsTransform = transformProps.has(key);\n const removeOnChange = value.on(\"change\", (latestValue) => {\n this.latestValues[key] = latestValue;\n this.props.onUpdate &&\n frame.update(this.notifyUpdate, false, true);\n if (valueIsTransform && this.projection) {\n this.projection.isTransformDirty = true;\n }\n });\n const removeOnRenderRequest = value.on(\"renderRequest\", this.scheduleRender);\n this.valueSubscriptions.set(key, () => {\n removeOnChange();\n removeOnRenderRequest();\n });\n }\n sortNodePosition(other) {\n /**\n * If these nodes aren't even of the same type we can't compare their depth.\n */\n if (!this.current ||\n !this.sortInstanceNodePosition ||\n this.type !== other.type) {\n return 0;\n }\n return this.sortInstanceNodePosition(this.current, other.current);\n }\n loadFeatures({ children, ...renderedProps }, isStrict, preloadedFeatures, initialLayoutGroupConfig) {\n let ProjectionNodeConstructor;\n let MeasureLayout;\n /**\n * If we're in development mode, check to make sure we're not rendering a motion component\n * as a child of LazyMotion, as this will break the file-size benefits of using it.\n */\n if (process.env.NODE_ENV !== \"production\" &&\n preloadedFeatures &&\n isStrict) {\n const strictMessage = \"You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.\";\n renderedProps.ignoreStrict\n ? warning(false, strictMessage)\n : invariant(false, strictMessage);\n }\n for (let i = 0; i < numFeatures; i++) {\n const name = featureNames[i];\n const { isEnabled, Feature: FeatureConstructor, ProjectionNode, MeasureLayout: MeasureLayoutComponent, } = featureDefinitions[name];\n if (ProjectionNode)\n ProjectionNodeConstructor = ProjectionNode;\n if (isEnabled(renderedProps)) {\n if (!this.features[name] && FeatureConstructor) {\n this.features[name] = new FeatureConstructor(this);\n }\n if (MeasureLayoutComponent) {\n MeasureLayout = MeasureLayoutComponent;\n }\n }\n }\n if ((this.type === \"html\" || this.type === \"svg\") &&\n !this.projection &&\n ProjectionNodeConstructor) {\n this.projection = new ProjectionNodeConstructor(this.latestValues, this.parent && this.parent.projection);\n const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, } = renderedProps;\n this.projection.setOptions({\n layoutId,\n layout,\n alwaysMeasureLayout: Boolean(drag) ||\n (dragConstraints && isRefObject(dragConstraints)),\n visualElement: this,\n scheduleRender: () => this.scheduleRender(),\n /**\n * TODO: Update options in an effect. This could be tricky as it'll be too late\n * to update by the time layout animations run.\n * We also need to fix this safeToRemove by linking it up to the one returned by usePresence,\n * ensuring it gets called if there's no potential layout animations.\n *\n */\n animationType: typeof layout === \"string\" ? layout : \"both\",\n initialPromotionConfig: initialLayoutGroupConfig,\n layoutScroll,\n layoutRoot,\n });\n }\n return MeasureLayout;\n }\n updateFeatures() {\n for (const key in this.features) {\n const feature = this.features[key];\n if (feature.isMounted) {\n feature.update();\n }\n else {\n feature.mount();\n feature.isMounted = true;\n }\n }\n }\n triggerBuild() {\n this.build(this.renderState, this.latestValues, this.options, this.props);\n }\n /**\n * Measure the current viewport box with or without transforms.\n * Only measures axis-aligned boxes, rotate and skew must be manually\n * removed with a re-render to work.\n */\n measureViewportBox() {\n return this.current\n ? this.measureInstanceViewportBox(this.current, this.props)\n : createBox();\n }\n getStaticValue(key) {\n return this.latestValues[key];\n }\n setStaticValue(key, value) {\n this.latestValues[key] = value;\n }\n /**\n * Make a target animatable by Popmotion. For instance, if we're\n * trying to animate width from 100px to 100vw we need to measure 100vw\n * in pixels to determine what we really need to animate to. This is also\n * pluggable to support Framer's custom value types like Color,\n * and CSS variables.\n */\n makeTargetAnimatable(target, canMutate = true) {\n return this.makeTargetAnimatableFromInstance(target, this.props, canMutate);\n }\n /**\n * Update the provided props. Ensure any newly-added motion values are\n * added to our map, old ones removed, and listeners updated.\n */\n update(props, presenceContext) {\n if (props.transformTemplate || this.props.transformTemplate) {\n this.scheduleRender();\n }\n this.prevProps = this.props;\n this.props = props;\n this.prevPresenceContext = this.presenceContext;\n this.presenceContext = presenceContext;\n /**\n * Update prop event handlers ie onAnimationStart, onAnimationComplete\n */\n for (let i = 0; i < propEventHandlers.length; i++) {\n const key = propEventHandlers[i];\n if (this.propEventSubscriptions[key]) {\n this.propEventSubscriptions[key]();\n delete this.propEventSubscriptions[key];\n }\n const listener = props[\"on\" + key];\n if (listener) {\n this.propEventSubscriptions[key] = this.on(key, listener);\n }\n }\n this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps), this.prevMotionValues);\n if (this.handleChildMotionValue) {\n this.handleChildMotionValue();\n }\n }\n getProps() {\n return this.props;\n }\n /**\n * Returns the variant definition with a given name.\n */\n getVariant(name) {\n return this.props.variants ? this.props.variants[name] : undefined;\n }\n /**\n * Returns the defined default transition on this component.\n */\n getDefaultTransition() {\n return this.props.transition;\n }\n getTransformPagePoint() {\n return this.props.transformPagePoint;\n }\n getClosestVariantNode() {\n return this.isVariantNode\n ? this\n : this.parent\n ? this.parent.getClosestVariantNode()\n : undefined;\n }\n getVariantContext(startAtParent = false) {\n if (startAtParent) {\n return this.parent ? this.parent.getVariantContext() : undefined;\n }\n if (!this.isControllingVariants) {\n const context = this.parent\n ? this.parent.getVariantContext() || {}\n : {};\n if (this.props.initial !== undefined) {\n context.initial = this.props.initial;\n }\n return context;\n }\n const context = {};\n for (let i = 0; i < numVariantProps; i++) {\n const name = variantProps[i];\n const prop = this.props[name];\n if (isVariantLabel(prop) || prop === false) {\n context[name] = prop;\n }\n }\n return context;\n }\n /**\n * Add a child visual element to our set of children.\n */\n addVariantChild(child) {\n const closestVariantNode = this.getClosestVariantNode();\n if (closestVariantNode) {\n closestVariantNode.variantChildren &&\n closestVariantNode.variantChildren.add(child);\n return () => closestVariantNode.variantChildren.delete(child);\n }\n }\n /**\n * Add a motion value and bind it to this visual element.\n */\n addValue(key, value) {\n // Remove existing value if it exists\n if (value !== this.values.get(key)) {\n this.removeValue(key);\n this.bindToMotionValue(key, value);\n }\n this.values.set(key, value);\n this.latestValues[key] = value.get();\n }\n /**\n * Remove a motion value and unbind any active subscriptions.\n */\n removeValue(key) {\n this.values.delete(key);\n const unsubscribe = this.valueSubscriptions.get(key);\n if (unsubscribe) {\n unsubscribe();\n this.valueSubscriptions.delete(key);\n }\n delete this.latestValues[key];\n this.removeValueFromRenderState(key, this.renderState);\n }\n /**\n * Check whether we have a motion value for this key\n */\n hasValue(key) {\n return this.values.has(key);\n }\n getValue(key, defaultValue) {\n if (this.props.values && this.props.values[key]) {\n return this.props.values[key];\n }\n let value = this.values.get(key);\n if (value === undefined && defaultValue !== undefined) {\n value = motionValue(defaultValue, { owner: this });\n this.addValue(key, value);\n }\n return value;\n }\n /**\n * If we're trying to animate to a previously unencountered value,\n * we need to check for it in our state and as a last resort read it\n * directly from the instance (which might have performance implications).\n */\n readValue(key) {\n var _a;\n return this.latestValues[key] !== undefined || !this.current\n ? this.latestValues[key]\n : (_a = this.getBaseTargetFromProps(this.props, key)) !== null && _a !== void 0 ? _a : this.readValueFromInstance(this.current, key, this.options);\n }\n /**\n * Set the base target to later animate back to. This is currently\n * only hydrated on creation and when we first read a value.\n */\n setBaseTarget(key, value) {\n this.baseTarget[key] = value;\n }\n /**\n * Find the base target for a value thats been removed from all animation\n * props.\n */\n getBaseTarget(key) {\n var _a;\n const { initial } = this.props;\n const valueFromInitial = typeof initial === \"string\" || typeof initial === \"object\"\n ? (_a = resolveVariantFromProps(this.props, initial)) === null || _a === void 0 ? void 0 : _a[key]\n : undefined;\n /**\n * If this value still exists in the current initial variant, read that.\n */\n if (initial && valueFromInitial !== undefined) {\n return valueFromInitial;\n }\n /**\n * Alternatively, if this VisualElement config has defined a getBaseTarget\n * so we can read the value from an alternative source, try that.\n */\n const target = this.getBaseTargetFromProps(this.props, key);\n if (target !== undefined && !isMotionValue(target))\n return target;\n /**\n * If the value was initially defined on initial, but it doesn't any more,\n * return undefined. Otherwise return the value as initially read from the DOM.\n */\n return this.initialValues[key] !== undefined &&\n valueFromInitial === undefined\n ? undefined\n : this.baseTarget[key];\n }\n on(eventName, callback) {\n if (!this.events[eventName]) {\n this.events[eventName] = new SubscriptionManager();\n }\n return this.events[eventName].add(callback);\n }\n notify(eventName, ...args) {\n if (this.events[eventName]) {\n this.events[eventName].notify(...args);\n }\n }\n}\n\nexport { VisualElement };\n","import { getOrigin, checkTargetForNewValues } from '../utils/setters.mjs';\nimport { parseDomVariant } from './utils/parse-dom-variant.mjs';\nimport { VisualElement } from '../VisualElement.mjs';\n\nclass DOMVisualElement extends VisualElement {\n sortInstanceNodePosition(a, b) {\n /**\n * compareDocumentPosition returns a bitmask, by using the bitwise &\n * we're returning true if 2 in that bitmask is set to true. 2 is set\n * to true if b preceeds a.\n */\n return a.compareDocumentPosition(b) & 2 ? 1 : -1;\n }\n getBaseTargetFromProps(props, key) {\n return props.style ? props.style[key] : undefined;\n }\n removeValueFromRenderState(key, { vars, style }) {\n delete vars[key];\n delete style[key];\n }\n makeTargetAnimatableFromInstance({ transition, transitionEnd, ...target }, { transformValues }, isMounted) {\n let origin = getOrigin(target, transition || {}, this);\n /**\n * If Framer has provided a function to convert `Color` etc value types, convert them\n */\n if (transformValues) {\n if (transitionEnd)\n transitionEnd = transformValues(transitionEnd);\n if (target)\n target = transformValues(target);\n if (origin)\n origin = transformValues(origin);\n }\n if (isMounted) {\n checkTargetForNewValues(this, target, origin);\n const parsed = parseDomVariant(this, target, origin, transitionEnd);\n transitionEnd = parsed.transitionEnd;\n target = parsed.target;\n }\n return {\n transition,\n transitionEnd,\n ...target,\n };\n }\n}\n\nexport { DOMVisualElement };\n","import { buildHTMLStyles } from './utils/build-styles.mjs';\nimport { isCSSVariableName } from '../dom/utils/is-css-variable.mjs';\nimport { transformProps } from './utils/transform.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\nimport { renderHTML } from './utils/render.mjs';\nimport { getDefaultValueType } from '../dom/value-types/defaults.mjs';\nimport { measureViewportBox } from '../../projection/utils/measure.mjs';\nimport { DOMVisualElement } from '../dom/DOMVisualElement.mjs';\nimport { isMotionValue } from '../../value/utils/is-motion-value.mjs';\n\nfunction getComputedStyle(element) {\n return window.getComputedStyle(element);\n}\nclass HTMLVisualElement extends DOMVisualElement {\n constructor() {\n super(...arguments);\n this.type = \"html\";\n }\n readValueFromInstance(instance, key) {\n if (transformProps.has(key)) {\n const defaultType = getDefaultValueType(key);\n return defaultType ? defaultType.default || 0 : 0;\n }\n else {\n const computedStyle = getComputedStyle(instance);\n const value = (isCSSVariableName(key)\n ? computedStyle.getPropertyValue(key)\n : computedStyle[key]) || 0;\n return typeof value === \"string\" ? value.trim() : value;\n }\n }\n measureInstanceViewportBox(instance, { transformPagePoint }) {\n return measureViewportBox(instance, transformPagePoint);\n }\n build(renderState, latestValues, options, props) {\n buildHTMLStyles(renderState, latestValues, options, props.transformTemplate);\n }\n scrapeMotionValuesFromProps(props, prevProps) {\n return scrapeMotionValuesFromProps(props, prevProps);\n }\n handleChildMotionValue() {\n if (this.childSubscription) {\n this.childSubscription();\n delete this.childSubscription;\n }\n const { children } = this.props;\n if (isMotionValue(children)) {\n this.childSubscription = children.on(\"change\", (latest) => {\n if (this.current)\n this.current.textContent = `${latest}`;\n });\n }\n }\n renderInstance(instance, renderState, styleProp, projection) {\n renderHTML(instance, renderState, styleProp, projection);\n }\n}\n\nexport { HTMLVisualElement, getComputedStyle };\n","import { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\nimport { DOMVisualElement } from '../dom/DOMVisualElement.mjs';\nimport { buildSVGAttrs } from './utils/build-attrs.mjs';\nimport { camelToDash } from '../dom/utils/camel-to-dash.mjs';\nimport { camelCaseAttributes } from './utils/camel-case-attrs.mjs';\nimport { transformProps } from '../html/utils/transform.mjs';\nimport { renderSVG } from './utils/render.mjs';\nimport { getDefaultValueType } from '../dom/value-types/defaults.mjs';\nimport { createBox } from '../../projection/geometry/models.mjs';\nimport { isSVGTag } from './utils/is-svg-tag.mjs';\n\nclass SVGVisualElement extends DOMVisualElement {\n constructor() {\n super(...arguments);\n this.type = \"svg\";\n this.isSVGTag = false;\n }\n getBaseTargetFromProps(props, key) {\n return props[key];\n }\n readValueFromInstance(instance, key) {\n if (transformProps.has(key)) {\n const defaultType = getDefaultValueType(key);\n return defaultType ? defaultType.default || 0 : 0;\n }\n key = !camelCaseAttributes.has(key) ? camelToDash(key) : key;\n return instance.getAttribute(key);\n }\n measureInstanceViewportBox() {\n return createBox();\n }\n scrapeMotionValuesFromProps(props, prevProps) {\n return scrapeMotionValuesFromProps(props, prevProps);\n }\n build(renderState, latestValues, options, props) {\n buildSVGAttrs(renderState, latestValues, options, this.isSVGTag, props.transformTemplate);\n }\n renderInstance(instance, renderState, styleProp, projection) {\n renderSVG(instance, renderState, styleProp, projection);\n }\n mount(instance) {\n this.isSVGTag = isSVGTag(instance.tagName);\n super.mount(instance);\n }\n}\n\nexport { SVGVisualElement };\n","import { HTMLVisualElement } from '../html/HTMLVisualElement.mjs';\nimport { SVGVisualElement } from '../svg/SVGVisualElement.mjs';\nimport { isSVGComponent } from './utils/is-svg-component.mjs';\n\nconst createDomVisualElement = (Component, options) => {\n return isSVGComponent(Component)\n ? new SVGVisualElement(options, { enableHardwareAcceleration: false })\n : new HTMLVisualElement(options, { enableHardwareAcceleration: true });\n};\n\nexport { createDomVisualElement };\n","import { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs';\nimport { MeasureLayout } from './layout/MeasureLayout.mjs';\n\nconst layout = {\n layout: {\n ProjectionNode: HTMLProjectionNode,\n MeasureLayout,\n },\n};\n\nexport { layout };\n","import { createMotionComponent } from '../../motion/index.mjs';\nimport { createMotionProxy } from './motion-proxy.mjs';\nimport { createDomMotionConfig } from './utils/create-config.mjs';\nimport { gestureAnimations } from '../../motion/features/gestures.mjs';\nimport { animations } from '../../motion/features/animations.mjs';\nimport { drag } from '../../motion/features/drag.mjs';\nimport { createDomVisualElement } from './create-visual-element.mjs';\nimport { layout } from '../../motion/features/layout.mjs';\n\nconst preloadedFeatures = {\n ...animations,\n ...gestureAnimations,\n ...drag,\n ...layout,\n};\n/**\n * HTML & SVG components, optimised for use with gestures and animation. These can be used as\n * drop-in replacements for any HTML & SVG component, all CSS & SVG properties are supported.\n *\n * @public\n */\nconst motion = /*@__PURE__*/ createMotionProxy((Component, config) => createDomMotionConfig(Component, config, preloadedFeatures, createDomVisualElement));\n/**\n * Create a DOM `motion` component with the provided string. This is primarily intended\n * as a full alternative to `motion` for consumers who have to support environments that don't\n * support `Proxy`.\n *\n * ```javascript\n * import { createDomMotionComponent } from \"framer-motion\"\n *\n * const motion = {\n * div: createDomMotionComponent('div')\n * }\n * ```\n *\n * @public\n */\nfunction createDomMotionComponent(key) {\n return createMotionComponent(createDomMotionConfig(key, { forwardMotionProps: false }, preloadedFeatures, createDomVisualElement));\n}\n\nexport { createDomMotionComponent, motion };\n","import { useRef } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-effect.mjs';\n\nfunction useIsMounted() {\n const isMounted = useRef(false);\n useIsomorphicLayoutEffect(() => {\n isMounted.current = true;\n return () => {\n isMounted.current = false;\n };\n }, []);\n return isMounted;\n}\n\nexport { useIsMounted };\n","import { useState, useCallback } from 'react';\nimport { useIsMounted } from './use-is-mounted.mjs';\nimport { frame } from '../frameloop/frame.mjs';\n\nfunction useForceUpdate() {\n const isMounted = useIsMounted();\n const [forcedRenderCount, setForcedRenderCount] = useState(0);\n const forceRender = useCallback(() => {\n isMounted.current && setForcedRenderCount(forcedRenderCount + 1);\n }, [forcedRenderCount]);\n /**\n * Defer this to the end of the next animation frame in case there are multiple\n * synchronous calls.\n */\n const deferredForceRender = useCallback(() => frame.postRender(forceRender), [forceRender]);\n return [deferredForceRender, forcedRenderCount];\n}\n\nexport { useForceUpdate };\n","import * as React from 'react';\nimport { useId, useRef, useInsertionEffect } from 'react';\n\n/**\n * Measurement functionality has to be within a separate component\n * to leverage snapshot lifecycle.\n */\nclass PopChildMeasure extends React.Component {\n getSnapshotBeforeUpdate(prevProps) {\n const element = this.props.childRef.current;\n if (element && prevProps.isPresent && !this.props.isPresent) {\n const size = this.props.sizeRef.current;\n size.height = element.offsetHeight || 0;\n size.width = element.offsetWidth || 0;\n size.top = element.offsetTop;\n size.left = element.offsetLeft;\n }\n return null;\n }\n /**\n * Required with getSnapshotBeforeUpdate to stop React complaining.\n */\n componentDidUpdate() { }\n render() {\n return this.props.children;\n }\n}\nfunction PopChild({ children, isPresent }) {\n const id = useId();\n const ref = useRef(null);\n const size = useRef({\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n });\n /**\n * We create and inject a style block so we can apply this explicit\n * sizing in a non-destructive manner by just deleting the style block.\n *\n * We can't apply size via render as the measurement happens\n * in getSnapshotBeforeUpdate (post-render), likewise if we apply the\n * styles directly on the DOM node, we might be overwriting\n * styles set via the style prop.\n */\n useInsertionEffect(() => {\n const { width, height, top, left } = size.current;\n if (isPresent || !ref.current || !width || !height)\n return;\n ref.current.dataset.motionPopId = id;\n const style = document.createElement(\"style\");\n document.head.appendChild(style);\n if (style.sheet) {\n style.sheet.insertRule(`\n [data-motion-pop-id=\"${id}\"] {\n position: absolute !important;\n width: ${width}px !important;\n height: ${height}px !important;\n top: ${top}px !important;\n left: ${left}px !important;\n }\n `);\n }\n return () => {\n document.head.removeChild(style);\n };\n }, [isPresent]);\n return (React.createElement(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size }, React.cloneElement(children, { ref })));\n}\n\nexport { PopChild };\n","import * as React from 'react';\nimport { useId, useMemo } from 'react';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\nimport { useConstant } from '../../utils/use-constant.mjs';\nimport { PopChild } from './PopChild.mjs';\n\nconst PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, }) => {\n const presenceChildren = useConstant(newChildrenMap);\n const id = useId();\n const context = useMemo(() => ({\n id,\n initial,\n isPresent,\n custom,\n onExitComplete: (childId) => {\n presenceChildren.set(childId, true);\n for (const isComplete of presenceChildren.values()) {\n if (!isComplete)\n return; // can stop searching when any is incomplete\n }\n onExitComplete && onExitComplete();\n },\n register: (childId) => {\n presenceChildren.set(childId, false);\n return () => presenceChildren.delete(childId);\n },\n }), \n /**\n * If the presence of a child affects the layout of the components around it,\n * we want to make a new context value to ensure they get re-rendered\n * so they can detect that layout change.\n */\n presenceAffectsLayout ? undefined : [isPresent]);\n useMemo(() => {\n presenceChildren.forEach((_, key) => presenceChildren.set(key, false));\n }, [isPresent]);\n /**\n * If there's no `motion` components to fire exit animations, we want to remove this\n * component immediately.\n */\n React.useEffect(() => {\n !isPresent &&\n !presenceChildren.size &&\n onExitComplete &&\n onExitComplete();\n }, [isPresent]);\n if (mode === \"popLayout\") {\n children = React.createElement(PopChild, { isPresent: isPresent }, children);\n }\n return (React.createElement(PresenceContext.Provider, { value: context }, children));\n};\nfunction newChildrenMap() {\n return new Map();\n}\n\nexport { PresenceChild };\n","import { useEffect } from 'react';\n\nfunction useUnmountEffect(callback) {\n return useEffect(() => () => callback(), []);\n}\n\nexport { useUnmountEffect };\n","import * as React from 'react';\nimport { useContext, useRef, cloneElement, Children, isValidElement } from 'react';\nimport { useForceUpdate } from '../../utils/use-force-update.mjs';\nimport { useIsMounted } from '../../utils/use-is-mounted.mjs';\nimport { PresenceChild } from './PresenceChild.mjs';\nimport { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs';\nimport { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';\nimport { useUnmountEffect } from '../../utils/use-unmount-effect.mjs';\nimport { invariant } from '../../utils/errors.mjs';\n\nconst getChildKey = (child) => child.key || \"\";\nfunction updateChildLookup(children, allChildren) {\n children.forEach((child) => {\n const key = getChildKey(child);\n allChildren.set(key, child);\n });\n}\nfunction onlyElements(children) {\n const filtered = [];\n // We use forEach here instead of map as map mutates the component key by preprending `.$`\n Children.forEach(children, (child) => {\n if (isValidElement(child))\n filtered.push(child);\n });\n return filtered;\n}\n/**\n * `AnimatePresence` enables the animation of components that have been removed from the tree.\n *\n * When adding/removing more than a single child, every child **must** be given a unique `key` prop.\n *\n * Any `motion` components that have an `exit` property defined will animate out when removed from\n * the tree.\n *\n * ```jsx\n * import { motion, AnimatePresence } from 'framer-motion'\n *\n * export const Items = ({ items }) => (\n * \n * {items.map(item => (\n * \n * ))}\n * \n * )\n * ```\n *\n * You can sequence exit animations throughout a tree using variants.\n *\n * If a child contains multiple `motion` components with `exit` props, it will only unmount the child\n * once all `motion` components have finished animating out. Likewise, any components using\n * `usePresence` all need to call `safeToRemove`.\n *\n * @public\n */\nconst AnimatePresence = ({ children, custom, initial = true, onExitComplete, exitBeforeEnter, presenceAffectsLayout = true, mode = \"sync\", }) => {\n invariant(!exitBeforeEnter, \"Replace exitBeforeEnter with mode='wait'\");\n // We want to force a re-render once all exiting animations have finished. We\n // either use a local forceRender function, or one from a parent context if it exists.\n const forceRender = useContext(LayoutGroupContext).forceRender || useForceUpdate()[0];\n const isMounted = useIsMounted();\n // Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key\n const filteredChildren = onlyElements(children);\n let childrenToRender = filteredChildren;\n const exitingChildren = useRef(new Map()).current;\n // Keep a living record of the children we're actually rendering so we\n // can diff to figure out which are entering and exiting\n const presentChildren = useRef(childrenToRender);\n // A lookup table to quickly reference components by key\n const allChildren = useRef(new Map()).current;\n // If this is the initial component render, just deal with logic surrounding whether\n // we play onMount animations or not.\n const isInitialRender = useRef(true);\n useIsomorphicLayoutEffect(() => {\n isInitialRender.current = false;\n updateChildLookup(filteredChildren, allChildren);\n presentChildren.current = childrenToRender;\n });\n useUnmountEffect(() => {\n isInitialRender.current = true;\n allChildren.clear();\n exitingChildren.clear();\n });\n if (isInitialRender.current) {\n return (React.createElement(React.Fragment, null, childrenToRender.map((child) => (React.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, initial: initial ? undefined : false, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child)))));\n }\n // If this is a subsequent render, deal with entering and exiting children\n childrenToRender = [...childrenToRender];\n // Diff the keys of the currently-present and target children to update our\n // exiting list.\n const presentKeys = presentChildren.current.map(getChildKey);\n const targetKeys = filteredChildren.map(getChildKey);\n // Diff the present children with our target children and mark those that are exiting\n const numPresent = presentKeys.length;\n for (let i = 0; i < numPresent; i++) {\n const key = presentKeys[i];\n if (targetKeys.indexOf(key) === -1 && !exitingChildren.has(key)) {\n exitingChildren.set(key, undefined);\n }\n }\n // If we currently have exiting children, and we're deferring rendering incoming children\n // until after all current children have exiting, empty the childrenToRender array\n if (mode === \"wait\" && exitingChildren.size) {\n childrenToRender = [];\n }\n // Loop through all currently exiting components and clone them to overwrite `animate`\n // with any `exit` prop they might have defined.\n exitingChildren.forEach((component, key) => {\n // If this component is actually entering again, early return\n if (targetKeys.indexOf(key) !== -1)\n return;\n const child = allChildren.get(key);\n if (!child)\n return;\n const insertionIndex = presentKeys.indexOf(key);\n let exitingComponent = component;\n if (!exitingComponent) {\n const onExit = () => {\n // clean up the exiting children map\n exitingChildren.delete(key);\n // compute the keys of children that were rendered once but are no longer present\n // this could happen in case of too many fast consequent renderings\n // @link https://github.com/framer/motion/issues/2023\n const leftOverKeys = Array.from(allChildren.keys()).filter((childKey) => !targetKeys.includes(childKey));\n // clean up the all children map\n leftOverKeys.forEach((leftOverKey) => allChildren.delete(leftOverKey));\n // make sure to render only the children that are actually visible\n presentChildren.current = filteredChildren.filter((presentChild) => {\n const presentChildKey = getChildKey(presentChild);\n return (\n // filter out the node exiting\n presentChildKey === key ||\n // filter out the leftover children\n leftOverKeys.includes(presentChildKey));\n });\n // Defer re-rendering until all exiting children have indeed left\n if (!exitingChildren.size) {\n if (isMounted.current === false)\n return;\n forceRender();\n onExitComplete && onExitComplete();\n }\n };\n exitingComponent = (React.createElement(PresenceChild, { key: getChildKey(child), isPresent: false, onExitComplete: onExit, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child));\n exitingChildren.set(key, exitingComponent);\n }\n childrenToRender.splice(insertionIndex, 0, exitingComponent);\n });\n // Add `MotionContext` even to children that don't need it to ensure we're rendering\n // the same tree between renders\n childrenToRender = childrenToRender.map((child) => {\n const key = child.key;\n return exitingChildren.has(key) ? (child) : (React.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child));\n });\n if (process.env.NODE_ENV !== \"production\" &&\n mode === \"wait\" &&\n childrenToRender.length > 1) {\n console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to \"wait\". This will lead to odd visual behaviour.`);\n }\n return (React.createElement(React.Fragment, null, exitingChildren.size\n ? childrenToRender\n : childrenToRender.map((child) => cloneElement(child))));\n};\n\nexport { AnimatePresence };\n","import { createContext } from 'react';\n\n/**\n * Note: Still used by components generated by old versions of Framer\n *\n * @deprecated\n */\nconst DeprecatedLayoutGroupContext = createContext(null);\n\nexport { DeprecatedLayoutGroupContext };\n","const notify = (node) => !node.isLayoutDirty && node.willUpdate(false);\nfunction nodeGroup() {\n const nodes = new Set();\n const subscriptions = new WeakMap();\n const dirtyAll = () => nodes.forEach(notify);\n return {\n add: (node) => {\n nodes.add(node);\n subscriptions.set(node, node.addEventListener(\"willUpdate\", dirtyAll));\n },\n remove: (node) => {\n nodes.delete(node);\n const unsubscribe = subscriptions.get(node);\n if (unsubscribe) {\n unsubscribe();\n subscriptions.delete(node);\n }\n dirtyAll();\n },\n dirty: dirtyAll,\n };\n}\n\nexport { nodeGroup };\n","import * as React from 'react';\nimport { useContext, useRef, useMemo } from 'react';\nimport { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs';\nimport { DeprecatedLayoutGroupContext } from '../../context/DeprecatedLayoutGroupContext.mjs';\nimport { useForceUpdate } from '../../utils/use-force-update.mjs';\nimport { nodeGroup } from '../../projection/node/group.mjs';\n\nconst shouldInheritGroup = (inherit) => inherit === true;\nconst shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === \"id\";\nconst LayoutGroup = ({ children, id, inherit = true }) => {\n const layoutGroupContext = useContext(LayoutGroupContext);\n const deprecatedLayoutGroupContext = useContext(DeprecatedLayoutGroupContext);\n const [forceRender, key] = useForceUpdate();\n const context = useRef(null);\n const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext;\n if (context.current === null) {\n if (shouldInheritId(inherit) && upstreamId) {\n id = id ? upstreamId + \"-\" + id : upstreamId;\n }\n context.current = {\n id,\n group: shouldInheritGroup(inherit)\n ? layoutGroupContext.group || nodeGroup()\n : nodeGroup(),\n };\n }\n const memoizedContext = useMemo(() => ({ ...context.current, forceRender }), [key]);\n return (React.createElement(LayoutGroupContext.Provider, { value: memoizedContext }, children));\n};\n\nexport { LayoutGroup };\n","import { useContext, useState, useEffect } from 'react';\nimport { motionValue } from './index.mjs';\nimport { MotionConfigContext } from '../context/MotionConfigContext.mjs';\nimport { useConstant } from '../utils/use-constant.mjs';\n\n/**\n * Creates a `MotionValue` to track the state and velocity of a value.\n *\n * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop.\n *\n * ```jsx\n * export const MyComponent = () => {\n * const scale = useMotionValue(1)\n *\n * return \n * }\n * ```\n *\n * @param initial - The initial state.\n *\n * @public\n */\nfunction useMotionValue(initial) {\n const value = useConstant(() => motionValue(initial));\n /**\n * If this motion value is being used in static mode, like on\n * the Framer canvas, force components to rerender when the motion\n * value is updated.\n */\n const { isStatic } = useContext(MotionConfigContext);\n if (isStatic) {\n const [, setLatest] = useState(initial);\n useEffect(() => value.on(\"change\", setLatest), []);\n }\n return value;\n}\n\nexport { useMotionValue };\n","import { interpolate } from './interpolate.mjs';\n\nconst isCustomValueType = (v) => {\n return v && typeof v === \"object\" && v.mix;\n};\nconst getMixer = (v) => (isCustomValueType(v) ? v.mix : undefined);\nfunction transform(...args) {\n const useImmediate = !Array.isArray(args[0]);\n const argOffset = useImmediate ? 0 : -1;\n const inputValue = args[0 + argOffset];\n const inputRange = args[1 + argOffset];\n const outputRange = args[2 + argOffset];\n const options = args[3 + argOffset];\n const interpolator = interpolate(inputRange, outputRange, {\n mixer: getMixer(outputRange[0]),\n ...options,\n });\n return useImmediate ? interpolator(inputValue) : interpolator;\n}\n\nexport { transform };\n","import { useMotionValue } from './use-motion-value.mjs';\nimport { useIsomorphicLayoutEffect } from '../utils/use-isomorphic-effect.mjs';\nimport { cancelFrame, frame } from '../frameloop/frame.mjs';\n\nfunction useCombineMotionValues(values, combineValues) {\n /**\n * Initialise the returned motion value. This remains the same between renders.\n */\n const value = useMotionValue(combineValues());\n /**\n * Create a function that will update the template motion value with the latest values.\n * This is pre-bound so whenever a motion value updates it can schedule its\n * execution in Framesync. If it's already been scheduled it won't be fired twice\n * in a single frame.\n */\n const updateValue = () => value.set(combineValues());\n /**\n * Synchronously update the motion value with the latest values during the render.\n * This ensures that within a React render, the styles applied to the DOM are up-to-date.\n */\n updateValue();\n /**\n * Subscribe to all motion values found within the template. Whenever any of them change,\n * schedule an update.\n */\n useIsomorphicLayoutEffect(() => {\n const scheduleUpdate = () => frame.update(updateValue, false, true);\n const subscriptions = values.map((v) => v.on(\"change\", scheduleUpdate));\n return () => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n cancelFrame(updateValue);\n };\n });\n return value;\n}\n\nexport { useCombineMotionValues };\n","import { collectMotionValues } from './index.mjs';\nimport { useCombineMotionValues } from './use-combine-values.mjs';\n\nfunction useComputed(compute) {\n /**\n * Open session of collectMotionValues. Any MotionValue that calls get()\n * will be saved into this array.\n */\n collectMotionValues.current = [];\n compute();\n const value = useCombineMotionValues(collectMotionValues.current, compute);\n /**\n * Synchronously close session of collectMotionValues.\n */\n collectMotionValues.current = undefined;\n return value;\n}\n\nexport { useComputed };\n","import { transform } from '../utils/transform.mjs';\nimport { useCombineMotionValues } from './use-combine-values.mjs';\nimport { useConstant } from '../utils/use-constant.mjs';\nimport { useComputed } from './use-computed.mjs';\n\nfunction useTransform(input, inputRangeOrTransformer, outputRange, options) {\n if (typeof input === \"function\") {\n return useComputed(input);\n }\n const transformer = typeof inputRangeOrTransformer === \"function\"\n ? inputRangeOrTransformer\n : transform(inputRangeOrTransformer, outputRange, options);\n return Array.isArray(input)\n ? useListTransform(input, transformer)\n : useListTransform([input], ([latest]) => transformer(latest));\n}\nfunction useListTransform(values, transformer) {\n const latest = useConstant(() => []);\n return useCombineMotionValues(values, () => {\n latest.length = 0;\n const numValues = values.length;\n for (let i = 0; i < numValues; i++) {\n latest[i] = values[i].get();\n }\n return transformer(latest);\n });\n}\n\nexport { useTransform };\n","import { invariant } from '../../../utils/errors.mjs';\n\nfunction resolveElements(elements, scope, selectorCache) {\n var _a;\n if (typeof elements === \"string\") {\n let root = document;\n if (scope) {\n invariant(Boolean(scope.current), \"Scope provided, but no element detected.\");\n root = scope.current;\n }\n if (selectorCache) {\n (_a = selectorCache[elements]) !== null && _a !== void 0 ? _a : (selectorCache[elements] = root.querySelectorAll(elements));\n elements = selectorCache[elements];\n }\n else {\n elements = root.querySelectorAll(elements);\n }\n }\n else if (elements instanceof Element) {\n elements = [elements];\n }\n /**\n * Return an empty array\n */\n return Array.from(elements || []);\n}\n\nexport { resolveElements };\n","import { frame, cancelFrame } from '../../../frameloop/frame.mjs';\n\nfunction observeTimeline(update, timeline) {\n let prevProgress;\n const onFrame = () => {\n const { currentTime } = timeline;\n const percentage = currentTime === null ? 0 : currentTime.value;\n const progress = percentage / 100;\n if (prevProgress !== progress) {\n update(progress);\n }\n prevProgress = progress;\n };\n frame.update(onFrame, true);\n return () => cancelFrame(onFrame);\n}\n\nexport { observeTimeline };\n","import { memo } from '../../../utils/memo.mjs';\n\nconst supportsScrollTimeline = memo(() => window.ScrollTimeline !== undefined);\n\nexport { supportsScrollTimeline };\n","import { observeTimeline } from '../render/dom/scroll/observe.mjs';\nimport { supportsScrollTimeline } from '../render/dom/scroll/supports.mjs';\n\nclass GroupPlaybackControls {\n constructor(animations) {\n this.animations = animations.filter(Boolean);\n }\n then(onResolve, onReject) {\n return Promise.all(this.animations).then(onResolve).catch(onReject);\n }\n /**\n * TODO: Filter out cancelled or stopped animations before returning\n */\n getAll(propName) {\n return this.animations[0][propName];\n }\n setAll(propName, newValue) {\n for (let i = 0; i < this.animations.length; i++) {\n this.animations[i][propName] = newValue;\n }\n }\n attachTimeline(timeline) {\n const cancelAll = this.animations.map((animation) => {\n if (supportsScrollTimeline() && animation.attachTimeline) {\n animation.attachTimeline(timeline);\n }\n else {\n animation.pause();\n return observeTimeline((progress) => {\n animation.time = animation.duration * progress;\n }, timeline);\n }\n });\n return () => {\n cancelAll.forEach((cancelTimeline, i) => {\n if (cancelTimeline)\n cancelTimeline();\n this.animations[i].stop();\n });\n };\n }\n get time() {\n return this.getAll(\"time\");\n }\n set time(time) {\n this.setAll(\"time\", time);\n }\n get speed() {\n return this.getAll(\"speed\");\n }\n set speed(speed) {\n this.setAll(\"speed\", speed);\n }\n get duration() {\n let max = 0;\n for (let i = 0; i < this.animations.length; i++) {\n max = Math.max(max, this.animations[i].duration);\n }\n return max;\n }\n runAll(methodName) {\n this.animations.forEach((controls) => controls[methodName]());\n }\n play() {\n this.runAll(\"play\");\n }\n pause() {\n this.runAll(\"pause\");\n }\n stop() {\n this.runAll(\"stop\");\n }\n cancel() {\n this.runAll(\"cancel\");\n }\n complete() {\n this.runAll(\"complete\");\n }\n}\n\nexport { GroupPlaybackControls };\n","function isDOMKeyframes(keyframes) {\n return typeof keyframes === \"object\" && !Array.isArray(keyframes);\n}\n\nexport { isDOMKeyframes };\n","import { isSVGElement } from '../../render/dom/utils/is-svg-element.mjs';\nimport { SVGVisualElement } from '../../render/svg/SVGVisualElement.mjs';\nimport { HTMLVisualElement } from '../../render/html/HTMLVisualElement.mjs';\nimport { visualElementStore } from '../../render/store.mjs';\n\nfunction createVisualElement(element) {\n const options = {\n presenceContext: null,\n props: {},\n visualState: {\n renderState: {\n transform: {},\n transformOrigin: {},\n style: {},\n vars: {},\n attrs: {},\n },\n latestValues: {},\n },\n };\n const node = isSVGElement(element)\n ? new SVGVisualElement(options, {\n enableHardwareAcceleration: false,\n })\n : new HTMLVisualElement(options, {\n enableHardwareAcceleration: true,\n });\n node.mount(element);\n visualElementStore.set(element, node);\n}\n\nexport { createVisualElement };\n","import { spring } from '../../animation/generators/spring/index.mjs';\nimport { calcGeneratorDuration, maxGeneratorDuration } from '../../animation/generators/utils/calc-duration.mjs';\nimport { millisecondsToSeconds } from '../../utils/time-conversion.mjs';\n\n/**\n * Create a progress => progress easing function from a generator.\n */\nfunction createGeneratorEasing(options, scale = 100) {\n const generator = spring({ keyframes: [0, scale], ...options });\n const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);\n return {\n type: \"keyframes\",\n ease: (progress) => generator.next(duration * progress).value / scale,\n duration: millisecondsToSeconds(duration),\n };\n}\n\nexport { createGeneratorEasing };\n","/**\n * Given a absolute or relative time definition and current/prev time state of the sequence,\n * calculate an absolute time for the next keyframes.\n */\nfunction calcNextTime(current, next, prev, labels) {\n var _a;\n if (typeof next === \"number\") {\n return next;\n }\n else if (next.startsWith(\"-\") || next.startsWith(\"+\")) {\n return Math.max(0, current + parseFloat(next));\n }\n else if (next === \"<\") {\n return prev;\n }\n else {\n return (_a = labels.get(next)) !== null && _a !== void 0 ? _a : current;\n }\n}\n\nexport { calcNextTime };\n","const wrap = (min, max, v) => {\n const rangeSize = max - min;\n return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;\n};\n\nexport { wrap };\n","import { wrap } from '../../utils/wrap.mjs';\nimport { isEasingArray } from './is-easing-array.mjs';\n\nfunction getEasingForSegment(easing, i) {\n return isEasingArray(easing) ? easing[wrap(0, easing.length, i)] : easing;\n}\n\nexport { getEasingForSegment };\n","import { getEasingForSegment } from '../../../easing/utils/get-easing-for-segment.mjs';\nimport { removeItem } from '../../../utils/array.mjs';\nimport { mix } from '../../../utils/mix.mjs';\n\nfunction eraseKeyframes(sequence, startTime, endTime) {\n for (let i = 0; i < sequence.length; i++) {\n const keyframe = sequence[i];\n if (keyframe.at > startTime && keyframe.at < endTime) {\n removeItem(sequence, keyframe);\n // If we remove this item we have to push the pointer back one\n i--;\n }\n }\n}\nfunction addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) {\n /**\n * Erase every existing value between currentTime and targetTime,\n * this will essentially splice this timeline into any currently\n * defined ones.\n */\n eraseKeyframes(sequence, startTime, endTime);\n for (let i = 0; i < keyframes.length; i++) {\n sequence.push({\n value: keyframes[i],\n at: mix(startTime, endTime, offset[i]),\n easing: getEasingForSegment(easing, i),\n });\n }\n}\n\nexport { addKeyframes, eraseKeyframes };\n","function compareByTime(a, b) {\n if (a.at === b.at) {\n if (a.value === null)\n return 1;\n if (b.value === null)\n return -1;\n return 0;\n }\n else {\n return a.at - b.at;\n }\n}\n\nexport { compareByTime };\n","import { createGeneratorEasing } from '../../easing/utils/create-generator-easing.mjs';\nimport { resolveElements } from '../../render/dom/utils/resolve-element.mjs';\nimport { defaultOffset } from '../../utils/offsets/default.mjs';\nimport { fillOffset } from '../../utils/offsets/fill.mjs';\nimport { progress } from '../../utils/progress.mjs';\nimport { secondsToMilliseconds } from '../../utils/time-conversion.mjs';\nimport { isMotionValue } from '../../value/utils/is-motion-value.mjs';\nimport { calcNextTime } from './utils/calc-time.mjs';\nimport { addKeyframes } from './utils/edit.mjs';\nimport { compareByTime } from './utils/sort.mjs';\n\nconst defaultSegmentEasing = \"easeInOut\";\nfunction createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope) {\n const defaultDuration = defaultTransition.duration || 0.3;\n const animationDefinitions = new Map();\n const sequences = new Map();\n const elementCache = {};\n const timeLabels = new Map();\n let prevTime = 0;\n let currentTime = 0;\n let totalDuration = 0;\n /**\n * Build the timeline by mapping over the sequence array and converting\n * the definitions into keyframes and offsets with absolute time values.\n * These will later get converted into relative offsets in a second pass.\n */\n for (let i = 0; i < sequence.length; i++) {\n const segment = sequence[i];\n /**\n * If this is a timeline label, mark it and skip the rest of this iteration.\n */\n if (typeof segment === \"string\") {\n timeLabels.set(segment, currentTime);\n continue;\n }\n else if (!Array.isArray(segment)) {\n timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels));\n continue;\n }\n let [subject, keyframes, transition = {}] = segment;\n /**\n * If a relative or absolute time value has been specified we need to resolve\n * it in relation to the currentTime.\n */\n if (transition.at !== undefined) {\n currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels);\n }\n /**\n * Keep track of the maximum duration in this definition. This will be\n * applied to currentTime once the definition has been parsed.\n */\n let maxDuration = 0;\n const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numElements = 0) => {\n const valueKeyframesAsList = keyframesAsList(valueKeyframes);\n const { delay = 0, times = defaultOffset(valueKeyframesAsList), type = \"keyframes\", ...remainingTransition } = valueTransition;\n let { ease = defaultTransition.ease || \"easeOut\", duration } = valueTransition;\n /**\n * Resolve stagger() if defined.\n */\n const calculatedDelay = typeof delay === \"function\"\n ? delay(elementIndex, numElements)\n : delay;\n /**\n * If this animation should and can use a spring, generate a spring easing function.\n */\n const numKeyframes = valueKeyframesAsList.length;\n if (numKeyframes <= 2 && type === \"spring\") {\n /**\n * As we're creating an easing function from a spring,\n * ideally we want to generate it using the real distance\n * between the two keyframes. However this isn't always\n * possible - in these situations we use 0-100.\n */\n let absoluteDelta = 100;\n if (numKeyframes === 2 &&\n isNumberKeyframesArray(valueKeyframesAsList)) {\n const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0];\n absoluteDelta = Math.abs(delta);\n }\n const springTransition = { ...remainingTransition };\n if (duration !== undefined) {\n springTransition.duration = secondsToMilliseconds(duration);\n }\n const springEasing = createGeneratorEasing(springTransition, absoluteDelta);\n ease = springEasing.ease;\n duration = springEasing.duration;\n }\n duration !== null && duration !== void 0 ? duration : (duration = defaultDuration);\n const startTime = currentTime + calculatedDelay;\n const targetTime = startTime + duration;\n /**\n * If there's only one time offset of 0, fill in a second with length 1\n */\n if (times.length === 1 && times[0] === 0) {\n times[1] = 1;\n }\n /**\n * Fill out if offset if fewer offsets than keyframes\n */\n const remainder = times.length - valueKeyframesAsList.length;\n remainder > 0 && fillOffset(times, remainder);\n /**\n * If only one value has been set, ie [1], push a null to the start of\n * the keyframe array. This will let us mark a keyframe at this point\n * that will later be hydrated with the previous value.\n */\n valueKeyframesAsList.length === 1 &&\n valueKeyframesAsList.unshift(null);\n /**\n * Add keyframes, mapping offsets to absolute time.\n */\n addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime);\n maxDuration = Math.max(calculatedDelay + duration, maxDuration);\n totalDuration = Math.max(targetTime, totalDuration);\n };\n if (isMotionValue(subject)) {\n const subjectSequence = getSubjectSequence(subject, sequences);\n resolveValueSequence(keyframes, transition, getValueSequence(\"default\", subjectSequence));\n }\n else {\n /**\n * Find all the elements specified in the definition and parse value\n * keyframes from their timeline definitions.\n */\n const elements = resolveElements(subject, scope, elementCache);\n const numElements = elements.length;\n /**\n * For every element in this segment, process the defined values.\n */\n for (let elementIndex = 0; elementIndex < numElements; elementIndex++) {\n /**\n * Cast necessary, but we know these are of this type\n */\n keyframes = keyframes;\n transition = transition;\n const element = elements[elementIndex];\n const subjectSequence = getSubjectSequence(element, sequences);\n for (const key in keyframes) {\n resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), elementIndex, numElements);\n }\n }\n }\n prevTime = currentTime;\n currentTime += maxDuration;\n }\n /**\n * For every element and value combination create a new animation.\n */\n sequences.forEach((valueSequences, element) => {\n for (const key in valueSequences) {\n const valueSequence = valueSequences[key];\n /**\n * Arrange all the keyframes in ascending time order.\n */\n valueSequence.sort(compareByTime);\n const keyframes = [];\n const valueOffset = [];\n const valueEasing = [];\n /**\n * For each keyframe, translate absolute times into\n * relative offsets based on the total duration of the timeline.\n */\n for (let i = 0; i < valueSequence.length; i++) {\n const { at, value, easing } = valueSequence[i];\n keyframes.push(value);\n valueOffset.push(progress(0, totalDuration, at));\n valueEasing.push(easing || \"easeOut\");\n }\n /**\n * If the first keyframe doesn't land on offset: 0\n * provide one by duplicating the initial keyframe. This ensures\n * it snaps to the first keyframe when the animation starts.\n */\n if (valueOffset[0] !== 0) {\n valueOffset.unshift(0);\n keyframes.unshift(keyframes[0]);\n valueEasing.unshift(defaultSegmentEasing);\n }\n /**\n * If the last keyframe doesn't land on offset: 1\n * provide one with a null wildcard value. This will ensure it\n * stays static until the end of the animation.\n */\n if (valueOffset[valueOffset.length - 1] !== 1) {\n valueOffset.push(1);\n keyframes.push(null);\n }\n if (!animationDefinitions.has(element)) {\n animationDefinitions.set(element, {\n keyframes: {},\n transition: {},\n });\n }\n const definition = animationDefinitions.get(element);\n definition.keyframes[key] = keyframes;\n definition.transition[key] = {\n ...defaultTransition,\n duration: totalDuration,\n ease: valueEasing,\n times: valueOffset,\n ...sequenceTransition,\n };\n }\n });\n return animationDefinitions;\n}\nfunction getSubjectSequence(subject, sequences) {\n !sequences.has(subject) && sequences.set(subject, {});\n return sequences.get(subject);\n}\nfunction getValueSequence(name, sequences) {\n if (!sequences[name])\n sequences[name] = [];\n return sequences[name];\n}\nfunction keyframesAsList(keyframes) {\n return Array.isArray(keyframes) ? keyframes : [keyframes];\n}\nfunction getValueTransition(transition, key) {\n return transition[key]\n ? { ...transition, ...transition[key] }\n : { ...transition };\n}\nconst isNumber = (keyframe) => typeof keyframe === \"number\";\nconst isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber);\n\nexport { createAnimationsFromSequence, getValueTransition };\n","import { resolveElements } from '../render/dom/utils/resolve-element.mjs';\nimport { visualElementStore } from '../render/store.mjs';\nimport { invariant } from '../utils/errors.mjs';\nimport { GroupPlaybackControls } from './GroupPlaybackControls.mjs';\nimport { isDOMKeyframes } from './utils/is-dom-keyframes.mjs';\nimport { animateTarget } from './interfaces/visual-element-target.mjs';\nimport { createVisualElement } from './utils/create-visual-element.mjs';\nimport { animateSingleValue } from './interfaces/single-value.mjs';\nimport { createAnimationsFromSequence } from './sequence/create.mjs';\nimport { isMotionValue } from '../value/utils/is-motion-value.mjs';\n\nfunction animateElements(elementOrSelector, keyframes, options, scope) {\n const elements = resolveElements(elementOrSelector, scope);\n const numElements = elements.length;\n invariant(Boolean(numElements), \"No valid element provided.\");\n const animations = [];\n for (let i = 0; i < numElements; i++) {\n const element = elements[i];\n /**\n * Check each element for an associated VisualElement. If none exists,\n * we need to create one.\n */\n if (!visualElementStore.has(element)) {\n /**\n * TODO: We only need render-specific parts of the VisualElement.\n * With some additional work the size of the animate() function\n * could be reduced significantly.\n */\n createVisualElement(element);\n }\n const visualElement = visualElementStore.get(element);\n const transition = { ...options };\n /**\n * Resolve stagger function if provided.\n */\n if (typeof transition.delay === \"function\") {\n transition.delay = transition.delay(i, numElements);\n }\n animations.push(...animateTarget(visualElement, { ...keyframes, transition }, {}));\n }\n return new GroupPlaybackControls(animations);\n}\nconst isSequence = (value) => Array.isArray(value) && Array.isArray(value[0]);\nfunction animateSequence(sequence, options, scope) {\n const animations = [];\n const animationDefinitions = createAnimationsFromSequence(sequence, options, scope);\n animationDefinitions.forEach(({ keyframes, transition }, subject) => {\n let animation;\n if (isMotionValue(subject)) {\n animation = animateSingleValue(subject, keyframes.default, transition.default);\n }\n else {\n animation = animateElements(subject, keyframes, transition);\n }\n animations.push(animation);\n });\n return new GroupPlaybackControls(animations);\n}\nconst createScopedAnimate = (scope) => {\n /**\n * Implementation\n */\n function scopedAnimate(valueOrElementOrSequence, keyframes, options) {\n let animation;\n if (isSequence(valueOrElementOrSequence)) {\n animation = animateSequence(valueOrElementOrSequence, keyframes, scope);\n }\n else if (isDOMKeyframes(keyframes)) {\n animation = animateElements(valueOrElementOrSequence, keyframes, options, scope);\n }\n else {\n animation = animateSingleValue(valueOrElementOrSequence, keyframes, options);\n }\n if (scope) {\n scope.animations.push(animation);\n }\n return animation;\n }\n return scopedAnimate;\n};\nconst animate = createScopedAnimate();\n\nexport { animate, createScopedAnimate };\n","import { easingDefinitionToFunction } from '../../easing/utils/map.mjs';\n\nfunction getOriginIndex(from, total) {\n if (from === \"first\") {\n return 0;\n }\n else {\n const lastIndex = total - 1;\n return from === \"last\" ? lastIndex : lastIndex / 2;\n }\n}\nfunction stagger(duration = 0.1, { startDelay = 0, from = 0, ease } = {}) {\n return (i, total) => {\n const fromIndex = typeof from === \"number\" ? from : getOriginIndex(from, total);\n const distance = Math.abs(fromIndex - i);\n let delay = duration * distance;\n if (ease) {\n const maxDelay = total * duration;\n const easingFunction = easingDefinitionToFunction(ease);\n delay = easingFunction(delay / maxDelay) * maxDelay;\n }\n return startDelay + delay;\n };\n}\n\nexport { getOriginIndex, stagger };\n","/**\n * @remix-run/router v1.16.1\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n(function (Action) {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Action[\"Pop\"] = \"POP\";\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Action[\"Push\"] = \"PUSH\";\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\nconst PopStateEventType = \"popstate\";\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n let {\n initialEntries = [\"/\"],\n initialIndex,\n v5Compat = false\n } = options;\n let entries; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n let action = Action.Pop;\n let listener = null;\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation() {\n return entries[index];\n }\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n return location;\n }\n function createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n let history = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\"\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 1\n });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 0\n });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: nextLocation,\n delta\n });\n }\n },\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\n }\n };\n return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createBrowserLocation(window, globalHistory) {\n let {\n pathname,\n search,\n hash\n } = window.location;\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n function validateHashLocation(location, to) {\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n }\n return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location, index) {\n return {\n usr: location.state,\n key: location.key,\n idx: index\n };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = _extends({\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\"\n }, typeof to === \"string\" ? parsePath(to) : to, {\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: to && to.key || key || createKey()\n });\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nfunction createPath(_ref) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = _ref;\n if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nfunction parsePath(path) {\n let parsedPath = {};\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n if (path) {\n parsedPath.pathname = path;\n }\n }\n return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\n let {\n window = document.defaultView,\n v5Compat = false\n } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener = null;\n let index = getIndex();\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), \"\");\n }\n function getIndex() {\n let state = globalHistory.state || {\n idx: null\n };\n return state.idx;\n }\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: history.location,\n delta\n });\n }\n }\n function push(to, state) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 1\n });\n }\n }\n function replace(to, state) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 0\n });\n }\n }\n function createURL(to) {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base = window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n return new URL(href, base);\n }\n let history = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n }\n };\n return history;\n}\n//#endregion\n\nvar ResultType;\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\nfunction isIndexRoute(route) {\n return route.index === true;\n}\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nfunction convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n if (manifest === void 0) {\n manifest = {};\n }\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n invariant(!manifest[id], \"Found a route id collision on id \\\"\" + id + \"\\\". Route \" + \"id's must be globally unique within Data Router usages\");\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, mapRouteProperties(route), {\n id\n });\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {\n id,\n children: undefined\n });\n manifest[id] = pathOrLayoutRoute;\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);\n }\n return pathOrLayoutRoute;\n }\n });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n if (pathname == null) {\n return null;\n }\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch(branches[i], decoded);\n }\n return matches;\n}\nfunction convertRouteMatchToUiMatch(match, loaderData) {\n let {\n route,\n pathname,\n params\n } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle\n };\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n if (parentPath === void 0) {\n parentPath = \"\";\n }\n let flattenRoute = (route, index, relativePath) => {\n let meta = {\n relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route\n };\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(meta.relativePath.startsWith(parentPath), \"Absolute route path \\\"\" + meta.relativePath + \"\\\" nested under path \" + (\"\\\"\" + parentPath + \"\\\" is not valid. An absolute child route path \") + \"must start with the combined path of all its parent routes.\");\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n };\n routes.forEach((route, index) => {\n var _route$path;\n // coarse-grain check for optional params\n if (route.path === \"\" || !((_route$path = route.path) != null && _route$path.includes(\"?\"))) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n return branches;\n}\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path) {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n let [first, ...rest] = segments;\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n let result = [];\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\")));\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n // for absolute paths, ensure `/` instead of empty segment\n return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\nfunction rankRouteBranches(branches) {\n branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n if (index) {\n initialScore += indexRouteValue;\n }\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n return siblings ?\n // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1] :\n // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\nfunction matchRouteBranch(branch, pathname) {\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end\n }, remainingPathname);\n if (!match) return null;\n Object.assign(matchedParams, match.params);\n let route = meta.route;\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n route\n });\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nfunction generatePath(originalPath, params) {\n if (params === void 0) {\n params = {};\n }\n let path = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(false, \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n path = path.replace(/\\*$/, \"/*\");\n }\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n const stringify = p => p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n const segments = path.split(/\\/+/).map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\";\n // Apply the splat\n return stringify(params[star]);\n }\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key];\n invariant(optional === \"?\" || param != null, \"Missing \\\":\" + key + \"\\\" param\");\n return stringify(param);\n }\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter(segment => !!segment);\n return prefix + segments.join(\"/\");\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n let match = pathname.match(matcher);\n if (!match) return null;\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params = compiledParams.reduce((memo, _ref, index) => {\n let {\n paramName,\n isOptional\n } = _ref;\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n }\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n if (end === void 0) {\n end = true;\n }\n warning(path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"), \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n let params = [];\n let regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:([\\w-]+)(\\?)?/g, (_, paramName, isOptional) => {\n params.push({\n paramName,\n isOptional: isOptional != null\n });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n });\n if (path.endsWith(\"*\")) {\n params.push({\n paramName: \"*\"\n });\n regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else ;\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, params];\n}\nfunction decodePath(value) {\n try {\n return value.split(\"/\").map(v => decodeURIComponent(v).replace(/\\//g, \"%2F\")).join(\"/\");\n } catch (error) {\n warning(false, \"The URL path \\\"\" + value + \"\\\" could not be decoded because it is is a \" + \"malformed URL segment. This is probably due to a bad percent \" + (\"encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n return pathname.slice(startIndex) || \"/\";\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\"\n } = typeof to === \"string\" ? parsePath(to) : to;\n let pathname = toPathname ? toPathname.startsWith(\"/\") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash)\n };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n relativeSegments.forEach(segment => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n return \"Cannot include a '\" + char + \"' character in a manually specified \" + (\"`to.\" + field + \"` field [\" + JSON.stringify(path) + \"]. Please separate it out to the \") + (\"`to.\" + dest + \"` field. Alternatively you may provide the full path as \") + \"a string in and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nfunction getPathContributingMatches(matches) {\n return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nfunction getResolveToMatches(matches, v7_relativeSplatPath) {\n let pathMatches = getPathContributingMatches(matches);\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase);\n }\n return pathMatches.map(match => match.pathnameBase);\n}\n/**\n * @private\n */\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n let to;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = _extends({}, toArg);\n invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n }\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from;\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n to.pathname = toSegments.join(\"/\");\n }\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n let path = resolvePath(to, from);\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n return path;\n}\n/**\n * @private\n */\nfunction getToPathname(to) {\n // Empty strings should be treated the same as / paths\n return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\n/**\n * @private\n */\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n return new Response(JSON.stringify(data), _extends({}, responseInit, {\n headers\n }));\n};\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n constructor(data, responseInit) {\n this.pendingKeysSet = new Set();\n this.subscribers = new Set();\n this.deferredKeys = [];\n invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\");\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n this.init = responseInit;\n }\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\n onSettle(promise, key, error, data) {\n if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n return Promise.reject(error);\n }\n this.pendingKeysSet.delete(key);\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\"Deferred data for key \\\"\" + key + \"\\\" resolved/rejected with `undefined`, \" + \"you must resolve/reject with a value or `null`.\");\n Object.defineProperty(promise, \"_error\", {\n get: () => undefinedError\n });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n this.emit(false, key);\n return Promise.reject(error);\n }\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n this.emit(false, key);\n return data;\n }\n emit(aborted, settledKey) {\n this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n }\n subscribe(fn) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n async resolveData(signal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n get unwrappedData() {\n invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n return Object.entries(this.data).reduce((acc, _ref3) => {\n let [key, value] = _ref3;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\nconst defer = function defer(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n return new DeferredData(data, responseInit);\n};\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n return new Response(null, _extends({}, responseInit, {\n headers\n }));\n};\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirectDocument = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nclass ErrorResponseImpl {\n constructor(status, statusText, data, internal) {\n if (internal === void 0) {\n internal = false;\n }\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nfunction isRouteErrorResponse(error) {\n return error != null && typeof error.status === \"number\" && typeof error.statusText === \"string\" && typeof error.internal === \"boolean\" && \"data\" in error;\n}\n\nconst validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nconst validMutationMethods = new Set(validMutationMethodsArr);\nconst validRequestMethodsArr = [\"get\", ...validMutationMethodsArr];\nconst validRequestMethods = new Set(validRequestMethodsArr);\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\nconst IDLE_NAVIGATION = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_BLOCKER = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined\n};\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst defaultMapRouteProperties = route => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary)\n});\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Create a router and listen to history POP navigations\n */\nfunction createRouter(init) {\n const routerWindow = init.window ? init.window : typeof window !== \"undefined\" ? window : undefined;\n const isBrowser = typeof routerWindow !== \"undefined\" && typeof routerWindow.document !== \"undefined\" && typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let mapRouteProperties;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Routes keyed by ID\n let manifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);\n let inFlightDataRoutes;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;\n // Config driven behavior flags\n let future = _extends({\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n unstable_skipActionErrorRevalidation: false\n }, init.future);\n // Cleanup function for history\n let unlistenHistory = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors = null;\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname\n });\n let {\n matches,\n route\n } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = {\n [route.id]: error\n };\n }\n let initialized;\n let hasLazyRoutes = initialMatches.some(m => m.route.lazy);\n let hasLoaders = initialMatches.some(m => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n let isRouteInitialized = m => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (typeof m.route.loader === \"function\" && m.route.loader.hydrate === true) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined;\n };\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);\n initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n let router;\n let state = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n actionData: init.hydrationData && init.hydrationData.actionData || null,\n errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n fetchers: new Map(),\n blockers: new Map()\n };\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction = Action.Pop;\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController;\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions = new Map();\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener = null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes = [];\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads = [];\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(_ref => {\n let {\n action: historyAction,\n location,\n delta\n } = _ref;\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n warning(blockerFunctions.size === 0 || delta != null, \"You are trying to use a blocker on a POP navigation to a location \" + \"that was not created by @remix-run/router. This will fail silently in \" + \"production. This can happen if you are navigating outside the router \" + \"via `window.history.pushState`/`window.location.hash` instead of using \" + \"router navigation APIs. This can also happen if you are using \" + \"createHashRouter and the user manually changes the URL.\");\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction\n });\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return startNavigation(historyAction, location);\n });\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () => routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location, {\n initialHydration: true\n });\n }\n return router;\n }\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n // Subscribe to state updates for the router\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n // Update our state and notify the calling context of the change\n function updateState(newState, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state = _extends({}, state, newState);\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers = [];\n let deletedFetchersKeys = [];\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach(subscriber => subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true\n }));\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach(key => state.fetchers.delete(key));\n deletedFetchersKeys.forEach(key => deleteFetcher(key));\n }\n }\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(location, newState, _temp) {\n var _location$state, _location$state2;\n let {\n flushSync\n } = _temp === void 0 ? {} : _temp;\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === \"loading\" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;\n let actionData;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === Action.Replace) {\n init.history.replace(location, location.state);\n }\n let viewTransitionOpts;\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === Action.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n }\n updateState(_extends({}, newState, {\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset,\n blockers\n }), {\n viewTransitionOpts,\n flushSync: flushSync === true\n });\n // Reset stateful navigation vars\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n let historyAction = Action.Push;\n if (userReplace === true) {\n historyAction = Action.Replace;\n } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = Action.Replace;\n }\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n let flushSync = (opts && opts.unstable_flushSync) === true;\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction\n });\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync\n });\n }\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\n });\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\n }\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation\n });\n }\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(historyAction, location, opts) {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, {\n pathname: location.pathname\n });\n let {\n matches: notFoundMatches,\n route\n } = getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n }, {\n flushSync\n });\n return;\n }\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a