pxt-core 7.3.21 → 7.3.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/built/pxt.js +73 -39
- package/built/pxtblockly.js +1448 -1359
- package/built/pxtblocks.d.ts +4 -4
- package/built/pxtblocks.js +80 -35
- package/built/pxtlib.d.ts +6 -2
- package/built/pxtlib.js +73 -39
- package/built/target.js +1 -1
- package/built/web/blockly.css +1 -1
- package/built/web/main.js +1 -1
- package/built/web/pxtapp.js +1 -1
- package/built/web/pxtasseteditor.js +1 -1
- package/built/web/pxtblockly.js +1 -1
- package/built/web/pxtblocks.js +1 -1
- package/built/web/pxtembed.js +1 -1
- package/built/web/pxtlib.js +1 -1
- package/built/web/pxtworker.js +1 -1
- package/built/web/rtlblockly.css +1 -1
- package/built/web/rtlsemantic.css +1 -1
- package/built/web/semantic.css +1 -1
- package/built/web/skillmap/js/main.7ad07e3a.chunk.js +1 -0
- package/localtypings/blockly.d.ts +6555 -11288
- package/package.json +2 -2
- package/theme/blockly-core.less +13 -22
- package/theme/melodyeditor.less +2 -2
- package/theme/print.less +1 -1
- package/theme/toolbox.less +0 -1
- package/webapp/public/blockly/blockly_compressed.js +1286 -1269
- package/webapp/public/blockly/blocks_compressed.js +65 -47
- package/webapp/public/blockly/msg/js/en.js +17 -8
- package/webapp/public/blockly/msg/json/en.json +15 -6
- package/webapp/public/skillmap.html +1 -1
- package/built/web/skillmap/js/main.bdd63c80.chunk.js +0 -1
package/built/web/pxtapp.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=function(){"use strict";function t(e,t){postMessage({action:$e,cbn:t,result:e})}function n(e){var t=[];return t[e-1]=void 0,t}function i(e,t){return o(e[0]+t[0],e[1]+t[1])}function r(e,t){return function(e,t){var n;return n=t,0>t&&(n+=He),[n,e*He]}(~~Math.max(Math.min(e[1]/He,2147483647),-2147483648)&~~Math.max(Math.min(t[1]/He,2147483647),-2147483648),c(e)&c(t))}function s(e,t){var n,i;return e[0]==t[0]&&e[1]==t[1]?0:(n=0>e[1],i=0>t[1],n&&!i?-1:!n&&i?1:p(e,t)[1]<0?-1:1)}function o(e,t){var n,i;for(e%=0x10000000000000000,t=(t%=0x10000000000000000)-(n=t%He)+(i=Math.floor(e/He)*He),e=e-i+n;0>e;)e+=He,t-=He;for(;e>4294967295;)e-=He,t+=He;for(t%=0x10000000000000000;t>0x7fffffff00000000;)t-=0x10000000000000000;for(;-0x8000000000000000>t;)t+=0x10000000000000000;return[e,t]}function a(e,t){return e[0]==t[0]&&e[1]==t[1]}function l(e){return e>=0?[e,0]:[e+He,-He]}function c(e){return e[0]>=2147483648?~~Math.max(Math.min(e[0]-He,2147483647),-2147483648):~~Math.max(Math.min(e[0],2147483647),-2147483648)}function u(e){return 30>=e?1<<e:u(30)*u(e-30)}function d(e,t){var n,i,r,s;if(t&=63,a(e,Ge))return t?ze:e;if(0>e[1])throw Error("Neg");return s=u(t),i=e[1]*s%0x10000000000000000,(i+=n=(r=e[0]*s)-r%He)>=0x8000000000000000&&(i-=0x10000000000000000),[r-=n,i]}function h(e,t){var n;return n=u(t&=63),o(Math.floor(e[0]/n),e[1]/n)}function p(e,t){return o(e[0]-t[0],e[1]-t[1])}function f(e,t){return e.Mc=t,e.Lc=0,e.Yb=t.length,e}function m(e){return e.Lc>=e.Yb?-1:255&e.Mc[e.Lc++]}function g(e,t,n,i){return e.Lc>=e.Yb?-1:(i=Math.min(i,e.Yb-e.Lc),x(e.Mc,e.Lc,t,n,i),e.Lc+=i,i)}function b(e){return e.Mc=n(32),e.Yb=0,e}function y(e){var t=e.Mc;return t.length=e.Yb,t}function v(e,t){e.Mc[e.Yb++]=t<<24>>24}function w(e,t,n,i){x(t,n,e.Mc,e.Yb,i),e.Yb+=i}function x(e,t,n,i,r){for(var s=0;r>s;++s)n[i+s]=e[t+s]}function k(t,n,i,r,o){var a,l;if(s(r,Ve)<0)throw Error("invalid length "+r);for(t.Tb=r,function(e,t){(function(e,t){e.ab=t;for(var n=0;t>1<<n;++n);e.$b=2*n})(t,1<<e.s),t.n=e.f,function(e,t){var n=e.X;e.X=t,e.b&&n!=e.X&&(e.wb=-1,e.b=null)}(t,e.m),t.eb=0,t.fb=3,t.Y=2,t.y=3}(o,a=Y({})),a.Gc=void 0===e.disableEndMark,function(e,t){e.fc[0]=9*(5*e.Y+e.eb)+e.fb<<24>>24;for(var n=0;4>n;++n)e.fc[1+n]=e.ab>>8*n<<24>>24;w(t,e.fc,0,5)}(a,i),l=0;64>l;l+=8)v(i,255&c(h(r,l)));t.yb=(a.W=0,a.oc=n,a.pc=0,function(e){var t,n;e.b||(t={},n=4,e.X||(n=2),function(e,t){e.qb=t>2,e.qb?(e.w=0,e.xb=4,e.R=66560):(e.w=2,e.xb=3,e.R=0)}(t,n),e.b=t),he(e.A,e.eb,e.fb),(e.ab!=e.wb||e.Hb!=e.n)&&(_(e.b,e.ab,4096,e.n,274),e.wb=e.ab,e.Hb=e.n)}(a),a.d.Ab=i,function(e){(function(e){e.l=0,e.J=0;for(var t=0;4>t;++t)e.v[t]=0})(e),function(e){e.mc=ze,e.xc=ze,e.E=-1,e.Jb=1,e.Oc=0}(e.d),Pe(e.C),Pe(e._),Pe(e.bb),Pe(e.hb),Pe(e.Ub),Pe(e.vc),Pe(e.Sb),function(e){var t,n=1<<e.u+e.I;for(t=0;n>t;++t)Pe(e.V[t].tb)}(e.A);for(var t=0;4>t;++t)Pe(e.K[t].G);oe(e.$,1<<e.Y),oe(e.i,1<<e.Y),Pe(e.S.G),e.N=0,e.jb=0,e.q=0,e.s=0}(a),X(a),K(a),a.$.rb=a.n+1-2,de(a.$,1<<a.Y),a.i.rb=a.n+1-2,de(a.i,1<<a.Y),a.g=ze,function(e,t){return e.cb=t,e.Z=null,e.zc=1,e}({},a))}function A(e,t,n){return e.Nb=b({}),k(e,f({},t),e.Nb,l(t.length),n),e}function T(e,t,n){var i,r,s,o,a="",c=[];for(r=0;5>r;++r){if(-1==(s=m(t)))throw Error("truncated input");c[r]=s<<24>>24}if(!function(e,t){var n,i,r,s,o,a,l;if(5>t.length)return 0;for(l=255&t[0],r=l%9,s=(a=~~(l/9))%5,o=~~(a/5),n=0,i=0;4>i;++i)n+=(255&t[1+i])<<8*i;return n>99999999||!function(e,t,n,i){if(t>8||n>4||i>4)return 0;W(e.gb,n,t);var r=1<<i;return H(e.Rb,r),H(e.sb,r),e.Dc=r-1,1}(e,r,s,o)?0:function(e,t){return 0>t?0:(e.Ob!=t&&(e.Ob=t,e.nb=Math.max(e.Ob,1),D(e.B,Math.max(e.nb,4096))),1)}(e,n)}(i=j({}),c))throw Error("corrupted input");for(r=0;64>r;r+=8){if(-1==(s=m(t)))throw Error("truncated input");1==(s=s.toString(16)).length&&(s="0"+s),a=s+""+a}/^0+$|^f+$/i.test(a)?e.Tb=Ve:(o=parseInt(a,16),e.Tb=o>4294967295?Ve:l(o)),e.yb=function(e,t,n,i){return e.e.Ab=t,L(e.B),e.B.cc=n,function(e){e.B.h=0,e.B.o=0,Pe(e.Gb),Pe(e.pb),Pe(e.Zb),Pe(e.Cb),Pe(e.Db),Pe(e.Eb),Pe(e.kc),function(e){var t,n;for(n=1<<e.u+e.I,t=0;n>t;++t)Pe(e.V[t].Ib)}(e.gb);for(var t=0;4>t;++t)Pe(e.kb[t].G);z(e.Rb),z(e.sb),Pe(e.Fb.G),function(e){e.Bb=0,e.E=-1;for(var t=0;5>t;++t)e.Bb=e.Bb<<8|m(e.Ab)}(e.e)}(e),e.U=0,e.ib=0,e.Jc=0,e.Ic=0,e.Qc=0,e.Nc=i,e.g=ze,e.jc=0,function(e,t){return e.Z=t,e.cb=null,e.zc=1,e}({},e)}(i,t,n,e.Tb)}function E(e,t){return e.Nb=b({}),T(e,f({},t),e.Nb),e}function C(e,t){return e.c[e.f+e.o+t]}function S(e,t,n,i){var r,s;for(e.T&&e.o+t+i>e.h&&(i=e.h-(e.o+t)),++n,s=e.f+e.o+t,r=0;i>r&&e.c[s+r]==e.c[s+r-n];++r);return r}function I(e){return e.h-e.o}function P(e){var t,n;if(!e.T)for(;;){if(!(n=-e.f+e.Kb-e.h))return;if(-1==(t=g(e.cc,e.c,e.f+e.h,n)))return e.zb=e.h,e.f+e.zb>e.H&&(e.zb=e.H-e.f),void(e.T=1);e.h+=t,e.h>=e.o+e._b&&(e.zb=e.h-e._b)}}function U(e,t){e.f+=t,e.zb-=t,e.o-=t,e.h-=t}function _(e,t,i,r,s){var o,a;1073741567>t&&(e.Fc=16+(r>>1),function(e,t,i,r){var s;e.Bc=t,e._b=i,s=t+i+r,(null==e.c||e.Kb!=s)&&(e.c=null,e.Kb=s,e.c=n(e.Kb)),e.H=e.Kb-i}(e,t+i,r+s,256+~~((t+i+r+s)/2)),e.ob=r,o=t+1,e.p!=o&&(e.L=n(2*(e.p=o))),a=65536,e.qb&&(a=t-1,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a>>=1,(a|=65535)>16777216&&(a>>=1),e.Ec=a,++a,a+=e.R),a!=e.rc&&(e.ub=n(e.rc=a)))}function N(e){var t;++e.k>=e.p&&(e.k=0),function(e){++e.o,e.o>e.zb&&(e.f+e.o>e.H&&function(e){var t,n,i;for((i=e.f+e.o-e.Bc)>0&&--i,n=e.f+e.h-i,t=0;n>t;++t)e.c[t]=e.c[i+t];e.f-=i}(e),P(e))}(e),1073741823==e.o&&(t=e.o-e.p,O(e.L,2*e.p,t),O(e.ub,e.rc,t),U(e,t))}function O(e,t,n){var i,r;for(i=0;t>i;++i)n>=(r=e[i]||0)?r=0:r-=n,e[i]=r}function D(e,t){(null==e.Lb||e.M!=t)&&(e.Lb=n(t)),e.M=t,e.o=0,e.h=0}function R(e){var t=e.o-e.h;t&&(w(e.cc,e.Lb,e.h,t),e.o>=e.M&&(e.o=0),e.h=e.o)}function M(e,t){var n=e.o-t-1;return 0>n&&(n+=e.M),e.Lb[n]}function L(e){R(e),e.cc=null}function B(e){return 4>(e-=2)?e:3}function F(e){return 4>e?0:10>e?e-3:e-6}function $(e){if(!e.zc)throw Error("bad state");return e.cb?function(e){(function(e,t,n,r){var o,u,d,h,f,m,g,b,y,v,w,x,k,A,T;if(t[0]=ze,n[0]=ze,r[0]=1,e.oc&&(e.b.cc=e.oc,function(e){e.f=0,e.o=0,e.h=0,e.T=0,P(e),e.k=0,U(e,-1)}(e.b),e.W=1,e.oc=null),!e.pc){if(e.pc=1,A=e.g,a(e.g,ze)){if(!I(e.b))return void Q(e,c(e.g));ie(e),k=c(e.g)&e.y,Ue(e.d,e.C,(e.l<<4)+k,0),e.l=F(e.l),d=C(e.b,-e.s),fe(pe(e.A,c(e.g),e.J),e.d,d),e.J=d,--e.s,e.g=i(e.g,We)}if(!I(e.b))return void Q(e,c(e.g));for(;;){if(g=Z(e,c(e.g)),v=e.mb,k=c(e.g)&e.y,u=(e.l<<4)+k,1==g&&-1==v)Ue(e.d,e.C,u,0),d=C(e.b,-e.s),T=pe(e.A,c(e.g),e.J),7>e.l?fe(T,e.d,d):(y=C(e.b,-e.v[0]-1-e.s),me(T,e.d,y,d)),e.J=d,e.l=F(e.l);else{if(Ue(e.d,e.C,u,1),4>v){if(Ue(e.d,e.bb,e.l,1),v?(Ue(e.d,e.hb,e.l,1),1==v?Ue(e.d,e.Ub,e.l,0):(Ue(e.d,e.Ub,e.l,1),Ue(e.d,e.vc,e.l,v-2))):(Ue(e.d,e.hb,e.l,0),Ue(e.d,e._,u,1==g?0:1)),1==g?e.l=7>e.l?9:11:(le(e.i,e.d,g-2,k),e.l=7>e.l?8:11),h=e.v[v],0!=v){for(m=v;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h}}else{for(Ue(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,g-2,k),x=se(v-=4),b=B(g),ke(e.K[b],e.d,x),x>=4&&(w=v-(o=(2|1&x)<<(f=(x>>1)-1)),14>x?Ce(e.Sb,o-x-1,e.d,f,w):(_e(e.d,w>>4,f-4),Te(e.S,e.d,15&w),++e.Qb)),h=v,m=3;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h,++e.Mb}e.J=C(e.b,g-1-e.s)}if(e.s-=g,e.g=i(e.g,l(g)),!e.s){if(e.Mb>=128&&X(e),e.Qb>=16&&K(e),t[0]=e.g,n[0]=Ne(e.d),!I(e.b))return void Q(e,c(e.g));if(s(p(e.g,A),[4096,0])>=0)return e.pc=0,void(r[0]=0)}}}})(e.cb,e.cb.Xb,e.cb.uc,e.cb.Kc),e.Pb=e.cb.Xb[0],e.cb.Kc[0]&&(function(e){re(e),e.d.Ab=null}(e.cb),e.zc=0)}(e):function(e){var t=function(e){var t,n,r,o,a,u;if(u=c(e.g)&e.Dc,Ie(e.e,e.Gb,(e.U<<4)+u)){if(Ie(e.e,e.Zb,e.U))r=0,Ie(e.e,e.Cb,e.U)?(Ie(e.e,e.Db,e.U)?(Ie(e.e,e.Eb,e.U)?(n=e.Qc,e.Qc=e.Ic):n=e.Ic,e.Ic=e.Jc):n=e.Jc,e.Jc=e.ib,e.ib=n):Ie(e.e,e.pb,(e.U<<4)+u)||(e.U=7>e.U?9:11,r=1),r||(r=V(e.sb,e.e,u)+2,e.U=7>e.U?8:11);else if(e.Qc=e.Ic,e.Ic=e.Jc,e.Jc=e.ib,r=2+V(e.Rb,e.e,u),e.U=7>e.U?7:10,(a=we(e.kb[B(r)],e.e))>=4){if(o=(a>>1)-1,e.ib=(2|1&a)<<o,14>a)e.ib+=function(e,t,n,i){var r,s,o=1,a=0;for(s=0;i>s;++s)r=Ie(n,e,t+o),o<<=1,o+=r,a|=r<<s;return a}(e.kc,e.ib-a-1,e.e,o);else if(e.ib+=function(e,t){var n,i,r=0;for(n=t;0!=n;--n)e.E>>>=1,i=e.Bb-e.E>>>31,e.Bb-=e.E&i-1,r=r<<1|1-i,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8);return r}(e.e,o-4)<<4,e.ib+=function(e,t){var n,i,r=1,s=0;for(i=0;e.F>i;++i)n=Ie(t,e.G,r),r<<=1,r+=n,s|=n<<i;return s}(e.Fb,e.e),0>e.ib)return-1==e.ib?1:-1}else e.ib=a;if(s(l(e.ib),e.g)>=0||e.ib>=e.nb)return-1;(function(e,t,n){var i=e.o-t-1;for(0>i&&(i+=e.M);0!=n;--n)i>=e.M&&(i=0),e.Lb[e.o++]=e.Lb[i++],e.o>=e.M&&R(e)})(e.B,e.ib,r),e.g=i(e.g,l(r)),e.jc=M(e.B,0)}else t=function(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}(e.gb,c(e.g),e.jc),e.jc=7>e.U?function(e,t){var n=1;do{n=n<<1|Ie(t,e.Ib,n)}while(256>n);return n<<24>>24}(t,e.e):function(e,t,n){var i,r,s=1;do{if(r=n>>7&1,n<<=1,i=Ie(t,e.Ib,(1+r<<8)+s),s=s<<1|i,r!=i){for(;256>s;)s=s<<1|Ie(t,e.Ib,s);break}}while(256>s);return s<<24>>24}(t,e.e,M(e.B,e.ib)),function(e,t){e.Lb[e.o++]=t,e.o>=e.M&&R(e)}(e.B,e.jc),e.U=F(e.U),e.g=i(e.g,We);return 0}(e.Z);if(-1==t)throw Error("corrupted input");e.Pb=Ve,e.Pc=e.Z.g,(t||s(e.Z.Nc,ze)>=0&&s(e.Z.g,e.Z.Nc)>=0)&&(R(e.Z.B),L(e.Z.B),e.Z.e.Ab=null,e.zc=0)}(e),e.zc}function j(e){e.B={},e.e={},e.Gb=n(192),e.Zb=n(12),e.Cb=n(12),e.Db=n(12),e.Eb=n(12),e.pb=n(192),e.kb=n(4),e.kc=n(114),e.Fb=ve({},4),e.Rb=G({}),e.sb=G({}),e.gb={};for(var t=0;4>t;++t)e.kb[t]=ve({},6);return e}function H(e,t){for(;t>e.O;++e.O)e.ec[e.O]=ve({},3),e.hc[e.O]=ve({},3)}function V(e,t,n){return Ie(t,e.wc,0)?8+(Ie(t,e.wc,1)?8+we(e.tc,t):we(e.hc[n],t)):we(e.ec[n],t)}function G(e){return e.wc=n(2),e.ec=n(16),e.hc=n(16),e.tc=ve({},8),e.O=0,e}function z(e){Pe(e.wc);for(var t=0;e.O>t;++t)Pe(e.ec[t].G),Pe(e.hc[t].G);Pe(e.tc.G)}function W(e,t,i){var r,s;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,s=1<<e.u+e.I,e.V=n(s),r=0;s>r;++r)e.V[r]=q({})}function q(e){return e.Ib=n(768),e}function J(e,t){var n,i,r,s;e.jb=t,r=e.a[t].r,i=e.a[t].j;do{e.a[t].t&&(ye(e.a[r]),e.a[r].r=r-1,e.a[t].Ac&&(e.a[r-1].t=0,e.a[r-1].r=e.a[t].r2,e.a[r-1].j=e.a[t].j2)),s=r,n=i,i=e.a[s].j,r=e.a[s].r,e.a[s].j=n,e.a[s].r=t,t=s}while(t>0);return e.mb=e.a[0].j,e.q=e.a[0].r}function Y(e){var t;for(e.v=n(4),e.a=[],e.d={},e.C=n(192),e.bb=n(12),e.hb=n(12),e.Ub=n(12),e.vc=n(12),e._=n(192),e.K=[],e.Sb=n(114),e.S=xe({},4),e.$=ce({}),e.i=ce({}),e.A={},e.m=[],e.P=[],e.lb=[],e.nc=n(16),e.x=n(4),e.Q=n(4),e.Xb=[ze],e.uc=[ze],e.Kc=[0],e.fc=n(5),e.yc=n(128),e.vb=0,e.X=1,e.D=0,e.Hb=-1,e.mb=0,t=0;4096>t;++t)e.a[t]={};for(t=0;4>t;++t)e.K[t]=xe({},6);return e}function K(e){for(var t=0;16>t;++t)e.nc[t]=Ee(e.S,t);e.Qb=0}function X(e){var t,n,i,r,s,o,a,l;for(r=4;128>r;++r)t=(2|1&(o=se(r)))<<(i=(o>>1)-1),e.yc[r]=Se(e.Sb,t-o-1,i,r-t);for(s=0;4>s;++s){for(n=e.K[s],a=s<<6,o=0;e.$b>o;++o)e.P[a+o]=Ae(n,o);for(o=14;e.$b>o;++o)e.P[a+o]+=(o>>1)-1-4<<6;for(l=128*s,r=0;4>r;++r)e.lb[l+r]=e.P[a+r];for(;128>r;++r)e.lb[l+r]=e.P[a+se(r)]+e.yc[r]}e.Mb=0}function Q(e,t){re(e),function(e,t){if(e.Gc){Ue(e.d,e.C,(e.l<<4)+t,1),Ue(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,0,t);var n=B(2);ke(e.K[n],e.d,63),_e(e.d,67108863,26),Te(e.S,e.d,15)}}(e,t&e.y);for(var n=0;5>n;++n)Oe(e.d)}function Z(e,t){var n,i,r,s,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,x,k,A,T,E,P,U,_,N,O,D,R,M,L,B,$,j,H,V,G,z,W,q,Y,K;if(e.jb!=e.q)return f=e.a[e.q].r-e.q,e.mb=e.a[e.q].j,e.q=e.a[e.q].r,f;if(e.q=e.jb=0,e.N?(p=e.vb,e.N=0):p=ie(e),U=e.D,2>(E=I(e.b)+1))return e.mb=-1,1;for(E>273&&(E=273),G=0,u=0;4>u;++u)e.x[u]=e.v[u],e.Q[u]=S(e.b,-1,e.x[u],273),e.Q[u]>e.Q[G]&&(G=u);if(e.Q[G]>=e.n)return e.mb=G,ne(e,(f=e.Q[G])-1),f;if(p>=e.n)return e.mb=e.m[U-1]+4,ne(e,p-1),p;if(l=C(e.b,-1),y=C(e.b,-e.v[0]-1-1),2>p&&l!=y&&2>e.Q[G])return e.mb=-1,1;if(e.a[0].Hc=e.l,L=t&e.y,e.a[1].z=Ye[e.C[(e.l<<4)+L]>>>2]+be(pe(e.A,t,e.J),e.l>=7,y,l),ye(e.a[1]),V=(v=Ye[2048-e.C[(e.l<<4)+L]>>>2])+Ye[2048-e.bb[e.l]>>>2],y==l&&(z=V+function(e,t,n){return Ye[e.hb[t]>>>2]+Ye[e._[(t<<4)+n]>>>2]}(e,e.l,L),e.a[1].z>z&&(e.a[1].z=z,function(e){e.j=0,e.t=0}(e.a[1]))),2>(h=p>=e.Q[G]?p:e.Q[G]))return e.mb=e.a[1].j,1;e.a[1].r=0,e.a[0].bc=e.x[0],e.a[0].ac=e.x[1],e.a[0].dc=e.x[2],e.a[0].lc=e.x[3],d=h;do{e.a[d--].z=268435455}while(d>=2);for(u=0;4>u;++u)if(!(2>(H=e.Q[u]))){$=V+te(e,u,e.l,L);do{s=$+ue(e.i,H-2,L),(D=e.a[H]).z>s&&(D.z=s,D.r=0,D.j=u,D.t=0)}while(--H>=2)}if(T=v+Ye[e.bb[e.l]>>>2],p>=(d=e.Q[0]>=2?e.Q[0]+1:2)){for(_=0;d>e.m[_];)_+=2;for(;s=T+ee(e,c=e.m[_+1],d,L),(D=e.a[d]).z>s&&(D.z=s,D.r=0,D.j=c+4,D.t=0),d!=e.m[_]||(_+=2)!=U;++d);}for(n=0;;){if(++n==h)return J(e,n);if(w=ie(e),U=e.D,w>=e.n)return e.vb=w,e.N=1,J(e,n);if(++t,M=e.a[n].r,e.a[n].t?(--M,e.a[n].Ac?(q=e.a[e.a[n].r2].Hc,q=4>e.a[n].j2?7>q?8:11:7>q?7:10):q=e.a[M].Hc,q=F(q)):q=e.a[M].Hc,M==n-1?q=e.a[n].j?F(q):7>q?9:11:(e.a[n].t&&e.a[n].Ac?(M=e.a[n].r2,R=e.a[n].j2,q=7>q?8:11):q=4>(R=e.a[n].j)?7>q?8:11:7>q?7:10,O=e.a[M],4>R?R?1==R?(e.x[0]=O.ac,e.x[1]=O.bc,e.x[2]=O.dc,e.x[3]=O.lc):2==R?(e.x[0]=O.dc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.lc):(e.x[0]=O.lc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc):(e.x[0]=O.bc,e.x[1]=O.ac,e.x[2]=O.dc,e.x[3]=O.lc):(e.x[0]=R-4,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc)),e.a[n].Hc=q,e.a[n].bc=e.x[0],e.a[n].ac=e.x[1],e.a[n].dc=e.x[2],e.a[n].lc=e.x[3],a=e.a[n].z,l=C(e.b,-1),y=C(e.b,-e.x[0]-1-1),L=t&e.y,i=a+Ye[e.C[(q<<4)+L]>>>2]+be(pe(e.A,t,C(e.b,-2)),q>=7,y,l),x=0,(k=e.a[n+1]).z>i&&(k.z=i,k.r=n,k.j=-1,k.t=0,x=1),V=(v=a+Ye[2048-e.C[(q<<4)+L]>>>2])+Ye[2048-e.bb[q]>>>2],y!=l||n>k.r&&!k.j||(z=V+(Ye[e.hb[q]>>>2]+Ye[e._[(q<<4)+L]>>>2]),k.z>=z&&(k.z=z,k.r=n,k.j=0,k.t=0,x=1)),!(2>(E=P=(P=I(e.b)+1)>4095-n?4095-n:P))){if(E>e.n&&(E=e.n),!x&&y!=l&&(K=Math.min(P-1,e.n),(g=S(e.b,0,e.x[0],K))>=2)){for(Y=F(q),B=t+1&e.y,A=i+Ye[2048-e.C[(Y<<4)+B]>>>2]+Ye[2048-e.bb[Y]>>>2],N=n+1+g;N>h;)e.a[++h].z=268435455;s=A+(ue(e.i,g-2,B)+te(e,0,Y,B)),(D=e.a[N]).z>s&&(D.z=s,D.r=n+1,D.j=0,D.t=1,D.Ac=0)}for(W=2,j=0;4>j;++j)if(!(2>(m=S(e.b,-1,e.x[j],E)))){b=m;do{for(;n+m>h;)e.a[++h].z=268435455;s=V+(ue(e.i,m-2,L)+te(e,j,q,L)),(D=e.a[n+m]).z>s&&(D.z=s,D.r=n,D.j=j,D.t=0)}while(--m>=2);if(m=b,j||(W=m+1),P>m&&(K=Math.min(P-1-m,e.n),(g=S(e.b,m,e.x[j],K))>=2)){for(Y=7>q?8:11,B=t+m&e.y,r=V+(ue(e.i,m-2,L)+te(e,j,q,L))+Ye[e.C[(Y<<4)+B]>>>2]+be(pe(e.A,t+m,C(e.b,m-1-1)),1,C(e.b,m-1-(e.x[j]+1)),C(e.b,m-1)),Y=F(Y),B=t+m+1&e.y,A=r+Ye[2048-e.C[(Y<<4)+B]>>>2]+Ye[2048-e.bb[Y]>>>2],N=m+1+g;n+N>h;)e.a[++h].z=268435455;s=A+(ue(e.i,g-2,B)+te(e,0,Y,B)),(D=e.a[n+N]).z>s&&(D.z=s,D.r=n+m+1,D.j=0,D.t=1,D.Ac=1,D.r2=n,D.j2=j)}}if(w>E){for(w=E,U=0;w>e.m[U];U+=2);e.m[U]=w,U+=2}if(w>=W){for(T=v+Ye[e.bb[q]>>>2];n+w>h;)e.a[++h].z=268435455;for(_=0;W>e.m[_];)_+=2;for(m=W;;++m)if(s=T+ee(e,o=e.m[_+1],m,L),(D=e.a[n+m]).z>s&&(D.z=s,D.r=n,D.j=o+4,D.t=0),m==e.m[_]){if(P>m&&(K=Math.min(P-1-m,e.n),(g=S(e.b,m,o,K))>=2)){for(Y=7>q?7:10,B=t+m&e.y,r=s+Ye[e.C[(Y<<4)+B]>>>2]+be(pe(e.A,t+m,C(e.b,m-1-1)),1,C(e.b,m-(o+1)-1),C(e.b,m-1)),Y=F(Y),B=t+m+1&e.y,A=r+Ye[2048-e.C[(Y<<4)+B]>>>2]+Ye[2048-e.bb[Y]>>>2],N=m+1+g;n+N>h;)e.a[++h].z=268435455;s=A+(ue(e.i,g-2,B)+te(e,0,Y,B)),(D=e.a[n+N]).z>s&&(D.z=s,D.r=n+m+1,D.j=0,D.t=1,D.Ac=1,D.r2=n,D.j2=o+4)}if((_+=2)==U)break}}}}}function ee(e,t,n,i){var r=B(n);return(128>t?e.lb[128*r+t]:e.P[(r<<6)+function(e){return 131072>e?Je[e>>6]+12:134217728>e?Je[e>>16]+32:Je[e>>26]+52}(t)]+e.nc[15&t])+ue(e.$,n-2,i)}function te(e,t,n,i){var r;return t?(r=Ye[2048-e.hb[n]>>>2],1==t?r+=Ye[e.Ub[n]>>>2]:(r+=Ye[2048-e.Ub[n]>>>2],r+=De(e.vc[n],t-2))):(r=Ye[e.hb[n]>>>2],r+=Ye[2048-e._[(n<<4)+i]>>>2]),r}function ne(e,t){t>0&&(function(e,t){var n,i,r,s,o,a,l,c,u,d,h,p,f,m,g,b,y;do{if(e.h>=e.o+e.ob)p=e.ob;else if(p=e.h-e.o,e.xb>p){N(e);continue}for(f=e.o>e.p?e.o-e.p:0,i=e.f+e.o,e.qb?(a=1023&(y=qe[255&e.c[i]]^255&e.c[i+1]),e.ub[a]=e.o,l=65535&(y^=(255&e.c[i+2])<<8),e.ub[1024+l]=e.o,c=(y^qe[255&e.c[i+3]]<<5)&e.Ec):c=255&e.c[i]^(255&e.c[i+1])<<8,r=e.ub[e.R+c],e.ub[e.R+c]=e.o,g=1+(e.k<<1),b=e.k<<1,d=h=e.w,n=e.Fc;;){if(f>=r||0==n--){e.L[g]=e.L[b]=0;break}if(o=e.o-r,s=(e.k>=o?e.k-o:e.k-o+e.p)<<1,m=e.f+r,u=h>d?d:h,e.c[m+u]==e.c[i+u]){for(;++u!=p&&e.c[m+u]==e.c[i+u];);if(u==p){e.L[b]=e.L[s],e.L[g]=e.L[s+1];break}}(255&e.c[i+u])>(255&e.c[m+u])?(e.L[b]=r,b=s+1,r=e.L[b],h=u):(e.L[g]=r,g=s,r=e.L[g],d=u)}N(e)}while(0!=--t)}(e.b,t),e.s+=t)}function ie(e){var t=0;return e.D=function(e,t){var n,i,r,s,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,x,k;if(e.h>=e.o+e.ob)m=e.ob;else if(m=e.h-e.o,e.xb>m)return N(e),0;for(y=0,g=e.o>e.p?e.o-e.p:0,i=e.f+e.o,b=1,c=0,u=0,e.qb?(c=1023&(k=qe[255&e.c[i]]^255&e.c[i+1]),u=65535&(k^=(255&e.c[i+2])<<8),d=(k^qe[255&e.c[i+3]]<<5)&e.Ec):d=255&e.c[i]^(255&e.c[i+1])<<8,r=e.ub[e.R+d]||0,e.qb&&(s=e.ub[c]||0,o=e.ub[1024+u]||0,e.ub[c]=e.o,e.ub[1024+u]=e.o,s>g&&e.c[e.f+s]==e.c[i]&&(t[y++]=b=2,t[y++]=e.o-s-1),o>g&&e.c[e.f+o]==e.c[i]&&(o==s&&(y-=2),t[y++]=b=3,t[y++]=e.o-o-1,s=o),0!=y&&s==r&&(y-=2,b=1)),e.ub[e.R+d]=e.o,w=1+(e.k<<1),x=e.k<<1,p=f=e.w,0!=e.w&&r>g&&e.c[e.f+r+e.w]!=e.c[i+e.w]&&(t[y++]=b=e.w,t[y++]=e.o-r-1),n=e.Fc;;){if(g>=r||0==n--){e.L[w]=e.L[x]=0;break}if(l=e.o-r,a=(e.k>=l?e.k-l:e.k-l+e.p)<<1,v=e.f+r,h=f>p?p:f,e.c[v+h]==e.c[i+h]){for(;++h!=m&&e.c[v+h]==e.c[i+h];);if(h>b&&(t[y++]=b=h,t[y++]=l-1,h==m)){e.L[x]=e.L[a],e.L[w]=e.L[a+1];break}}(255&e.c[i+h])>(255&e.c[v+h])?(e.L[x]=r,x=a+1,r=e.L[x],f=h):(e.L[w]=r,w=a,r=e.L[w],p=h)}return N(e),y}(e.b,e.m),e.D>0&&((t=e.m[e.D-2])==e.n&&(t+=S(e.b,t-1,e.m[e.D-1],273-t))),++e.s,t}function re(e){e.b&&e.W&&(e.b.cc=null,e.W=0)}function se(e){return 2048>e?Je[e]:2097152>e?Je[e>>10]+20:Je[e>>20]+40}function oe(e,t){Pe(e.db);for(var n=0;t>n;++n)Pe(e.Vb[n].G),Pe(e.Wb[n].G);Pe(e.ic.G)}function ae(e,t,n,i,r){var s,o,a,l,c;for(s=Ye[e.db[0]>>>2],a=(o=Ye[2048-e.db[0]>>>2])+Ye[e.db[1]>>>2],l=o+Ye[2048-e.db[1]>>>2],c=0,c=0;8>c;++c){if(c>=n)return;i[r+c]=s+Ae(e.Vb[t],c)}for(;16>c;++c){if(c>=n)return;i[r+c]=a+Ae(e.Wb[t],c-8)}for(;n>c;++c)i[r+c]=l+Ae(e.ic,c-8-8)}function le(e,t,n,i){(function(e,t,n,i){8>n?(Ue(t,e.db,0,0),ke(e.Vb[i],t,n)):(n-=8,Ue(t,e.db,0,1),8>n?(Ue(t,e.db,1,0),ke(e.Wb[i],t,n)):(Ue(t,e.db,1,1),ke(e.ic,t,n-8)))})(e,t,n,i),0==--e.sc[i]&&(ae(e,i,e.rb,e.Cc,272*i),e.sc[i]=e.rb)}function ce(e){return function(e){e.db=n(2),e.Vb=n(16),e.Wb=n(16),e.ic=xe({},8);for(var t=0;16>t;++t)e.Vb[t]=xe({},3),e.Wb[t]=xe({},3)}(e),e.Cc=[],e.sc=[],e}function ue(e,t,n){return e.Cc[272*n+t]}function de(e,t){for(var n=0;t>n;++n)ae(e,n,e.rb,e.Cc,272*n),e.sc[n]=e.rb}function he(e,t,i){var r,s;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,s=1<<e.u+e.I,e.V=n(s),r=0;s>r;++r)e.V[r]=ge({})}function pe(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}function fe(e,t,n){var i,r,s=1;for(r=7;r>=0;--r)i=n>>r&1,Ue(t,e.tb,s,i),s=s<<1|i}function me(e,t,n,i){var r,s,o,a,l=1,c=1;for(s=7;s>=0;--s)r=i>>s&1,a=c,l&&(a+=1+(o=n>>s&1)<<8,l=o==r),Ue(t,e.tb,a,r),c=c<<1|r}function ge(e){return e.tb=n(768),e}function be(e,t,n,i){var r,s,o=1,a=7,l=0;if(t)for(;a>=0;--a)if(s=n>>a&1,r=i>>a&1,l+=De(e.tb[(1+s<<8)+o],r),o=o<<1|r,s!=r){--a;break}for(;a>=0;--a)r=i>>a&1,l+=De(e.tb[o],r),o=o<<1|r;return l}function ye(e){e.j=-1,e.t=0}function ve(e,t){return e.F=t,e.G=n(1<<t),e}function we(e,t){var n,i=1;for(n=e.F;0!=n;--n)i=(i<<1)+Ie(t,e.G,i);return i-(1<<e.F)}function xe(e,t){return e.F=t,e.G=n(1<<t),e}function ke(e,t,n){var i,r,s=1;for(r=e.F;0!=r;)i=n>>>--r&1,Ue(t,e.G,s,i),s=s<<1|i}function Ae(e,t){var n,i,r=1,s=0;for(i=e.F;0!=i;)n=t>>>--i&1,s+=De(e.G[r],n),r=(r<<1)+n;return s}function Te(e,t,n){var i,r,s=1;for(r=0;e.F>r;++r)i=1&n,Ue(t,e.G,s,i),s=s<<1|i,n>>=1}function Ee(e,t){var n,i,r=1,s=0;for(i=e.F;0!=i;--i)n=1&t,t>>>=1,s+=De(e.G[r],n),r=r<<1|n;return s}function Ce(e,t,n,i,r){var s,o,a=1;for(o=0;i>o;++o)Ue(n,e,t+a,s=1&r),a=a<<1|s,r>>=1}function Se(e,t,n,i){var r,s,o=1,a=0;for(s=n;0!=s;--s)r=1&i,i>>>=1,a+=Ye[(2047&(e[t+o]-r^-r))>>>2],o=o<<1|r;return a}function Ie(e,t,n){var i,r=t[n];return(-2147483648^(i=(e.E>>>11)*r))>(-2147483648^e.Bb)?(e.E=i,t[n]=r+(2048-r>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),0):(e.E-=i,e.Bb-=i,t[n]=r-(r>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),1)}function Pe(e){for(var t=e.length-1;t>=0;--t)e[t]=1024}function Ue(e,t,n,s){var o,a=t[n];o=(e.E>>>11)*a,s?(e.xc=i(e.xc,r(l(o),[4294967295,0])),e.E-=o,t[n]=a-(a>>>5)<<16>>16):(e.E=o,t[n]=a+(2048-a>>>5)<<16>>16),-16777216&e.E||(e.E<<=8,Oe(e))}function _e(e,t,n){for(var r=n-1;r>=0;--r)e.E>>>=1,1==(t>>>r&1)&&(e.xc=i(e.xc,l(e.E))),-16777216&e.E||(e.E<<=8,Oe(e))}function Ne(e){return i(i(l(e.Jb),e.mc),[4,0])}function Oe(e){var t,n=c(function(e,t){var n;return n=h(e,t&=63),0>e[1]&&(n=i(n,d([2,0],63-t))),n}(e.xc,32));if(0!=n||s(e.xc,[4278190080,0])<0){e.mc=i(e.mc,l(e.Jb)),t=e.Oc;do{v(e.Ab,t+n),t=255}while(0!=--e.Jb);e.Oc=c(e.xc)>>>24}++e.Jb,e.xc=d(r(e.xc,[16777215,0]),8)}function De(e,t){return Ye[(2047&(e-t^-t))>>>2]}function Re(e){for(var t,n,i,r=0,s=0,o=e.length,a=[],l=[];o>r;++r,++s){if(128&(t=255&e[r]))if(192==(224&t)){if(r+1>=o)return e;if(128!=(192&(n=255&e[++r])))return e;l[s]=(31&t)<<6|63&n}else{if(224!=(240&t))return e;if(r+2>=o)return e;if(128!=(192&(n=255&e[++r])))return e;if(128!=(192&(i=255&e[++r])))return e;l[s]=(15&t)<<12|(63&n)<<6|63&i}else{if(!t)return e;l[s]=t}16383==s&&(a.push(String.fromCharCode.apply(String,l)),s=-1)}return s>0&&(l.length=s,a.push(String.fromCharCode.apply(String,l))),a.join("")}function Me(e){var t,n,i,r=[],s=0,o=e.length;if("object"==typeof e)return e;for(function(e,t,n,i,r){var s;for(s=t;n>s;++s)i[r++]=e.charCodeAt(s)}(e,0,o,r,0),i=0;o>i;++i)(t=r[i])>=1&&127>=t?++s:s+=!t||t>=128&&2047>=t?2:3;for(n=[],s=0,i=0;o>i;++i)(t=r[i])>=1&&127>=t?n[s++]=t<<24>>24:!t||t>=128&&2047>=t?(n[s++]=(192|t>>6&31)<<24>>24,n[s++]=(128|63&t)<<24>>24):(n[s++]=(224|t>>12&15)<<24>>24,n[s++]=(128|t>>6&63)<<24>>24,n[s++]=(128|63&t)<<24>>24);return n}function Le(e){return e[1]+e[0]}var Be=1,Fe=2,$e=3,je="function"==typeof setImmediate?setImmediate:setTimeout,He=4294967296,Ve=[4294967295,-He],Ge=[0,-0x8000000000000000],ze=[0,0],We=[1,0],qe=function(){var e,t,n,i=[];for(e=0;256>e;++e){for(n=e,t=0;8>t;++t)0!=(1&n)?n=n>>>1^-306674912:n>>>=1;i[e]=n}return i}(),Je=function(){var e,t,n,i=2,r=[0,1];for(n=2;22>n;++n)for(t=1<<(n>>1)-1,e=0;t>e;++e,++i)r[i]=n<<24>>24;return r}(),Ye=function(){var e,t,n,i=[];for(t=8;t>=0;--t)for(e=1<<9-t,n=1<<9-t-1;e>n;++n)i[n]=(t<<6)+(e-n<<6>>>9-t-1);return i}(),Ke=function(){var e=[{s:16,f:64,m:0},{s:20,f:64,m:0},{s:19,f:64,m:1},{s:20,f:64,m:1},{s:21,f:128,m:1},{s:22,f:128,m:1},{s:23,f:128,m:1},{s:24,f:255,m:1},{s:25,f:255,m:1}];return function(t){return e[t-1]||e[6]}}();return"undefined"==typeof onmessage||"undefined"!=typeof window&&void 0!==window.document||(onmessage=function(t){t&&t.gc&&(t.gc.action==Fe?e.decompress(t.gc.gc,t.gc.cbn):t.gc.action==Be&&e.compress(t.gc.gc,t.gc.Rc,t.gc.cbn))}),{compress:function(e,n,i,r){var s,o,a={},l=void 0===i&&void 0===r;if("function"!=typeof i&&(o=i,i=r=0),r=r||function(e){return void 0!==o?t(e,o):void 0},i=i||function(e,t){return void 0!==o?postMessage({action:Be,cbn:o,result:e,error:t}):void 0},l){for(a.c=A({},Me(e),Ke(n));$(a.c.yb););return y(a.c.Nb)}try{a.c=A({},Me(e),Ke(n)),r(0)}catch(e){return i(null,e)}je((function e(){try{for(var t,n=(new Date).getTime();$(a.c.yb);)if(s=Le(a.c.yb.Pb)/Le(a.c.Tb),(new Date).getTime()-n>200)return r(s),je(e,0),0;r(1),t=y(a.c.Nb),je(i.bind(null,t),0)}catch(e){i(null,e)}}),0)},decompress:function(e,n,i){var r,s,o,a,l={},c=void 0===n&&void 0===i;if("function"!=typeof n&&(s=n,n=i=0),i=i||function(e){return void 0!==s?t(o?e:-1,s):void 0},n=n||function(e,t){return void 0!==s?postMessage({action:Fe,cbn:s,result:e,error:t}):void 0},c){for(l.d=E({},e);$(l.d.yb););return Re(y(l.d.Nb))}try{l.d=E({},e),a=Le(l.d.Tb),o=a>-1,i(0)}catch(e){return n(null,e)}je((function e(){try{for(var t,s=0,c=(new Date).getTime();$(l.d.yb);)if(++s%1e3==0&&(new Date).getTime()-c>200)return o&&(r=Le(l.d.yb.Z.g)/a,i(r)),je(e,0),0;i(1),t=Re(y(l.d.Nb)),je(n.bind(null,t),0)}catch(e){n(null,e)}}),0)}}}(),pxt,pxt,pxt,pxt,pxt,ts;this.LZMA=this.LZMA_WORKER=e,function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.DOMPurify=t()}(this,(function(){"use strict";function e(e){return function(t){for(var n=arguments.length,i=Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return h(e,t,i)}}function t(e){return function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];return p(e,n)}}function n(e,t){o&&o(e,null);for(var n=t.length;n--;){var i=t[n];if("string"==typeof i){var r=w(i);r!==i&&(a(t)||(t[n]=r),i=r)}e[i]=!0}return e}function i(e){var t={},n=void 0;for(n in e)h(s,e,[n])&&(t[n]=e[n]);return t}function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var s=Object.hasOwnProperty,o=Object.setPrototypeOf,a=Object.isFrozen,l=Object.keys,c=Object.freeze,u=Object.seal,d="undefined"!=typeof Reflect&&Reflect,h=d.apply,p=d.construct;h||(h=function(e,t,n){return e.apply(t,n)}),c||(c=function(e){return e}),u||(u=function(e){return e}),p||(p=function(e,t){return new(Function.prototype.bind.apply(e,[null].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(t))))});var f=e(Array.prototype.forEach),m=e(Array.prototype.indexOf),g=e(Array.prototype.join),b=e(Array.prototype.pop),y=e(Array.prototype.push),v=e(Array.prototype.slice),w=e(String.prototype.toLowerCase),x=e(String.prototype.match),k=e(String.prototype.replace),A=e(String.prototype.indexOf),T=e(String.prototype.trim),E=e(RegExp.prototype.test),C=t(RegExp),S=t(TypeError),I=c(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),P=c(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","audio","canvas","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","video","view","vkern"]),U=c(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),_=c(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),N=c(["#text"]),O=c(["accept","action","align","alt","autocomplete","background","bgcolor","border","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","coords","crossorigin","datetime","default","dir","disabled","download","enctype","face","for","headers","height","hidden","high","href","hreflang","id","integrity","ismap","label","lang","list","loop","low","max","maxlength","media","method","min","minlength","multiple","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","type","usemap","valign","value","width","xmlns"]),D=c(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","tabindex","targetx","targety","transform","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),R=c(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),M=c(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),L=u(/\{\{[\s\S]*|[\s\S]*\}\}/gm),B=u(/<%[\s\S]*|[\s\S]*%>/gm),F=u(/^data-[\-\w.\u00B7-\uFFFF]/),$=u(/^aria-[\-\w]+$/),j=u(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),H=u(/^(?:\w+script|data):/i),V=u(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g),G="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},z=function(){return"undefined"==typeof window?null:window},W=function(e,t){if("object"!==(void 0===e?"undefined":G(e))||"function"!=typeof e.createPolicy)return null;var n=null;t.currentScript&&t.currentScript.hasAttribute("data-tt-policy-suffix")&&(n=t.currentScript.getAttribute("data-tt-policy-suffix"));var i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}};return function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:z(),s=function(t){return e(t)};if(s.version="2.0.8",s.removed=[],!t||!t.document||9!==t.document.nodeType)return s.isSupported=!1,s;var o=t.document,a=!1,u=!1,d=t.document,h=t.DocumentFragment,p=t.HTMLTemplateElement,q=t.Node,J=t.NodeFilter,Y=t.NamedNodeMap,K=void 0===Y?t.NamedNodeMap||t.MozNamedAttrMap:Y,X=t.Text,Q=t.Comment,Z=t.DOMParser,ee=t.trustedTypes;if("function"==typeof p){var te=d.createElement("template");te.content&&te.content.ownerDocument&&(d=te.content.ownerDocument)}var ne=W(ee,o),ie=ne?ne.createHTML(""):"",re=d,se=re.implementation,oe=re.createNodeIterator,ae=re.getElementsByTagName,le=re.createDocumentFragment,ce=o.importNode,ue={};s.isSupported=se&&void 0!==se.createHTMLDocument&&9!==d.documentMode;var de=L,he=B,pe=F,fe=$,me=H,ge=V,be=j,ye=null,ve=n({},[].concat(r(I),r(P),r(U),r(_),r(N))),we=null,xe=n({},[].concat(r(O),r(D),r(R),r(M))),ke=null,Ae=null,Te=!0,Ee=!0,Ce=!1,Se=!1,Ie=!1,Pe=!1,Ue=!1,_e=!1,Ne=!1,Oe=!1,De=!1,Re=!1,Me=!0,Le=!0,Be=!1,Fe={},$e=n({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","plaintext","script","style","svg","template","thead","title","video","xmp"]),je=n({},["audio","video","img","source","image"]),He=null,Ve=n({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Ge=null,ze=d.createElement("form"),We=function(e){Ge&&Ge===e||(e&&"object"===(void 0===e?"undefined":G(e))||(e={}),ye="ALLOWED_TAGS"in e?n({},e.ALLOWED_TAGS):ve,we="ALLOWED_ATTR"in e?n({},e.ALLOWED_ATTR):xe,He="ADD_URI_SAFE_ATTR"in e?n(i(Ve),e.ADD_URI_SAFE_ATTR):Ve,ke="FORBID_TAGS"in e?n({},e.FORBID_TAGS):{},Ae="FORBID_ATTR"in e?n({},e.FORBID_ATTR):{},Fe="USE_PROFILES"in e&&e.USE_PROFILES,Te=!1!==e.ALLOW_ARIA_ATTR,Ee=!1!==e.ALLOW_DATA_ATTR,Ce=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Se=e.SAFE_FOR_JQUERY||!1,Ie=e.SAFE_FOR_TEMPLATES||!1,Pe=e.WHOLE_DOCUMENT||!1,Ne=e.RETURN_DOM||!1,Oe=e.RETURN_DOM_FRAGMENT||!1,De=e.RETURN_DOM_IMPORT||!1,Re=e.RETURN_TRUSTED_TYPE||!1,_e=e.FORCE_BODY||!1,Me=!1!==e.SANITIZE_DOM,Le=!1!==e.KEEP_CONTENT,Be=e.IN_PLACE||!1,be=e.ALLOWED_URI_REGEXP||be,Ie&&(Ee=!1),Oe&&(Ne=!0),Fe&&(ye=n({},[].concat(r(N))),we=[],!0===Fe.html&&(n(ye,I),n(we,O)),!0===Fe.svg&&(n(ye,P),n(we,D),n(we,M)),!0===Fe.svgFilters&&(n(ye,U),n(we,D),n(we,M)),!0===Fe.mathMl&&(n(ye,_),n(we,R),n(we,M))),e.ADD_TAGS&&(ye===ve&&(ye=i(ye)),n(ye,e.ADD_TAGS)),e.ADD_ATTR&&(we===xe&&(we=i(we)),n(we,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&n(He,e.ADD_URI_SAFE_ATTR),Le&&(ye["#text"]=!0),Pe&&n(ye,["html","head","body"]),ye.table&&(n(ye,["tbody"]),delete ke.tbody),c&&c(e),Ge=e)},qe=function(e){y(s.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=ie}},Je=function(e,t){try{y(s.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){y(s.removed,{attribute:null,from:t})}t.removeAttribute(e)},Ye=function(e){var t=void 0,i=void 0;if(_e)e="<remove></remove>"+e;else{var r=x(e,/^[\s]+/);i=r&&r[0]}var s=ne?ne.createHTML(e):e;if(a)try{t=(new Z).parseFromString(s,"text/html")}catch(e){}if(u&&n(ke,["title"]),!t||!t.documentElement){var o=(t=se.createHTMLDocument("")).body;o.parentNode.removeChild(o.parentNode.firstElementChild),o.outerHTML=s}return e&&i&&t.body.insertBefore(d.createTextNode(i),t.body.childNodes[0]||null),ae.call(t,Pe?"html":"body")[0]};s.isSupported&&(function(){try{Ye('<svg><p><textarea><img src="</textarea><img src=x abc=1//">').querySelector("svg img")&&(a=!0)}catch(e){}}(),function(){try{var e=Ye("<x/><title></title><img>");E(/<\/title/,e.querySelector("title").innerHTML)&&(u=!0)}catch(e){}}());var Ke=function(e){return oe.call(e.ownerDocument||e,e,J.SHOW_ELEMENT|J.SHOW_COMMENT|J.SHOW_TEXT,(function(){return J.FILTER_ACCEPT}),!1)},Xe=function(e){return!(e instanceof X||e instanceof Q||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof K&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI)},Qe=function(e){return"object"===(void 0===q?"undefined":G(q))?e instanceof q:e&&"object"===(void 0===e?"undefined":G(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},Ze=function(e,t,n){ue[e]&&f(ue[e],(function(e){e.call(s,t,n,Ge)}))},et=function(e){var t=void 0;if(Ze("beforeSanitizeElements",e,null),Xe(e))return qe(e),!0;var n=w(e.nodeName);if(Ze("uponSanitizeElement",e,{tagName:n,allowedTags:ye}),("svg"===n||"math"===n)&&0!==e.querySelectorAll("p, br").length)return qe(e),!0;if(!ye[n]||ke[n]){if(Le&&!$e[n]&&"function"==typeof e.insertAdjacentHTML)try{var i=e.innerHTML;e.insertAdjacentHTML("AfterEnd",ne?ne.createHTML(i):i)}catch(e){}return qe(e),!0}return"noscript"===n&&E(/<\/noscript/i,e.innerHTML)||"noembed"===n&&E(/<\/noembed/i,e.innerHTML)?(qe(e),!0):(!Se||e.firstElementChild||e.content&&e.content.firstElementChild||!E(/</g,e.textContent)||(y(s.removed,{element:e.cloneNode()}),e.innerHTML?e.innerHTML=k(e.innerHTML,/</g,"<"):e.innerHTML=k(e.textContent,/</g,"<")),Ie&&3===e.nodeType&&(t=e.textContent,t=k(t,de," "),t=k(t,he," "),e.textContent!==t&&(y(s.removed,{element:e.cloneNode()}),e.textContent=t)),Ze("afterSanitizeElements",e,null),!1)},tt=function(e,t,n){if(Me&&("id"===t||"name"===t)&&(n in d||n in ze))return!1;if(Ee&&E(pe,t));else if(Te&&E(fe,t));else{if(!we[t]||Ae[t])return!1;if(He[t]);else if(E(be,k(n,ge,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==A(n,"data:")||!je[e])if(Ce&&!E(me,k(n,ge,"")));else if(n)return!1}return!0},nt=function(e){var t=void 0,n=void 0,i=void 0,r=void 0,o=void 0;Ze("beforeSanitizeAttributes",e,null);var a=e.attributes;if(a){var c={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we};for(o=a.length;o--;){var u=t=a[o],d=u.name,h=u.namespaceURI;if(n=T(t.value),i=w(d),c.attrName=i,c.attrValue=n,c.keepAttr=!0,c.forceKeepAttr=void 0,Ze("uponSanitizeAttribute",e,c),n=c.attrValue,!c.forceKeepAttr){if("name"===i&&"IMG"===e.nodeName&&a.id)r=a.id,a=v(a,[]),Je("id",e),Je(d,e),m(a,r)>o&&e.setAttribute("id",r.value);else{if("INPUT"===e.nodeName&&"type"===i&&"file"===n&&c.keepAttr&&(we[i]||!Ae[i]))continue;"id"===d&&e.setAttribute(d,""),Je(d,e)}if(c.keepAttr)if(Se&&E(/\/>/i,n))Je(d,e);else if(E(/svg|math/i,e.namespaceURI)&&E(C("</("+g(l($e),"|")+")","i"),n))Je(d,e);else{Ie&&(n=k(n,de," "),n=k(n,he," "));var p=e.nodeName.toLowerCase();if(tt(p,i,n))try{h?e.setAttributeNS(h,d,n):e.setAttribute(d,n),b(s.removed)}catch(e){}}}}Ze("afterSanitizeAttributes",e,null)}},it=function e(t){var n=void 0,i=Ke(t);for(Ze("beforeSanitizeShadowDOM",t,null);n=i.nextNode();)Ze("uponSanitizeShadowNode",n,null),et(n)||(n.content instanceof h&&e(n.content),nt(n));Ze("afterSanitizeShadowDOM",t,null)};return s.sanitize=function(e,n){var i=void 0,r=void 0,a=void 0,l=void 0,c=void 0;if(e||(e="\x3c!--\x3e"),"string"!=typeof e&&!Qe(e)){if("function"!=typeof e.toString)throw S("toString is not a function");if("string"!=typeof(e=e.toString()))throw S("dirty is not a string, aborting")}if(!s.isSupported){if("object"===G(t.toStaticHTML)||"function"==typeof t.toStaticHTML){if("string"==typeof e)return t.toStaticHTML(e);if(Qe(e))return t.toStaticHTML(e.outerHTML)}return e}if(Ue||We(n),s.removed=[],"string"==typeof e&&(Be=!1),Be);else if(e instanceof q)1===(r=(i=Ye("\x3c!--\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?i=r:i.appendChild(r);else{if(!Ne&&!Ie&&!Pe&&Re&&-1===e.indexOf("<"))return ne?ne.createHTML(e):e;if(!(i=Ye(e)))return Ne?null:ie}i&&_e&&qe(i.firstChild);for(var u=Ke(Be?e:i);a=u.nextNode();)3===a.nodeType&&a===l||et(a)||(a.content instanceof h&&it(a.content),nt(a),l=a);if(l=null,Be)return e;if(Ne){if(Oe)for(c=le.call(i.ownerDocument);i.firstChild;)c.appendChild(i.firstChild);else c=i;return De&&(c=ce.call(o,c,!0)),c}var d=Pe?i.outerHTML:i.innerHTML;return Ie&&(d=k(d,de," "),d=k(d,he," ")),ne&&Re?ne.createHTML(d):d},s.setConfig=function(e){We(e),Ue=!0},s.clearConfig=function(){Ge=null,Ue=!1},s.isValidAttribute=function(e,t,n){Ge||We({});var i=w(e),r=w(t);return tt(i,r,n)},s.addHook=function(e,t){"function"==typeof t&&(ue[e]=ue[e]||[],y(ue[e],t))},s.removeHook=function(e){ue[e]&&b(ue[e])},s.removeHooks=function(e){ue[e]&&(ue[e]=[])},s.removeAllHooks=function(){ue={}},s}()})),pxt||(pxt={}),function(e){!function(t){const n={},i={};let r=!1;t.addDefaultProperties=function(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]}))},t.enable=function(){if(!e.aiTrackException||!e.aiTrackEvent||r)return;r=!0,e.debug("setting up app insights");const t=e.tickEvent;e.tickEvent=function(r,s,o){if(t&&t(r,s,o),(null==o?void 0:o.interactiveConsent)&&e.setInteractiveConsent(!0),s){const t=Object.assign({},n)||{},o=Object.assign({},i)||{};Object.keys(s).forEach((e=>{"string"==typeof s[e]?t[e]=s[e]:"number"==typeof s[e]?o[e]=s[e]:t[e]=JSON.stringify(s[e]||"")})),e.aiTrackEvent(r,t,o)}else e.aiTrackEvent(r)};const s=e.reportException;e.reportException=function(t,n){s&&s(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const o=e.reportError;e.reportError=function(t,n,i){o&&o(t,n,i);try{throw n}catch(r){const s={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(s,i),e.aiTrackException(r,"error",s)}}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,r=0,s=!1;function o(){return t||(t=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),t}function a(){t&&(i.gain.setTargetAtTime(0,t.currentTime,.015),r=0)}e.mute=function(e){t&&(s=e,a(),e&&n&&(n.disconnect(),i.disconnect(),n=void 0,i=void 0))},e.stop=a,e.frequency=function(){return r},e.tone=function(e){if(s)return;if(e<0)return;r=e;let a=o();if(a)try{n||(n=a.createOscillator(),n.type="triangle",i=a.createGain(),i.gain.value=0,i.connect(a.destination),n.connect(i),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),i.gain.setTargetAtTime(.2,t.currentTime,.015)}catch(e){return void(n=void 0)}}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxt||(pxt={})),function(e){!function(t){const n="auth",i="csrf-token",r="login-state",s="user-state";let o,a=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){return o};let l=0,c=0;t.AuthClient=class{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.prefPatchOps=[],e.Util.assert(!o),o=this}async initAsync(){try{this.state$=await e.storage.shared.getAsync(n,s)}catch(e){}this.state$||(this.state$={}),this.setUserProfileAsync(this.state$.profile),this.setUserPreferencesAsync(this.state$.preferences)}async loginAsync(t,i,s){var o;if(!h()||!function(e){return d().filter((t=>t.id===e)).length>0}(t))return;s=null!=s?s:u;const a=this.getState();a.profile||await this.authCheckAsync();if((null===(o=a.profile)||void 0===o?void 0:o.idp)===t)return void e.debug(`loginAsync: Already signed into ${t}.`);this.clearState();const l={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:s,callbackPathname:window.location.pathname,idp:t};await e.storage.shared.setAsync(n,r,l);const c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${l.key}`}),p=await this.apiAsync(c);p.success?(e.tickEvent("auth.login.start",{provider:t}),window.location.href=p.resp.loginUrl):await this.onSignInFailed()}async logoutAsync(t){if(!h())return;e.tickEvent("auth.logout"),await this.apiAsync("/api/auth/logout"),await e.storage.shared.delAsync(n,i),this.clearState();const r=t?t.startsWith("#")?t:`#${t}`:"";e.BrowserUtils.hasWindow()&&(window.location.href=`${window.location.origin}${window.location.pathname}${r}`,location.reload())}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const r=null===(t=this.getState().profile)||void 0===t?void 0:t.id,s=await this.apiAsync("/api/user",null,"DELETE");if(s.err)await this.onApiError(s.err);else try{await e.storage.shared.delAsync(n,i);try{await this.onProfileDeleted(r)}catch(t){e.tickEvent("auth.profile.cloudToLocalFailed")}this.clearState()}finally{e.tickEvent("auth.profile.deleted")}}async initialUserPreferencesAsync(){if(await this.loggedInAsync())return this.initialUserPreferences_||(this.initialUserPreferences_=this.fetchUserPreferencesAsync()),this.initialUserPreferences_}async userProfileAsync(){if(!await this.loggedInAsync())return;const e=this.getState();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=this.getState();return Object.assign({},e.preferences)}async authCheckAsync(){var t;if(!h())return;if(!await e.storage.shared.getAsync(n,i))return;const r=this.getState();return(null===(t=r.profile)||void 0===t?void 0:t.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(r.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return await this.authCheckAsync(),this.hasUserId()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=this.getState(),n=await this.apiAsync("/api/user/profile",{id:t.profile.id,username:e.username,avatarUrl:e.avatarUrl});return n.success&&await this.setUserProfileAsync(n.resp),n.success}async patchUserPreferencesAsync(t,n=!1){t=(t=Array.isArray(t)?t:[t]).filter((e=>!!e));const i=await this.userPreferencesAsync();if(!t.length)return{success:!0,res:i};if(ts.pxtc.jsonPatch.patchInPlace(i,t),await this.setUserPreferencesAsync(i),!await this.loggedInAsync())return{success:!0,res:i};t.forEach(((e,n)=>{this.prefPatchOps.some(((i,r)=>!!ts.pxtc.jsonPatch.opsAreEqual(i,e)&&(this.prefPatchOps[r]=e,t[n]=null,!0)))})),t.filter((e=>!!e)).forEach((e=>this.prefPatchOps.push(e))),clearTimeout(l);const r=async()=>{c=0;const t=this.prefPatchOps;this.prefPatchOps=[];const n=await this.apiAsync("/api/user/preferences",t,"PATCH");return n.success?(e.debug("Updating local user preferences w/ cloud data after result of POST"),this.setUserPreferencesAsync(n.resp)):e.reportError("identity","update preferences failed",n),{success:n.success,res:n.resp}};return n?await r():(c||(c=e.U.now()),1e4<e.U.now()-c?await r():(l=setTimeout(r,1e3),{success:!1,res:void 0}))}hasUserId(){var e;if(!h())return!1;return!!(null===(e=this.getState().profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!h())return;const t=this.getState();if(null===(e=t.profile)||void 0===e?void 0:e.id)return t.profile;const n=await this.apiAsync("/api/user/profile");if(n.success){const e=n.resp;return await this.setUserProfileAsync(e),e}}async setUserProfileAsync(e){const t=this.hasUserId();this.transformUserProfile(e);const n=this.hasUserId();this.onUserProfileChanged(),n&&!t?await this.onSignedIn():!n&&t&&await this.onSignedOut()}async setUserPreferencesAsync(e){var n;const i=null!==(n=this.getState().preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),r=ts.pxtc.jsonPatch.diff(i,e);this.transformUserPreferences(Object.assign(Object.assign({},i),e)),await this.onUserPreferencesChanged(r)}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;const e=this.getState(),t=await this.apiAsync("/api/user/preferences");return t.success&&t.resp?(this.setUserPreferencesAsync(t.resp),e.preferences):void 0}transformUserProfile(e){this.state$=Object.assign(Object.assign({},this.state$),{profile:Object.assign({},e)}),this.saveState()}transformUserPreferences(e){this.state$=Object.assign(Object.assign({},this.state$),{preferences:Object.assign({},e)}),this.saveState()}getState(){return this.state$}saveState(){e.storage.shared.setAsync(n,s,this.state$).then((()=>{}))}clearState(){this.state$={},e.storage.shared.delAsync(n,s).then((()=>this.onStateCleared()))}async apiAsync(t,r,s){var o;const a={},l=await e.storage.shared.getAsync(n,i);return l&&(a.authorization=`mkcd ${l}`),a["x-pxt-target"]=null===(o=e.appTarget)||void 0===o?void 0:o.id,t=e.BrowserUtils.isLocalHostDev()?`https://staging.pxt.io${t}`:t,e.Util.requestAsync({url:t,headers:a,data:r,method:s||(r?"POST":"GET"),withCredentials:!0}).then((e=>({statusCode:e.statusCode,resp:e.json,success:2===Math.floor(e.statusCode/100),err:null}))).catch((async e=>(/logout/.test(t)||401!=e.statusCode||await this.logoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1})))}};const u={hash:"",params:{}};function d(){var t,n;return Object.keys((null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.cloud)||void 0===n?void 0:n.cloudProviders)||{}).map((t=>e.appTarget.cloud.cloudProviders[t])).filter((e=>e.identity)).sort(((e,t)=>e.order-t.order))}function h(){return!a&&!e.BrowserUtils.isPxtElectron()&&d().length>0}function p(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let s,o=Object.assign({},u);do{if(s=await e.storage.shared.getAsync(n,r),!s)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,r);const a=t.state;if(!a||s.key!==a)return void e.debug("Failed to get auth state for key");o=Object.assign(Object.assign({},u),s.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:s.idp}),e.log(`Auth failed: ${l}:${n}`),o=Object.assign({},u);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}await e.storage.shared.setAsync(n,i,c),e.tickEvent("auth.login.success",{provider:s.idp})}while(0);const a=o.hash.startsWith("#")?o.hash:`#${o.hash}`,l=e.Util.stringifyQueryString("",o.params),c=`${s.callbackPathname.startsWith("/")?s.callbackPathname:`/${s.callbackPathname}`}${a}${l}`;window.location.href=c},t.identityProviders=d,t.identityProvider=function(e){return d().filter((t=>t.id===e)).shift()},t.hasIdentity=h,t.enableAuth=function(e=!0){a=!e},t.userName=function(e){var t,n,i,r;return null!==(r=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==r?r:"??"},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),r=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(r)}catch(e){}}},t.badgeEquals=p,t.hasBadge=function(e,t){return e.badges.some((e=>p(e,t)))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){!function(e){e.__dummy=42}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));var pxtc=ts.pxtc;!function(e){!function(e){!function(e){function t(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.flatClone=function(e){if(null==e)return null;let t={};return Object.keys(e).forEach((n=>{t[n]=e[n]})),t},e.clone=function(e){return null==e?null:JSON.parse(JSON.stringify(e))},e.htmlEscape=function(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,(e=>String.fromCharCode(Number(e.substr(2,e.length-3))))):e},e.jsStringQuote=t,e.jsStringLiteral=function(e){return'"'+t(e)+'"'},e.initials=function(e){if(/^\w+@/.test(e)){return e.match(/^\w\w/).shift().toUpperCase()}{const t=e.match(/\b\w/g)||[];return((t.shift()||"")+(t.pop()||"")).toUpperCase()}};let n="en",i={},r={},s=!1;function o(){return n}function a(e){const t=/^(\w{2})-(\w{2}$)/i.exec(e);return t&&t[1]&&t[2]?[`${t[1].toLowerCase()}-${t[2].toUpperCase()}`,t[1].toLowerCase(),`${t[1].toLowerCase()}-${t[2].toLowerCase()}`]:[(e||"en").toLowerCase()]}function l(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,i,r){let s=n[parseInt(i)],o="",a=/^:f(\d*)\.(\d+)/.exec(r);if(a){let e=parseInt(a[2]),t=parseInt(a[1])||0,n=/^0/.test(a[1])?"0":" ",i=s.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;o=i}else o=":x"==r?"0x"+s.toString(16):void 0===s?"(undef)":null===s?"(null)":s.toString?s.toString():s+"";return":a"==r?/^\s*[euioah]/.test(o.toLowerCase())?o="an "+o:/^\s*[bcdfgjklmnpqrstvwxz]/.test(o.toLowerCase())&&(o="a "+o):":s"==r?o=1==s?"":"s":":q"==r?o=e.htmlEscape(o):":jq"==r?o=e.jsStringQuote(o):":uri"==r?o=encodeURIComponent(o).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?o=encodeURI(o).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(o=(100*s).toFixed(1).toString()+"%"),o}))}e.enableLiveLocalizationUpdates=function(){s=!0},e.liveLocalizationEnabled=function(){return s},e.localeInfo=function(){return`${s?"live-":""}${o()}`},e.userLanguage=o,e.normalizeLanguageCode=a,e.setUserLanguage=function(e){n=a(e)[0]},e.isUserLanguageRtl=function(){return/^ar|dv|fa|ha|he|ks|ku|ps|ur|yi/i.test(n)},e.TRANSLATION_LOCALE="pxt",e.isTranslationMode=function(){return o()==e.TRANSLATION_LOCALE},e._localize=function(e){return i[e]||e},e.getLocalizedStrings=function(){return i},e.setLocalizedStrings=function(e){i=e},e.translationsCache=function(){return r},e.fmt_va=l,e.fmt=function(e,...t){return l(e,t)};const c={};e.dumpLocStats=function(){const e={};Object.keys(c).sort(((e,t)=>c[t]-c[e])).forEach((t=>e[t]=t)),console.log("prioritized list of strings:"),console.log(JSON.stringify(e,null,2))};function u(t,n){if(!t)return t;c[t]=(c[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),l(i,n)}e.lf_va=u,e.lf=function(e,...t){return u(e,t)},e.rlf=function(e,...t){return u(e,t)},e.lookup=function(e,t){return e.hasOwnProperty(t)?e[t]:null},e.isoTime=function(t){let n=new Date(1e3*t);return e.fmt("{0}-{1:f02.0}-{2:f02.0} {3:f02.0}:{4:f02.0}:{5:f02.0}",n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds())},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.deq=function e(t,n){if(t===n)return null;if(!t||!n)return"Null value";if("object"==typeof t&&"object"==typeof n){if(Array.isArray(t)){if(!Array.isArray(n))return"Expected array";if(t.length!=n.length)return"Expected array of length "+t.length+", got "+n.length;for(let i=0;i<t.length;i++)if(null!=e(t[i],n[i]))return"Expected array value "+t[i]+" got "+n[i];return null}let i=Object.keys(t),r=Object.keys(t);if(i.length!=r.length)return"Expected "+i.length+" keys, got "+r.length;for(let r=0;r<i.length;r++){if(!Object.prototype.hasOwnProperty.call(n,i[r]))return"Missing key "+i[r];if(null!=e(t[i[r]],n[i[r]]))return"Expected value of "+i[r]+" to be "+t[i[r]]+", got "+n[i[r]]}return null}return"Unable to compare "+t+", "+n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,ts,pxt,ts,pxtmelody,pxtmelody,pxtmelody,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(e){e.decodeBase64=function(e){return atob(e)},e.encodeBase64=function(e){return btoa(e)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function i(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function r(e){let t=[];for(let n=0;n<e.length;++n)i(t,e[n]);return t}function s(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function o(e,t,n,i,r){void 0===i&&(i=0),void 0===r&&(r=n.length-i);for(let s=0;s<r;++s)e[t+s]=n[i+s]}function a(e,t){return e==t?0:e<t?-1:1}n.CancellationToken=class{constructor(){this.pending=!1,this.cancelled=!1}startOperation(){this.pending=!0}isRunning(){return this.pending}onProgress(e){this.progressHandler=e}reportProgress(e,t){this.progressHandler&&this.progressHandler(e,t)}cancel(){this.cancelled=!0,this.pending=!1}cancelAsync(){return this.cancelled||!this.pending?(this.cancelled=!0,this.pending=!1,Promise.resolve()):(this.cancelled=!0,this.deferred=new Promise((e=>{this.resolve=e})),this.deferred)}isCancelled(){return this.cancelled}throwIfCancelled(){if(this.isCancelled())throw new Error}resolveCancel(){this.pending=!1,this.deferred&&(this.resolve(),this.deferred=void 0,this.resolve=void 0)}},n.codalHash16=function(e){const t=[251,175,119,215,81,14,79,191,103,49,181,143,186,157,0,232,31,32,55,60,152,58,17,237,174,70,160,144,220,90,57,223,59,3,18,140,111,166,203,196,134,243,124,95,222,179,197,65,180,48,36,15,107,46,233,130,165,30,123,161,209,23,97,16,40,91,219,61,100,10,210,109,250,127,22,138,29,108,244,67,207,9,178,204,74,98,126,249,167,116,34,77,193,200,121,5,20,113,71,35,128,13,182,94,25,226,227,199,75,27,41,245,230,224,43,225,177,26,155,150,212,142,218,115,241,73,88,105,39,114,62,255,192,201,145,214,168,158,221,148,154,122,12,84,82,163,44,139,228,236,205,242,217,11,187,146,159,64,86,239,195,42,106,198,118,112,184,172,87,2,173,117,176,229,247,253,137,185,99,164,102,147,45,66,231,52,141,211,194,206,246,238,56,110,78,248,63,240,189,93,92,51,53,183,19,171,72,50,33,104,101,69,8,252,83,120,76,135,85,54,202,125,188,213,96,235,136,208,162,129,190,132,156,38,47,1,7,254,24,4,216,131,89,21,28,133,37,153,149,80,170,68,6,169,234,151];function n(e){let n=0;for(let i=0;i<e.length;i++){let r=e[i];n=t[n^r]}return n}return e?function(e,t){let i;const r=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);r[t]=255&n}let s=0;for(let e=0;e<t;++e)i=n(r),s|=i<<8*e,r[0]=(r[0]+1)%255;return s}(e,2):0},n.bufferSerial=function(e,t="",n="?",i=255){for(let r=0;r<t.length;++r){const s=t[r];if(e[n]=(e[n]||"")+s,"\n"===s||e[n].length>i){let t=e[n];e[n]="",window.postMessage({type:"serial",id:n,data:t},"*")}}},n.blobReadAsDataURL=function(e){return e?new Promise(((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=e=>n(e),i.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(new Uint8Array(i.result)),i.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(i.result),i.readAsText(e)})):Promise.resolve(null)},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=((e,t)=>e===t)){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach((n=>t(n,e[n])))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach((i=>n[i]=t(i,e[i]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=i,n.concatArrayLike=function(e){return r(e)},n.concat=r,n.memcpy=o,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),i=0;for(let t of e)o(n,i,t),i+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,i){i&&Object.keys(i).forEach((r=>{s(t[r])&&s(i[r])?e(t[r],i[r]):t[r]=n.clone(i[r])}))},n.jsonCopyFrom=function(e,t){let i=n.clone(t);for(let n of Object.keys(t))e[n]=i[n]},n.jsonFlatten=function(e){let t={},i=(e,r)=>{if(null!==r&&"object"==typeof r){n.assert(!Array.isArray(r)),e&&(e+=".");for(let t of Object.keys(r))i(e+t,r[t])}else t[e]=r};return i("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let i=t,r=n.split(".");for(let t=0;t<r.length;++t){let s=r[t];t==r.length-1?i[s]=e[n]:("object"!=typeof i[s]&&(i[s]={}),i=i[s])}}return t},n.strcmp=a,n.stringMapEq=function(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!=i.length)return!1;for(let i of n){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i])return!1}return!0},n.endsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(-t.length)==t)},n.startsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(0,t.length)==t)},n.contains=function(e,t){return!(e.length<t.length)&&(0==t.length||e.indexOf(t)>-1)},n.replaceAll=function(e,t,n){return t?e.split(t).join(n):e},n.snakify=function(e){const t=e.toUpperCase(),n=e.toLowerCase();if(e==t||e==n)return e;if(e.lastIndexOf("_")>0)return e;const i=t=>e[t]!=n[t],r=n=>e[n]!=t[n];let s="",o=0;for(;o<e.length;){let t=i(o),n=o;for(;n<e.length;){if(t&&r(n)){if(n-o>2){n--;break}t=!1}if(!t&&i(n))break;n++}s&&(s+="_"),s+=e.slice(o,n),o=n}return s.toUpperCase()===s?s:s.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(a);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},n.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let r=t(e);i.hasOwnProperty(r)||(i[r]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let i=t(e);n.hasOwnProperty(i)||(n[i]=[]),n[i].push(e)})),n},n.toDictionary=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=e})),n},n.toSet=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=!0})),n},n.toArray=function(e){if(Array.isArray(e))return e;let t=[];if(!e)return t;for(let n=0;n<e.length;++n)t.push(e[n]);return t},n.indexOfMatching=function(e,t){for(let n=0;n<e.length;++n)if(t(e[n]))return n;return-1};const l=Promise.resolve();async function c(e,t,n){let i=0;const r=[],s=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,r=t[e];s[e]=await n(r)}})();r.push(e)}try{await Promise.all(r)}catch(e){throw i=t.length,e}return s}function u(e,t){const n={};return i=>{const r=e(i);return n.hasOwnProperty(r)?n[r]:n[r]=t(i)}}n.nextTick=function(e){l.then(e)},n.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},n.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},n.promiseMapAllSeries=function(e,t){return c(1,e,t)},n.promisePoolAsync=c,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let i,r;const s=new Promise(((t,s)=>{r=t,i=setTimeout((()=>{r=void 0,clearTimeout(i),s(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,s]).then((e=>(r&&(clearTimeout(i),r()),e)))},n.defer=function(){let e,t,n,i=!1;return{resolve:function(n){i?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),i=!0)},reject:function(t){i?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),i=!0)},promise:new Promise((function(i,r){e?i(e):(t=i,n=r)}))}},n.memoize=u,n.debounce=function(e,t,n){let i;return function(){let r=this,s=arguments,o=function(){i=null,n||e.apply(r,s)},a=n&&!i;return clearTimeout(i),i=setTimeout(o,t),a&&e.apply(r,s),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){return n.httpRequestCoreAsync(e).then((i=>{const r=i.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(r)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",i.statusCode,e.url,(i.text||"").slice(0,500)),r=new Error(t);return r.statusCode=i.statusCode,Promise.reject(r)}return i.text&&/application\/json/.test(i.headers["content-type"])&&(i.json=t.U.jsonTryParse(i.text)),i}))}function p(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let r=e.charCodeAt(i);if(r<=127)n+=e.charAt(i);else if(r<=2047)n+=String.fromCharCode(192|r>>6,128|63&r);else{if(!t&&55296<=r&&r<=56319){let t=e.charCodeAt(++i);isNaN(t)||(r=65536+(r-55296<<10)+(t-56320))}n+=r<=65535?String.fromCharCode(224|r>>12,128|r>>6&63,128|63&r):String.fromCharCode(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,i=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=i,this.lastPoke=0,this.recentGaps=[],this.wrapped=()=>{this.timeout=null,this.func()}}poke(){const e=Date.now();if(this.lastPoke){const t=e-this.lastPoke;if(t<10)return;for(t<4e3&&this.recentGaps.push(t);this.recentGaps.length>10;)this.recentGaps.shift()}this.lastPoke=e}trigger(){let e=this.maxDelay;if(this.lastPoke){const t=this.recentGaps.slice();t.sort();const n=t[t.length>>1]||1;e=Math.min(Math.max(n*this.slowdownFactor|0,this.minDelay),this.maxDelay);e-=Date.now()-this.lastPoke,e<0&&(e=0),this.lastPoke=null}clearTimeout(this.timeout),this.timeout=setTimeout(this.wrapped,e)}},n.throttle=function(e,t,n){let i;return function(){let r=this,s=arguments,o=function(){i=null,n||e.apply(r,s)},a=n&&!i;i||(i=setTimeout(o,t)),a&&e.apply(r,s)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[m()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,(function(e,t){return String.fromCharCode(parseInt(t,16))}))},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return h({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise(((n,i)=>{let r=this.promises[e];r||(r=this.promises[e]=[]),r.push((()=>t().finally((()=>{r.shift(),0==r.length?delete this.promises[e]:r[0]()})).then(n,i))),1==r.length&&r[0]()}))}};function f(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n,i){function r(r){pxt.debug(`downloading translations for ${e} ${t} ${n||""}`);let s=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",o=`${s}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;n&&(o+="&branch="+encodeURIComponent(n));const a={};return i&&!pxt.Cloud.useCdnApi()&&(a["If-None-Match"]=i),(s?h:pxt.Cloud.apiRequestWithCdnAsync)({url:o,headers:a}).then((s=>304==s.statusCode||200==s.statusCode?(i=s.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((o=>o.setAsync(e,t,n,i,s.json||r))).then((()=>s.json||r))):s.json),(e=>{console.log(`failed to load translations from ${o}`)}))}return pxt.BrowserUtils.translationDbAsync().then((i=>i.getAsync(e,t,n))).then((e=>{if(e){i=e.etag;return(Date.now()-e.time)/1e3>300&&r(e.strings),e.strings}return r()}))}function b(e){let[t,i]=n.normalizeLanguageCode(e),r=pxt.appTarget.appTheme;if(r&&r.availableLocales){if(r.availableLocales.indexOf(t)>-1)return!0;if(i&&r.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,r,s,o,a,l){if(l=l||y.Editor,"en-US"===(r=n.normalizeLanguageCode(r)[0])||"en"===r)return Promise.resolve(void 0);let c,u,d=`${r}/${a}/${l}`;if(n.translationsCache()[d])return Promise.resolve(n.translationsCache()[d]);switch(l){case y.Editor:c=[{branch:s,staticName:"strings.json",path:"strings.json"},{branch:o,staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:c=[{branch:o,staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:c=[{branch:o,staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:c=[{branch:o,staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function h(e){e&&(u||(u={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>u[t]=e[t])))}if(a){let a=0;return t.U.promiseMapAllSeries(c,(e=>g(r,e.path,e.branch).then(h,(e=>{console.log(e.message),++a})))).then((()=>(a&&(n.translationsCache()[d]=u),a!==c.length&&u?Promise.resolve(u):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,r,s,o,!1,l)))))}return Promise.all(c.map((e=>n.httpGetJsonAsync(`${i}locales/${r}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(u=t,n.translationsCache()[d]=u)}),(e=>{console.error("failed to load localizations")})).then((()=>u))}function w(e){const t={};for(const n of Object.keys(e))t[n]=x(e[n]);return t}function x(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(k),extendsTypes:e.extendsTypes?[...e.extendsTypes]:void 0,pkgs:e.pkgs?[...e.pkgs]:void 0,combinedProperties:e.combinedProperties?[...e.combinedProperties]:void 0,name:e.name,namespace:e.namespace,fileName:e.fileName,kind:e.kind,retType:e.retType,isInstance:e.isInstance,isContextual:e.isContextual,qName:e.qName,pkg:e.pkg,snippet:e.snippet,snippetName:e.snippetName,snippetWithMarkers:e.snippetWithMarkers,pySnippet:e.pySnippet,pySnippetName:e.pySnippetName,pySnippetWithMarkers:e.pySnippetWithMarkers,blockFields:e.blockFields,isReadOnly:e.isReadOnly,pyName:e.pyName,pyQName:e.pyQName,snippetAddsDefinitions:e.snippetAddsDefinitions}}function k(e){var n,i;return{name:e.name,description:e.description,type:e.type,pyTypeString:e.pyTypeString,initializer:e.initializer,default:e.default,properties:null===(n=e.properties)||void 0===n?void 0:n.map(A),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(A),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function A(e){return{name:e.name,type:e.type}}n.PromiseBuffer=class{constructor(){this.waiting=[],this.available=[]}drain(){for(let e of this.waiting)e(new Error("Promise Buffer Reset"));this.waiting=[],this.available=[]}pushError(e){this.push(e)}push(e){let t=this.waiting.shift();t?t(e):this.available.push(e)}shiftAsync(e=0){if(this.available.length>0){let e=this.available.shift();return e instanceof Error?Promise.reject(e):Promise.resolve(e)}return new Promise(((n,i)=>{let r=e=>{e instanceof Error?i(e):n(e)};this.waiting.push(r),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(r);e>=0&&(this.waiting.splice(e,1),i(new Error("Timeout")))}))}))}},n.now=f,n.nowSeconds=function(){return Math.round(f()/1e3)},n.timeout=function(e){return new Promise((t=>setTimeout((()=>t()),e)))},n.cpuUs=()=>{const e="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now;return n.cpuUs=()=>1e3*e(),n.cpuUs()},n.getMime=function(e){let t=/\.([a-zA-Z0-9]+)$/.exec(e);if(!t)return"application/octet-stream";switch(t[1].toLowerCase()){case"txt":return"text/plain";case"html":case"htm":return"text/html";case"css":return"text/css";case"js":return"application/javascript";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"ico":return"image/x-icon";case"manifest":return"text/cache-manifest";case"webmanifest":return"application/manifest+json";case"json":return"application/json";case"svg":return"image/svg+xml";case"eot":return"application/vnd.ms-fontobject";case"ttf":return"font/ttf";case"woff":return"application/font-woff";case"woff2":return"application/font-woff2";case"md":return"text/markdown";case"xml":return"application/xml";case"m4a":return"audio/m4a";case"mp3":return"audio/mp3";default:return"application/octet-stream"}},n.randomUint32=m,n.guidGen=function(){function e(){return(65536|m()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=g,n.pxtLangCookieId="PXT_LANG",n.langCookieExpirationDays=30,n.allLanguages={af:{englishName:"Afrikaans",localizedName:"Afrikaans"},ar:{englishName:"Arabic",localizedName:"العربية"},az:{englishName:"Azerbaijani",localizedName:"آذربایجان دیلی"},bg:{englishName:"Bulgarian",localizedName:"български"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},da:{englishName:"Danish",localizedName:"Dansk"},de:{englishName:"German",localizedName:"Deutsch"},el:{englishName:"Greek",localizedName:"Ελληνικά"},en:{englishName:"English",localizedName:"English"},"es-ES":{englishName:"Spanish (Spain)",localizedName:"Español (España)"},"es-MX":{englishName:"Spanish (Mexico)",localizedName:"Español (México)"},et:{englishName:"Estonian",localizedName:"Eesti"},eu:{englishName:"Basque",localizedName:"Euskara"},fa:{englishName:"Persian",localizedName:"فارسی"},fi:{englishName:"Finnish",localizedName:"Suomi"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"gu-IN":{englishName:"Gujarati",localizedName:"ગુજરાતી"},he:{englishName:"Hebrew",localizedName:"עברית"},hr:{englishName:"Croatian",localizedName:"Hrvatski"},hu:{englishName:"Hungarian",localizedName:"Magyar"},"hy-AM":{englishName:"Armenian (Armenia)",localizedName:"Հայերէն (Հայաստան)"},id:{englishName:"Indonesian",localizedName:"Bahasa Indonesia"},is:{englishName:"Icelandic",localizedName:"Íslenska"},it:{englishName:"Italian",localizedName:"Italiano"},ja:{englishName:"Japanese",localizedName:"日本語"},kab:{englishName:"Kabyle",localizedName:"شئعم"},ko:{englishName:"Korean",localizedName:"한국어"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},nl:{englishName:"Dutch",localizedName:"Nederlands"},no:{englishName:"Norwegian",localizedName:"Norsk"},nb:{englishName:"Norwegian Bokmal",localizedName:"Norsk bokmål"},"nn-NO":{englishName:"Norwegian Nynorsk",localizedName:"Norsk nynorsk"},"pa-IN":{englishName:"Punjabi",localizedName:"ਪੰਜਾਬੀ"},pl:{englishName:"Polish",localizedName:"Polski"},"pt-BR":{englishName:"Portuguese (Brazil)",localizedName:"Português (Brasil)"},"pt-PT":{englishName:"Portuguese (Portugal)",localizedName:"Português (Portugal)"},ro:{englishName:"Romanian",localizedName:"Română"},ru:{englishName:"Russian",localizedName:"Русский"},"si-LK":{englishName:"Sinhala (Sri Lanka)",localizedName:"සිංහල (ශ්රී ලංකා)"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sr:{englishName:"Serbian",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish (Sweden)",localizedName:"Svenska (Sverige)"},ta:{englishName:"Tamil",localizedName:"தமிழ்"},te:{englishName:"Telugu",localizedName:"తెలుగు"},th:{englishName:"Thai",localizedName:"ภาษาไทย"},tl:{englishName:"Tagalog",localizedName:"ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"},tr:{englishName:"Turkish",localizedName:"Türkçe"},uk:{englishName:"Ukrainian",localizedName:"Українська"},"ur-IN":{englishName:"Urdu (India)",localizedName:"اردو (ہندوستان)"},"ur-PK":{englishName:"Urdu (Pakistan)",localizedName:"اردو (پاکستان)"},vi:{englishName:"Vietnamese",localizedName:"Tiếng việt"},"zh-CN":{englishName:"Chinese (Simplified)",localizedName:"简体中文"},"zh-TW":{englishName:"Chinese (Traditional)",localizedName:"繁體中文"}},n.isLocaleEnabled=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:r,pxtBranch:s,targetBranch:o,force:a}=t;let{code:l}=t;if(l=n.normalizeLanguageCode(l)[0],"en-US"===l&&(l="en"),l===n.userLanguage()||!b(l)&&!a)return pxt.debug(`loc: ${l} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${l}`);const c=pxt.Util.liveLocalizationEnabled();return v(i,r,l,s,o,c,e.pxtc.Util.TranslationsKind.Editor).then((t=>(t&&(n.setUserLanguage(l),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,r,l,s,o,c,e.pxtc.Util.TranslationsKind.Apis).then((t=>{t&&(e.pxtc.apiLocalizationStrings=t)})))))},function(e){e[e.Editor=0]="Editor",e[e.Sim=1]="Sim",e[e.Apis=2]="Apis",e[e.SkillMap=3]="SkillMap"}(y=n.TranslationsKind||(n.TranslationsKind={})),n.downloadTranslationsAsync=v,n.capitalize=function(e){return e?e[0].toLocaleUpperCase()+e.slice(1):e},n.uncapitalize=function(e){return(e||"").split(/(?=[A-Z])/g).join(" ").toLowerCase()},n.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},i=null,r=null){const s="--------------------------0461489f461126c5";let o="";Object.keys(t).forEach((e=>function(e,t){o+=s+"\r\n",o+='Content-Disposition: form-data; name="'+e+'"\r\n\r\n',o+=t+"\r\n"}(e,t[e]))),i&&function(e,t){const n=e.split("/").reverse()[0];o+=s+"\r\n",o+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',o+="\r\n",o+=t+"\r\n"}(i,r),o+=s+"--\r\n";const a={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+s.slice(2)},data:o};return n.httpRequestCoreAsync(a)},n.toDataUri=function(e,n){return/^https?:/i.test(e)||/^data:/i.test(e)?e:(n||/^<svg/i.test(e)&&(n="image/svg+xml"),/xml|svg/.test(n)?`data:${n},${encodeURIComponent(e)}`:`data:${n||"image/png"};base64,${t.encodeBase64(p(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const i=n.imageHeaderSize+t.length,r=3*(e.width*e.height-1);let s=1;for(;s<4&&!(r*s>=8*i);)s++;let o=r*s>>3,a=i-o,l=0,c=e.width*e.height*4;if(a>0){const t=3*e.width;l=Math.ceil(a/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+l;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,l,0,0,0,0,0,0]);function d(e,t,n,i){let r=0,s=0,o=i[s++];const a=(1<<n)-1;let l=!0;for(;l;){let c=o>>r&a,u=8-r;if(u<=n){if(s>=i.length){if(0==u)break;l=!1}o=i[s++],c|=o<<u&a,r=n-u}else r+=n;e[t]=255&(e[t]&~a|c),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const h=e.getContext("2d"),p=h.getImageData(0,0,e.width,e.height);d(p.data,0,1,[s]);let f=4;if(f=d(p.data,f,s,u),pxt.Util.assert(0==(3&f)),0==l)f=d(p.data,f,s,t);else{let e=o-u.length;f=d(p.data,f,s,t.slice(0,e)),f=d(p.data,c,8,t.slice(e))}for(f|=3;f<p.data.length;)p.data[f]=255,f+=4;return h.putImageData(p,0,0),e},n.decodeBlobAsync=function(e){return pxt.BrowserUtils.loadCanvasAsync(e).then((e=>{const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data,i=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(i>5||0==i)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function r(e,n,i){let r=0,s=0,o=0;const a=(1<<n)-1;for(;s<i.length;)o|=(t[e++]&a)<<r,3==(3&e)&&e++,r+=n,r>=8&&(i[s++]=255&o,o>>=8,r-=8);return e}const s=new Uint8Array(pxt.Util.imageHeaderSize);let o=r(4,i,s);const a=pxt.HF2.decodeU32LE(s);if(a[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const l=new Uint8Array(a[1]),c=a[2];if(c>0){const t=(e.height-c)*e.width,n=new Uint8Array((3*(t-1)*i>>3)-pxt.Util.imageHeaderSize);r(o,i,n),l.set(n);const s=new Uint8Array(l.length-n.length);r(4*t,8,s),l.set(s,n.length)}else r(o,i,l);return l}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,i)=>(t[decodeURIComponent(n)]=decodeURIComponent(i),""))),t},n.stringifyQueryString=function(e,t){for(let n of Object.keys(t))e.indexOf("?")>=0?e+="&":e+="?",e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]);return e},n.cloneTargetBundle=function(e){const t=(e=Object.assign({},e)).apiInfo;delete e.apiInfo;const i=e.bundleddirs;delete e.bundleddirs;const r=e.bundledpkgs;delete e.bundledpkgs;const s=e.tutorialInfo;delete e.tutorialInfo;const o=n.clone(e);if(t){o.apiInfo={};for(const e of Object.keys(t)){const n=t[e].apis;o.apiInfo[e]={sha:t[e].sha,apis:{jres:Object.assign({},n.jres),byQName:w(n.byQName)}}}}if(i&&(o.bundleddirs=[...i]),r){o.bundledpkgs={};for(const e of Object.keys(r))o.bundledpkgs[e]=Object.assign({},r[e])}if(s){o.tutorialInfo={};for(const e of Object.keys(s)){const t=s[e];o.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks)}}}return o},n.cloneApis=w,n.cloneSymbolInfo=x,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)}}(t.Util||(t.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){e.Util.httpRequestCoreAsync=function(t){return new Promise(((n,i)=>{let r,s=!1,o=e.Util.clone(t.headers)||{};r=new XMLHttpRequest,t.responseArrayBuffer&&(r.responseType="arraybuffer"),t.withCredentials&&(r.withCredentials=!0),r.onreadystatechange=()=>{if(!s&&4==r.readyState){s=!0;let e={statusCode:r.status,headers:{},buffer:r.responseBody||r.response,text:t.responseArrayBuffer?void 0:r.responseText};r.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let a,l=t.data,c=t.method||(null==l?"GET":"POST");null==l?a=null:l instanceof Uint8Array?a=l:"object"==typeof l?(a=JSON.stringify(l),o["content-type"]="application/json; charset=utf8"):"string"==typeof l?a=l:e.Util.oops("bad data"),r.open(c,t.url),Object.keys(o).forEach((e=>{r.setRequestHeader(e,o[e])})),null==a?r.send():r.send(a)}))},e.Util.sha256=o,e.Util.getRandomBuf=e=>{if(window.crypto)window.crypto.getRandomValues(e);else for(let t=0;t<e.length;++t)e[t]=Math.floor(255*Math.random())};const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,t){return e>>>t|e<<32-t}function r(t,r){e.Util.assert(8==t.length),e.Util.assert(64==r.length);for(let e=16;e<64;++e){let t=i(r[e-15],7)^i(r[e-15],18)^r[e-15]>>>3,n=i(r[e-2],17)^i(r[e-2],19)^r[e-2]>>>10;r[e]=r[e-16]+t+r[e-7]+n|0}let s=t[0],o=t[1],a=t[2],l=t[3],c=t[4],u=t[5],d=t[6],h=t[7];for(let e=0;e<64;++e){let t=h+(i(c,6)^i(c,11)^i(c,25))+(c&u^~c&d)+n[e]+r[e]|0,p=s&o^s&a^o&a;h=d,d=u,u=c,c=l+t|0,l=a,a=o,o=s,s=t+((i(s,2)^i(s,13)^i(s,22))+p|0)|0}t[0]+=s,t[1]+=o,t[2]+=a,t[3]+=l,t[4]+=c,t[5]+=u,t[6]+=d,t[7]+=h}function s(e){let t=new Uint32Array(8);t[0]=1779033703,t[1]=3144134277,t[2]=1013904242,t[3]=2773480762,t[4]=1359893119,t[5]=2600822924,t[6]=528734635,t[7]=1541459225;let n=new Uint32Array(64);function i(e){let i=e.length-63;for(let s=0;s<i;s+=64){for(let t=0;t<16;t++){let i=(t<<2)+s;n[t]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}r(t,n)}}i(e);let s=64-(e.length+9)%64;64==s&&(s=0);let o=e.length-e.length%64,a=new Uint8Array(e.length-o+1+s+8),l=0;for(;o<e.length;)a[l++]=e[o++];for(a[l++]=128;s-- >0;)a[l++]=0;let c=8*e.length;for(l=a.length;c>0;)a[--l]=255&c,c>>=8;i(a);let u="";for(let e=0;e<t.length;++e)u+=("000000000"+t[e].toString(16)).slice(-8);return u.toLowerCase()}function o(t){pxt.perf.measureStart("sha256buffer");const n=s(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=s,t.sha256string=o}(e.BrowserImpl||(e.BrowserImpl={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={add:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");if(t in e)throw new Error(`jsonPatch: object already contains key ${t}`);e[t]=n},replace:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");e[t]=n},remove:(e,t)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");delete e[t]}},i={add:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");if(t in e)throw new Error(`jsonPatch: key ${t} already exists in array`);"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,0,n)},replace:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,1,n)},remove:(e,t)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?delete e[t]:e.splice(t,1)}};t.diff=function(e,t){const n={add:[],remove:[],replace:[]};function i(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,r,s){if(!Object.is(t,r)){r=r||{},t=t||{};for(let e of Object.keys(t))if(!(e in r)){const r=i(t,e);n.remove.push({op:"remove",path:s.concat(r)})}for(const o of Object.keys(r)){const a=t[o],l=r[o],c=i(r,o);c in t?"object"!=typeof a&&"object"!=typeof l&&a!==l||typeof a!=typeof l||Array.isArray(a)!==Array.isArray(l)?n.replace.push({op:"replace",path:s.concat(c),value:l}):e(a,l,s.concat(c)):void 0!==r[c]&&(s.length&&n.add.push({op:"add",path:s,value:Array.isArray(r)?[]:{}}),n.add.push({op:"add",path:s.concat(c),value:l}))}}}(e,t,[]),[...n.remove.reverse(),...n.replace,...n.add.sort(((e,t)=>e.path.length-t.path.length))]},t.patchInPlace=function(e,t){if(!e||"object"!=typeof e)throw new Error("jsonPatch: Must be an object or an array.");for(const r of t){const t=r.path.slice(),s=t.pop();if(null==s)throw new Error("jsonPatch: missing last key");let o=e,a=t.shift();for(;null!=a;){if(!(a in o))throw new Error(`jsonPatch: missing parent element ${a}`);o=o[a],a=t.shift()}if(Array.isArray(o)&&"number"!=typeof s)throw new Error("jsonPatch: expected numeric index for array object");const l=Array.isArray(o)?i:n;"remove"===r.op?l.remove(o,s):"add"!==r.op||s in o?"replace"===r.op&&l.replace(o,s,r.value):l.add(o,s,r.value)}},t.opsAreEqual=function(t,n){return t.op===n.op&&e.U.arrayEquals(t.path,n.path)}}(e.jsonPatch||(e.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(t){!function(t){function n(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){const i=Array.isArray(e),r=Array.isArray(t);if(i&&r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(!n(e[i],t[i]))return!1;return!0}if(i!==r)return!1;const s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(const i of s){if(!t.hasOwnProperty(i))return!1;if(!n(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}t.diffTests=function(){const t=[{comment:"test 1",obja:{a:4,b:5},objb:{a:3,b:5},expected:[{op:"replace",path:["a"],value:3}]},{comment:"test 2",obja:{a:3,b:5},objb:{a:4,c:5},expected:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}]},{comment:"test 3",obja:{a:4,b:[1,2,3]},objb:{a:3,b:[1,2,4]},expected:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4}]},{comment:"test 4",obja:{a:3,b:[1,2,4]},objb:{a:3,b:[1,2,4,5]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",3],value:5}]},{comment:"test 5",obja:{a:4,b:{c:3}},objb:{a:4,b:{c:4}},expected:[{op:"replace",path:["b","c"],value:4}]},{comment:"test 6",obja:{a:4,b:{c:4}},objb:{a:5,b:{d:4}},expected:[{op:"remove",path:["b","c"]},{op:"replace",path:["a"],value:5},{op:"add",path:["b"],value:{}},{op:"add",path:["b","d"],value:4}]},{comment:"test 7",obja:{a:4,b:[2,"foo"]},objb:{a:4,b:[2,"foo",["this","that"]]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",2],value:["this","that"]}]}];for(const i of t){console.log(i.comment);const t=e.pxtc.jsonPatch.diff(i.obja,i.objb);n(t,i.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",i.expected))}},t.patchTests=function(){const t=[{comment:"test 1",obj:{a:"foo",b:[4,11]},patches:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}],expected:{a:4,c:5}},{comment:"test 2",obj:{a:4,b:[1,2,3]},patches:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4},{op:"add",path:["b",3],value:9}],expected:{a:3,b:[1,2,4,9]}},{comment:"test 3",obj:{a:4,b:{c:3}},patches:[{op:"replace",path:["a"],value:5},{op:"remove",path:["b","c"]},{op:"add",path:["b","d"],value:4}],expected:{a:5,b:{d:4}}},{comment:"test 4",obj:{a:4},patches:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",0],value:"foo"},{op:"add",path:["b",1],value:"bar"}],expected:{a:4,b:["foo","bar"]},validate:e=>e.b&&e.b.forEach}];for(const i of t){console.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches);!n(i.obj,i.expected)||!i.validate||i.validate(i.obj)?console.log("succeeded"):i.expected&&(console.error("FAILED"),console.log("got",i.obj),console.log("exp",i.expected))}}}(t.tests||(t.tests={}))}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.report||(pxt.perf.report=()=>{}),pxt.perf.recordMilestone||(pxt.perf.recordMilestone=()=>{}),pxt.perf.measureStart||(pxt.perf.measureStart=()=>{}),pxt.perf.measureEnd||(pxt.perf.measureEnd=()=>{}),function(e){let t;e.U=pxtc.Util,e.Util=pxtc.Util;let n,i,r,s={};function o(n,i){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(s[n]=i,e.U.jsonCopyFrom(e.appTarget.compile.switches,s),e.U.jsonCopyFrom(t.compile.switches,s))}function a(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,s),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex");const i=e.appTarget.appTheme;i&&Object.keys(i).filter((e=>/(logo|hero)$/i.test(e)&&/^@cdnUrl@/.test(i[e]))).forEach((t=>i[t]=e.BrowserUtils.patchCdn(i[t])));const r=e.appTarget.simulator;if(r&&r.boardDefinition&&r.boardDefinition.visual){let t=r.boardDefinition.visual;t.image&&(t.image=e.BrowserUtils.patchCdn(t.image),t.outlineImage&&(t.outlineImage=e.BrowserUtils.patchCdn(t.outlineImage)))}if(Object.keys(e.appTarget.bundledpkgs).forEach((t=>{const n=e.appTarget.bundledpkgs[t],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)})),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach((i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function l(n=!1){e.perf.measureStart("reloadAppTargetVariant");const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}a(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function c(){return{relprefix:"/--",workerjs:"/worker.js",monacoworkerjs:"/monacoworker.js",gifworkerjs:"/gifjs/gif.worker.js",serviceworkerjs:"/serviceworker.js",typeScriptWorkerJs:"/tsworker.js",pxtVersion:"local",pxtRelId:"localRelId",pxtCdnUrl:"/cdn/",commitCdnUrl:"/cdn/",blobCdnUrl:"/blb/",cdnUrl:"/cdn/",targetUrl:"",targetVersion:"local",targetRelId:"",targetId:e.appTarget?e.appTarget.id:"",simUrl:"/sim/simulator.html",simserviceworkerUrl:"/simulatorserviceworker.js",simworkerconfigUrl:"/sim/workerConfig.js",partsUrl:"/sim/siminstructions.html"}}function u(){return r||(r=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),r}function d(t=null){return t||(t=e.appTarget.compile),t.nativeType==ts.pxtc.NATIVE_TYPE_VM?t.useESP?t.useUF2?ts.pxtc.BINARY_UF2:ts.pxtc.BINARY_ESP:ts.pxtc.BINARY_PXT64:t.useUF2&&!t.switches.rawELF?ts.pxtc.BINARY_UF2:t.useELF?ts.pxtc.BINARY_ELF:ts.pxtc.BINARY_HEX}e.setAppTarget=function(n){e.appTarget=n||{},a(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),r=t.pyQName,s=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:r,pyName:r?r.slice(r.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map((e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters}))):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},o=s.attributes;o.paramDefl||(o.paramDefl={}),o.callingConvention||(o.callingConvention=0),o.paramHelp||(o.paramHelp={}),o.jsDoc||(o.jsDoc=""),o._name=s.name.replace(/@.*/,"")}}n=e},e.getBundledApiInfo=function(){return n},e.savedAppTheme=function(){return t?t.appTheme:void 0},e.setCompileSwitch=o,e.setCompileSwitches=function(e){if(e)for(let t of e.split(/[\s,;:]+/))t&&("-"==t[0]?o(t.slice(1),!1):o(t,!0))},e.bundledSvg=function(t){if(!t)return;let n=i&&i[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;i||(i={});const r=e.appTarget.bundledpkgs[t];if(!r)return;if(JSON.parse(r["pxt.json"]).core&&r["board.json"]){const n=JSON.parse(r["board.json"]);if(n&&n.visual&&n.visual.image){let s=n.visual.image;/^pkg:\/\//.test(s)&&(s=r[s.slice(6)]),i[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(s))}`}}return i[t]},e.reloadAppTargetVariant=l,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,l(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some((e=>/^hw---/.test(e)))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter((e=>/^hw---/.test(e))).map((t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME]))).filter((t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw)):[]},e.options={},e.debug="undefined"!=typeof console&&console.debug?t=>{e.options.debug&&console.debug(t)}:()=>{},e.log="undefined"!=typeof console&&console.log?e=>{console.log(e)}:()=>{},e.reportException=function(e,t){if(console&&(console.error(e),t))try{console.log(t)}catch(e){}},e.reportError=function(t,n,i){if(console&&(console.error(`${t}: ${n}`),i))try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=c,e.getOnlineCdnUrl=function(){if(!e.webConfig)return null;let t=/^(https:\/\/[^\/]+)/.exec(e.webConfig.commitCdnUrl);return t?t[1]:null},e.setupWebConfig=function(t){t?e.webConfig=t:e.webConfig||(e.webConfig=c())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=u,e.packagesConfigAsync=function(){return u().then((e=>e?e.packages:void 0))},e.CONFIG_NAME="pxt.json",e.SIMSTATE_JSON=".simstate.json",e.SERIAL_EDITOR_FILE="serial.txt",e.README_FILE="README.md",e.GITIGNORE_FILE=".gitignore",e.ASSETS_FILE="assets.json",e.CLOUD_ID="pxt/",e.BLOCKS_PROJECT_NAME="blocksprj",e.JAVASCRIPT_PROJECT_NAME="tsprj",e.PYTHON_PROJECT_NAME="pyprj",e.MAIN_BLOCKS="main.blocks",e.MAIN_TS="main.ts",e.MAIN_PY="main.py",e.DEFAULT_GROUP_NAME="other",e.TILEMAP_CODE="tilemap.g.ts",e.TILEMAP_JRES="tilemap.g.jres",e.IMAGES_CODE="images.g.ts",e.IMAGES_JRES="images.g.jres",e.TUTORIAL_CODE_START="_onCodeStart.ts",e.TUTORIAL_CODE_STOP="_onCodeStop.ts",e.TUTORIAL_INFO_FILE="tutorial-info-cache.json",e.TUTORIAL_CUSTOM_TS="tutorial.custom.ts",e.BREAKPOINT_TABLET=991,e.outputName=d,e.isOutputText=function(e=null){return d(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let i;function r(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.lf("while %1"),appendField:e.Util.lf("{id:while}do")}},pxt_controls_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},controls_simple_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},pxt_controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},math_op2:{name:e.Util.lf("minimum or maximum of 2 numbers"),tooltip:{min:e.Util.lf("smaller value of 2 numbers"),max:e.Util.lf("larger value of 2 numbers")},url:"/blocks/math",operators:{op:["min","max"]},category:"math"},math_op3:{name:e.Util.lf("absolute number"),tooltip:e.Util.lf("absolute value of a number"),url:"/reference/math",category:"math",block:{message0:e.Util.lf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.appTarget&&e.appTarget.compile?e.Util.lf("a decimal number"):e.Util.lf("an integer number")},math_integer:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math"},math_arithmetic:{name:e.Util.lf("arithmetic operation"),url:"/blocks/math",tooltip:{ADD:e.Util.lf("Return the sum of the two numbers."),MINUS:e.Util.lf("Return the difference of the two numbers."),MULTIPLY:e.Util.lf("Return the product of the two numbers."),DIVIDE:e.Util.lf("Return the quotient of the two numbers."),POWER:e.Util.lf("Return the first number raised to the power of the second number.")},operators:{OP:["ADD","MINUS","MULTIPLY","DIVIDE","POWER"]},category:"math",block:{MATH_ADDITION_SYMBOL:e.Util.lf("{id:op}+"),MATH_SUBTRACTION_SYMBOL:e.Util.lf("{id:op}-"),MATH_MULTIPLICATION_SYMBOL:e.Util.lf("{id:op}×"),MATH_DIVISION_SYMBOL:e.Util.lf("{id:op}÷"),MATH_POWER_SYMBOL:e.Util.lf("{id:op}**")}},math_modulo:{name:e.Util.lf("division remainder"),tooltip:e.Util.lf("Return the remainder from dividing the two numbers."),url:"/blocks/math",category:"math",block:{MATH_MODULO_TITLE:e.Util.lf("remainder of %1 ÷ %2")}},math_js_op:{name:e.Util.lf("math function"),tooltip:{sqrt:e.Util.lf("Returns the square root of the argument"),sin:e.Util.lf("Returns the sine of the argument"),cos:e.Util.lf("Returns the cosine of the argument"),tan:e.Util.lf("Returns the tangent of the argument"),atan2:e.Util.lf("Returns the arctangent of the quotient of the two arguments"),idiv:e.Util.lf("Returns the integer portion of the division operation on the two arguments"),imul:e.Util.lf("Returns the integer portion of the multiplication operation on the two arguments")},url:"/blocks/math",operators:{OP:["sqrt","sin","cos","tan","atan2","idiv","imul"]},category:"math",block:{sqrt:e.Util.lf("{id:op}square root"),sin:e.Util.lf("{id:op}sin"),cos:e.Util.lf("{id:op}cos"),tan:e.Util.lf("{id:op}tan"),atan2:e.Util.lf("{id:op}atan2"),idiv:e.Util.lf("{id:op}integer ÷"),imul:e.Util.lf("{id:op}integer ×")}},math_js_round:{name:e.Util.lf("rounding functions"),tooltip:{round:e.Util.lf("Increases the argument to the next higher whole number if its fractional part is more than one half"),ceil:e.Util.lf("Increases the argument to the next higher whole number"),floor:e.Util.lf("Decreases the argument to the next lower whole number"),trunc:e.Util.lf("Removes the fractional part of the argument")},url:"/blocks/math",operators:{OP:["round","ceil","floor","trunc"]},category:"math",block:{round:e.Util.lf("{id:op}round"),ceil:e.Util.lf("{id:op}ceiling"),floor:e.Util.lf("{id:op}floor"),trunc:e.Util.lf("{id:op}truncate")}},variables_change:{name:e.Util.lf("update the value of a number variable"),tooltip:e.Util.lf("Changes the value of the variable by this amount"),url:"/blocks/variables/change",category:"variables",block:{message0:e.Util.lf("change %1 by %2")}},controls_repeat_ext:{name:e.Util.lf("a loop that repeats and increments an index"),tooltip:e.Util.lf("Do some statements several times."),url:"/blocks/loops/repeat",category:"loops",block:{CONTROLS_REPEAT_TITLE:e.Util.lf("repeat %1 times"),CONTROLS_REPEAT_INPUT_DO:e.Util.lf("{id:repeat}do")}},variables_get:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_get_reporter:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_set:{name:e.Util.lf("assign the value of a variable"),tooltip:e.Util.lf("Sets this variable to be equal to the input."),url:"/blocks/variables/assign",category:"variables",block:{VARIABLES_SET:e.Util.lf("set %1 to %2")}},controls_if:{name:e.Util.lf("a conditional statement"),tooltip:{CONTROLS_IF_TOOLTIP_1:e.Util.lf("If a value is true, then do some statements."),CONTROLS_IF_TOOLTIP_2:e.Util.lf("If a value is true, then do the first block of statements. Otherwise, do the second block of statements."),CONTROLS_IF_TOOLTIP_3:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."),CONTROLS_IF_TOOLTIP_4:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.")},tooltipSearch:"CONTROLS_IF_TOOLTIP_2",url:"/blocks/logic/if",category:"logic",block:{CONTROLS_IF_MSG_IF:e.Util.lf("{id:logic}if"),CONTROLS_IF_MSG_THEN:e.Util.lf("{id:logic}then"),CONTROLS_IF_MSG_ELSE:e.Util.lf("{id:logic}else"),CONTROLS_IF_MSG_ELSEIF:e.Util.lf("{id:logic}else if")}},lists_create_with:{name:e.Util.lf("create an array"),tooltip:e.Util.lf("Creates a new array."),url:"/reference/arrays/create",category:"arrays",blockTextSearch:"LISTS_CREATE_WITH_INPUT_WITH",block:{LISTS_CREATE_EMPTY_TITLE:e.Util.lf("empty array"),LISTS_CREATE_WITH_INPUT_WITH:e.Util.lf("array of"),LISTS_CREATE_WITH_CONTAINER_TITLE_ADD:e.Util.lf("array"),LISTS_CREATE_WITH_ITEM_TITLE:e.Util.lf("value")}},lists_length:{name:e.Util.lf("array length"),tooltip:e.Util.lf("Returns the number of items in an array."),url:"/reference/arrays/length",category:"arrays",block:{LISTS_LENGTH_TITLE:e.Util.lf("length of array %1")}},lists_index_get:{name:e.Util.lf("get a value in an array"),tooltip:e.Util.lf("Returns the value at the given index in an array."),url:"/reference/arrays/get",category:"arrays",block:{message0:e.Util.lf("%1 get value at %2")}},lists_index_set:{name:e.Util.lf("set a value in an array"),tooltip:e.Util.lf("Sets the value at the given index in an array"),url:"/reference/arrays/set",category:"arrays",block:{message0:e.Util.lf("%1 set value at %2 to %3")}},logic_compare:{name:e.Util.lf("comparing two numbers"),tooltip:{LOGIC_COMPARE_TOOLTIP_EQ:e.Util.lf("Return true if both inputs equal each other."),LOGIC_COMPARE_TOOLTIP_NEQ:e.Util.lf("Return true if both inputs are not equal to each other."),LOGIC_COMPARE_TOOLTIP_LT:e.Util.lf("Return true if the first input is smaller than the second input."),LOGIC_COMPARE_TOOLTIP_LTE:e.Util.lf("Return true if the first input is smaller than or equal to the second input."),LOGIC_COMPARE_TOOLTIP_GT:e.Util.lf("Return true if the first input is greater than the second input."),LOGIC_COMPARE_TOOLTIP_GTE:e.Util.lf("Return true if the first input is greater than or equal to the second input.")},url:"/blocks/logic/boolean",category:"logic",block:{search:"= ≠ < ≤ > ≥"}},logic_operation:{name:e.Util.lf("boolean operation"),tooltip:{LOGIC_OPERATION_TOOLTIP_AND:e.Util.lf("Return true if both inputs are true."),LOGIC_OPERATION_TOOLTIP_OR:e.Util.lf("Return true if at least one of the inputs is true.")},url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_OPERATION_AND:e.Util.lf("{id:op}and"),LOGIC_OPERATION_OR:e.Util.lf("{id:op}or")}},logic_negate:{name:e.Util.lf("logical negation"),tooltip:e.Util.lf("Returns true if the input is false. Returns false if the input is true."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_NEGATE_TITLE:e.Util.lf("not %1")}},logic_boolean:{name:e.Util.lf("a `true` or `false` value"),tooltip:e.Util.lf("Returns either true or false."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_BOOLEAN_TRUE:e.Util.lf("{id:boolean}true"),LOGIC_BOOLEAN_FALSE:e.Util.lf("{id:boolean}false")}},text:{name:e.Util.lf("a piece of text"),tooltip:e.Util.lf("A letter, word, or line of text."),url:"types/string",category:"text",block:{search:e.Util.lf("a piece of text")}},text_length:{name:e.Util.lf("number of characters in the string"),tooltip:e.Util.lf("Returns the number of letters (including spaces) in the provided text."),url:"reference/text/length",category:"text",block:{TEXT_LENGTH_TITLE:e.Util.lf("length of %1")}},text_join:{name:e.Util.lf("join items to create text"),tooltip:e.Util.lf("Create a piece of text by joining together any number of items."),url:"reference/text/join",category:"text",block:{TEXT_JOIN_TITLE_CREATEWITH:e.Util.lf("join")}},procedures_defnoreturn:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"types/function/define",category:"functions",block:{PROCEDURES_DEFNORETURN_TITLE:e.Util.lf("function"),PROCEDURE_ALREADY_EXISTS:e.Util.lf("A function named '%1' already exists.")}},procedures_callnoreturn:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"types/function/call",category:"functions",block:{PROCEDURES_CALLNORETURN_TITLE:e.Util.lf("call function")}},function_return:{name:e.Util.lf("return a value from within a function"),tooltip:e.Util.lf("Return a value from within a user-defined function."),url:"types/function/return",category:"functions",block:{message_with_value:e.Util.lf("return %1"),message_no_value:e.Util.lf("return")}},function_definition:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"types/function/define",category:"functions",block:{FUNCTIONS_EDIT_OPTION:e.Util.lf("Edit Function")}},function_call:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"types/function/call",category:"functions",block:{FUNCTIONS_CALL_TITLE:e.Util.lf("call"),FUNCTIONS_GO_TO_DEFINITION_OPTION:e.Util.lf("Go to Definition")}},function_call_output:{name:e.Util.lf("call the function with a return value"),tooltip:e.Util.lf("Call the user-defined function with a return value."),url:"types/function/call",category:"functions",block:{}}},i[pxtc.ON_START_TYPE]={name:e.Util.lf("on start event"),tooltip:e.Util.lf("Run code when the program starts"),url:"/blocks/on-start",category:"loops",block:{message0:e.Util.lf("on start %1 %2")}},i[pxtc.PAUSE_UNTIL_TYPE]={name:e.Util.lf("pause until"),tooltip:e.Util.lf("Pause execution of code until the given boolean expression is true"),url:"/blocks/pause-until",category:"loops",block:{message0:e.Util.lf("pause until %1")}},i[pxtc.TS_BREAK_TYPE]={name:e.Util.lf("break"),tooltip:e.Util.lf("Break out of the current loop or switch"),url:"/blocks/loops/break",category:"loops",block:{message0:e.Util.lf("break")}},i[pxtc.TS_CONTINUE_TYPE]={name:e.Util.lf("continue"),tooltip:e.Util.lf("Skip current iteration and continues with the next iteration in the loop"),url:"/blocks/loops/continue",category:"loops",block:{message0:e.Util.lf("continue")}},e.Util.isTranslationMode()){const t=Blockly.Msg;e.Util.values(i).filter((e=>e.block)).forEach((n=>{const i=Object.keys(n.block);n.translationIds=e.Util.values(n.block),i.forEach((i=>e.crowdin.inContextLoadAsync(n.block[i]).then((e=>{n.block[i]=e,/^[A-Z_]+$/.test(i)&&(t[i]=e)}))))}))}}t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan"],binary:["atan2"],infix:["idiv","imul"]},t.ROUNDING_FUNCTIONS=["round","ceil","floor","trunc"],t.builtinFunctionInfo={"Math.abs":{blockId:"math_op3",params:["x"]},"Math.min":{blockId:"math_op2",params:["x","y"]},"Math.max":{blockId:"math_op2",params:["x","y"]}},t.normalizeBlock=function(t,n=e.log){if(!t)return t;let i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){const i={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},r=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,s=!!e.attributes._def,o=s?e.attributes._def.parameters.slice(0):void 0,a=s?o.length:e.parameters?e.parameters.length:0,l=t.builtinFunctionInfo[e.qName];s&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const c={},u=o?o.filter((e=>!e.ref||(c[e.name]=e,!1))):[];if(r&&s&&o.length){const t=c.this||o[0],r=t.name;let s;(!t.shadowBlockId||"variables_get"===t.shadowBlockId)&&(s=t.varName||e.attributes.paramDefl[r]||e.attributes.paramDefl.this),i.thisParameter={actualName:n,definitionName:r,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:s,fieldEditor:d(r,n),fieldOptions:h(r,n),shadowOptions:p(r,n)}}if(e.parameters){let t=r&&!c.this?1:0;e.parameters.forEach(((e,n)=>{let r;if(c[e.name]?r=c[e.name]:t<u.length&&(r=u[t],++t),r||!s){let n;e.options&&e.options.min&&e.options.max&&(n={min:e.options.min.value,max:e.options.max.value});const s=r?r.name:l?l.params[t++]:e.name,c=r&&("variables_get"===r.shadowBlockId||"lists_create_with"==r.shadowBlockId);i.parameters.push({actualName:e.name,type:e.type,defaultValue:c&&r.varName||e.default,definitionName:s,shadowBlockId:r&&r.shadowBlockId,isOptional:!!o&&o.indexOf(r)>=a,fieldEditor:d(s,e.name),fieldOptions:h(s,e.name),shadowOptions:p(s,e.name),range:n})}e.handlerParameters&&e.handlerParameters.forEach((e=>{i.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!o&&o.some((t=>t.ref&&t.name===e.name))})}))}))}return i.parameters.forEach((e=>{i.actualNameToParam[e.actualName]=e,i.definitionNameToParam[e.definitionName]=e})),i;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function h(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function p(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some((e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)}))},t.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),t},t.defaultIconForArgType=function(e=""){switch(e){case"number":return"calculator";case"string":return"text width";case"boolean":return"random";case"Array":return"list";default:return"align justify"}},t.parseFields=function(e){return e.split("|").map(((e,t)=>{let n=/([^%]*)\s*%([a-zA-Z0-9_]+)/.exec(e);if(!n)return{n:e,ni:t};let i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}}))},t.blockDefinitions=function(){return i||r(),i},t.getBlockDefinition=function(e){return i||r(),i[e]}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function i(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function r(){return n()&&/mobi/i.test(navigator.userAgent)}function s(){return n()&&/Mac/i.test(navigator.platform)}function o(){return!!navigator&&/Linux/i.test(navigator.platform)}function a(){return n()&&/arm/i.test(navigator.platform)}function l(){return n()&&/Edge/i.test(navigator.userAgent)}function c(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!l()&&!c()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!l()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function h(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function p(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function f(){return n()&&/Midori/i.test(navigator.userAgent)}function m(){return n()&&/Epiphany/i.test(navigator.userAgent)}function g(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&(t||!/nolocalhost=1/.test(window.location.href))&&!(null===(n=null==e?void 0:e.webConfig)||void 0===n?void 0:n.isStatic)}catch(e){return!1}}function x(){return"undefined"!=typeof window&&!!window.PointerEvent}function k(){return i()?"windows":s()?"mac":o()&&a()?"rpi":o()?"linux":"unknown"}function A(){return l()?"edge":m()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function T(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=r,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=s,t.isLinux=o,t.isARM=a,t.isUwpEdge=function(){return"undefined"!=typeof window&&!!window.Windows},t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>!1,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)Map=1/.test(window.location.href)}catch(e){return!1}},t.isTabletSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)<e.BREAKPOINT_TABLET},t.isComputerSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)>=e.BREAKPOINT_TABLET},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=x,t.hasSaveAs=function(){return l()||c()||h()},t.os=k,t.browser=A,t.browserVersion=T;let E=!1;function C(){return r()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function S(t,n,i){const s=C(),o=T(),a=parseInt(o||"0");if(s)i?i.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(a<10||0==o.indexOf("10.0")||r())){let n=document.getElementById("downloader");n||(e.debug("injecting downloader iframe"),n=document.createElement("iframe"),n.id="downloader",n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.zIndex="-1",n.style.width="1px",n.style.height="1px",document.body.appendChild(n)),n.src=t}else if(/^data:/i.test(t)&&(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())){let i=atob(t.split(",")[1]),r=e.Util.stringToUint8Array(i),s=new Blob([r],{type:"img/png"});window.navigator.msSaveOrOpenBlob(s,n)}else{let e=window.document.createElement("a");"string"==typeof e.download?(e.href=t,e.download=n,document.body.appendChild(e),e.click(),document.body.removeChild(e)):document.location.href=t}}function I(t,n){let i="data";r()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(i=e.appTarget.appTheme.mobileSafariDownloadProtocol);const s=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);s&&(i=s[1]);return i+":"+n+";base64,"+t}function P(t,n,i={}){var r;e.debug("trigger download");const{contentType:s="application/octet-stream",userContextWindow:o,onError:a,maintainObjectURL:l}=i,c=null===(r=window.URL)||void 0===r?void 0:r.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(c&&!u){const i=c(new Blob([e.Util.stringToUint8Array(atob(t))],{type:s}));S(i,n,o),l?d=i:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=I(t,n),S(d,n,o)}catch(t){a&&a(t),e.debug("saving failed")}return d}function U(e){const t=document.createElement("img");return new Promise(((n,i)=>{t.onload=()=>n(t),t.onerror=()=>n(void 0),t.crossOrigin="anonymous",t.src=e}))}t.isBrowserSupported=function(){var t,n;if(!navigator)return!0;if(/bot|crawler|spider|crawling/i.test(navigator.userAgent))return!0;const i=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==i?void 0:i.some((e=>e.id==A())))return!1;const r=T(),s=parseInt(r||"0"),c=u()&&s>=38,g=h()&&s>=31,b=l(),y=d()&&s>=9,v=p()&&u()&&s>=21;let w=c||g||b||y||v;const x=f()||o()&&a()&&m();return w=w&&!x,w=w||/anybrowser=(true|1)/.test(window.location.href),E||(e.log(`Browser: ${A()} ${r} on ${k()}`),w||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),E=!0),w},t.devicePixelRatio=function(){if("undefined"==typeof window||!window.screen)return 1;const e=window.screen.systemXDPI,t=window.screen.logicalXDPI;return void 0!==e&&void 0!==t&&e>t?e/t:window&&void 0!==window.devicePixelRatio?window.devicePixelRatio:1},t.browserDownloadBinText=function(e,t,n){return P(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return P(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=C,t.isBrowserDownloadWithinUserContext=function(){const e=T(),t=parseInt(e||"0");return r()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=S,t.browserDownloadUInt8Array=function(t,n,i){return P(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=I,t.browserDownloadBase64=P,t.loadImageAsync=U,t.loadCanvasAsync=function(e){return U(e).then((e=>{const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}))},t.scaleImageData=function(e,t){const n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t;const i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),i.getImageData(0,0,e.width*t,e.height*t)},t.imageDataToPNG=function(e,t=1){if(!e)return;const n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t;const i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),n.toDataURL("image/png")};const _=1e6;function N(t){if(/^https?:\/\//i.test(t))return t;const n=(window.MonacoPaths||{})[t];return n||(e.U.startsWith(t,e.webConfig.commitCdnUrl)?t:e.webConfig.commitCdnUrl+t)}t.encodeToPngAsync=function(t,n){const{width:i,height:r,pixelDensity:s=4,maxSize:o=_,text:a}=n||{};return new Promise(((n,l)=>{const c=new Image;c.onload=function(){const t=document.createElement("canvas"),l=t.getContext("2d");t.width=(i||c.width)*s,t.height=(r||c.height)*s,a&&(l.fillStyle="#fff",l.fillRect(0,0,t.width,t.height)),l.drawImage(c,0,0,i,r,0,0,t.width,t.height);let u=t.toDataURL("image/png");for(;u.length>o;)t.width=t.width/2>>0,t.height=t.height/2>>0,e.debug(`screenshot size ${u.length}b, shrinking to ${t.width}x${t.height}`),l.drawImage(c,0,0,i,r,0,0,t.width,t.height),u=t.toDataURL("image/png");if(a){e.lzmaCompressAsync(a).then((i=>{const r=e.Util.encodeBlobAsync(t,i);n(r.toDataURL("image/png"))}))}else n(u)},c.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},c.src=t}))},t.resolveCdnUrl=N,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const i="style-"+t;if(document.getElementById(i))return Promise.resolve();const r=N(t),s=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==r))[0];return s?(s.id||(s.id=i),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=r,n.rel="stylesheet",n.type="text/css",n.id=i,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let O,D,R,M={};function L(e,t){if(!e)return t;if(!t)return e;return(e.indexOf("/")==e.length-1?e.substring(0,e.length-1):e)+"/"+(0==t.indexOf("/")?t.substring(1):t)}function B(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=N(t);let i=M[n];return i||(i=M[n]=new Promise(((t,i)=>{e.debug(`script: loading ${n}`);const r=document.createElement("script");r.type="text/javascript",r.addEventListener("load",(()=>t())),r.addEventListener("error",(e=>{delete M[n],i(e)})),r.src=n,r.async=!0,document.body.appendChild(r)}))),i},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&(200==i.status?t(i.responseText):n(i.status))},i.open("GET",e,!0),i.send()}))},t.loadBlocklyAsync=function(){if(!O){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());"undefined"==typeof Blockly&&(t=t.then((()=>e.BrowserUtils.loadScriptAsync("pxtblockly.js")))),t=t.then((()=>{e.debug("blockly: loaded")})),O=t}return O},t.patchCdn=function(t){if(!t)return t;const n=e.getOnlineCdnUrl();return n?t.replace("@cdnUrl@",n):t.replace(/@cdnUrl@\/(blob|commit)\/[a-f0-9]{40}\//,"./")},t.initTheme=function(){const t=e.appTarget.appTheme;if(t&&t.accentColor){let e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode(`.ui.accent { color: ${t.accentColor}; }\n .ui.inverted.menu .accent.active.item, .ui.inverted.accent.menu { background-color: ${t.accentColor}; }`)),document.getElementsByTagName("head")[0].appendChild(e)}if(e.Util.isUserLanguageRtl()){e.debug("rtl layout"),e.BrowserUtils.addClass(document.body,"rtl"),document.body.style.direction="rtl";const t=e.Util.toArray(document.head.getElementsByTagName("link")),n=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0];if(n){const t=n.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),n.setAttribute("href",t))}const i=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(i){const t=i.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),i.setAttribute("href",t),i.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=L,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=L(t,e[n]);return t},t.storageEstimateAsync=B,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){B().then((t=>(e.debug(`storage estimate: ${t.usage/t.quota*100>>0}%, ${t.usage/1e6>>0}/${t.quota/1e6>>0}Mb`),t.quota&&t.usage&&t.quota>1e6&&t.usage/t.quota>.9?(e.log("quota usage exceeded, clearing translations"),e.tickEvent("storage.cleanup"),V()):Promise.resolve()))).catch((t=>{e.reportException(t)}))}),1e4,!1):()=>{},t.stressTranslationsAsync=function t(){let n="...";for(let e=0;e<16;++e)n+=n+Math.random();return console.log(`adding entry ${2*n.length} bytes`),e.U.delay(1).then((()=>H())).then((e=>e.setAsync("foobar",Math.random().toString(),"",null,void 0,n))).then((()=>e.BrowserUtils.storageEstimateAsync())).then((e=>!e.quota||e.usage/e.quota<.8?t():Promise.resolve()))};class F{constructor(){this.translations={}}key(e,t,n){return`${e}|${t}|${n||"master"}`}get(e,t,n){return this.translations[this.key(e,t,n)]}getAsync(e,t,n){return Promise.resolve(this.get(e,t,n))}set(e,t,n,i,r,s,o){this.translations[this.key(e,t,n)]={etag:i,time:r,strings:s,md:o}}setAsync(t,n,i,r,s,o){return this.set(t,n,i,r,e.Util.now(),s),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class ${constructor(e,t,n,i){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler())}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise(((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)}))}openAsync(){return new Promise(((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)}))}getAsync(e,t){return new Promise(((n,i)=>{const r=this.getObjectStore(e).get(t);r.onsuccess=()=>n(r.result),r.onerror=()=>this.errorHandler(r.error,"get",i)}))}getAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e).openCursor(),r=[];i.onsuccess=()=>{i.result?(r.push(i.result.value),i.result.continue()):t(r)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,i)=>{const r=this.getObjectStore(e,"readwrite");let s;s=void 0!==t.id&&null!==t.id?r.put(t):r.add(t),s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"set",i)}))}deleteAsync(e,t){return new Promise(((n,i)=>{const r=this.getObjectStore(e,"readwrite").delete(t);r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"delete",i)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)}))}}t.IDBWrapper=$;class j{constructor(e){this.db=e,this.mem=new F}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new $(j.dbName(),2,((e,t)=>{t.result.createObjectStore(j.TABLE,{keyPath:j.KEYPATH})}),(()=>{V().catch((e=>{}))}));return e.openAsync().then((()=>new j(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),$.deleteDatabaseAsync(j.dbName()).then((()=>e())))))}getAsync(e,t,n){e=(e||"en-US").toLowerCase();const i=this.mem.key(e,t,n),r=this.mem.get(e,t,n);return r?Promise.resolve(r):this.db.getAsync(j.TABLE,i).then((i=>i?(this.mem.set(e,t,n,i.etag,i.time,i.strings),Promise.resolve(i)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,i,r,s,o,a){n=(n||"en-US").toLowerCase();const l=this.mem.key(n,i,r);let c=e.Util.now();this.mem.set(n,i,r,s,c,o,a),o&&Object.keys(o).filter((e=>!o[e])).forEach((e=>delete o[e]));const u={id:l,etag:s,time:c,strings:o,md:a};return this.db.setAsync(j.TABLE,u).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(j.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function H(){return e.Util.isNodeJS?Promise.resolve(new F):(D||(D=j.createAsync().catch((()=>new F))),D)}function V(){function t(){const t=j.dbName();return $.deleteDatabaseAsync(t).then((()=>{D=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),D=void 0}))}return D?D.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function G(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function z(e,t){return`${e}|${t||"master"}`}j.TABLE="files",j.KEYPATH="id",t.translationDbAsync=H,t.clearTranslationDbAsync=V,t.getTutorialCodeHash=G;class W{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(W.dbName(),2,((e,t)=>{t.result.createObjectStore(W.TABLE,{keyPath:W.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName())}));return t.openAsync().then((()=>new W(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName()).then((()=>t())))))}getAsync(t,n,i){const r=z(t,i),s=G(n);return this.db.getAsync(W.TABLE,r).then((t=>{if(t&&t.hash==s&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(W.TABLE,r)}))}setAsync(t,n,i,r){e.perf.measureStart("tutorial info db setAsync");z(t,r);const s=G(i);return this.setWithHashAsync(t,n,s)}setWithHashAsync(t,n,i,r){e.perf.measureStart("tutorial info db setAsync");const s=z(t,r),o={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{o[t]=n[e][t]}))}));const a={id:s,time:e.Util.now(),hash:i,snippets:n,blocks:o};return this.db.setAsync(W.TABLE,a).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(W.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function q(e){return e.split(/\s+/).filter((e=>!!e))}function J(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}W.TABLE="info",W.KEYPATH="id",t.tutorialInfoDbAsync=function(){return R||(R=W.createAsync()),R},t.clearTutorialInfoDbAsync=function(){function t(){const t=W.dbName();return $.deleteDatabaseAsync(t).then((()=>{R=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),R=void 0}))}return R?R.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=x()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:g()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,r){try{const e=window.screenLeft?window.screenLeft:window.screenX,s=window.screenTop?window.screenTop:window.screenY,o=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,l=o/2-i/2+e,c=a/2-r/2+s,u=window.open(t,n,"width="+i+", height="+r+", top="+c+", left="+l);return u.focus&&u.focus(),u}catch(n){return e.tickEvent("pxt.popupError",{url:t,msg:n.message}),null}},t.containsClass=function(e,t){return q(t).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},t.addClass=function(e,t){q(t).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},t.removeClass=function(e,t){q(t).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},t.getCookieLang=J,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==J()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){e.cloudStatus={none:{value:"none"},synced:{value:"synced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved"),longStatus:lf("Saved to cloud"),indicator:""},justSynced:{value:"justSynced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved!"),longStatus:lf("Saved to cloud!"),indicator:""},offline:{value:"offline",icon:"cloud-error-b",tooltip:lf("Unable to connect to cloud"),shortStatus:lf("offline"),longStatus:lf("Offline"),indicator:lf("offline")},syncing:{value:"syncing",icon:"cloud-saving-b",tooltip:lf("Saving project to cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:lf("syncing...")},conflict:{value:"conflict",icon:"cloud-error-b",tooltip:lf("Project was edited in two places and the changes conflict"),shortStatus:lf("conflict!"),longStatus:lf("Project has a conflict!"),indicator:"!"},localEdits:{value:"localEdits",icon:"cloud-saving-b",tooltip:lf("Saving project to the cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.deployCoreAsync=void 0,e.deployFallbackAsync=void 0,e.hasDeployFn=()=>e.deployCoreAsync||e.deployFallbackAsync,e.deployAsync=(t,n)=>(e.deployCoreAsync||e.deployFallbackAsync)(t,n),e.patchCompileResultAsync=void 0,e.browserDownloadAsync=void 0,e.saveOnlyAsync=void 0,e.renderBrowserDownloadInstructions=void 0,e.renderUsbPairDialog=void 0,e.renderIncompatibleHardwareDialog=void 0,e.showUploadInstructionsAsync=void 0,e.saveProjectAsync=void 0,e.electronDeployAsync=void 0,e.webUsbPairDialogAsync=void 0,e.onTutorialCompleted=void 0,e.workspaceLoadedAsync=void 0}(e.commands||(e.commands={}))}(pxt||(pxt={})),function(e){function t(){let t;return t||(t=e.U.isNodeJS?Promise.resolve(require("lzma")):Promise.resolve(window.LZMA),t.then((t=>(t||e.reportError("lzma","failed to load"),t)))),t}e.lzmaDecompressAsync=function(n){return t().then((t=>new Promise(((i,r)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),i(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),i(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((i,r)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),i(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),i(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i=n.lf;const r={"pxt::mkAction":1,"pxt::dumpPerfCounters":1,"pxt::deepSleep":1,"pxt::getConfig":1,"pxtrt::mkMap":1,"pxtrt::mapSet":1,"pxtrt::stclo":1,"pxtrt::mklocRef":1,"pxtrt::stlocRef":1,"pxtrt::ldlocRef":1,"pxtrt::panic":1};function s(e="namespace"){let t="",n="",i=(i,r="")=>{n!=i&&(n&&(t+="}\n"),i&&(t+=r||e+" "+i+" {\n"),n=i)},r=" ";return{setNs:i,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,r).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{r+=" "},decrIndent:()=>{r=r.slice(4)},finish:()=>(i(""),t)}}function o(e){if(!e)return null;e=e.trim();let t=/^\((.*)\)/.exec(e);return t&&(e=t[1]),/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(e)?parseInt(e):null}t.nsWriter=s,t.parseCppInt=o;let a={};class l extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function c(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e[n];t+=37==i||i>127?"%"+i.toString(16):String.fromCharCode(i)}return decodeURIComponent(t)}function u(t){let n="",i=0;for(;i<t.length;i+=2)n=t[i]+t[i+1]+n;return e.Util.assert(i==t.length),n}function d(e){let t=[65,20,14,47,184,47,162,187];e:for(let n=0;n<e.length;n+=16){if(e[n]!=t[0])continue;for(let i=0;i<t.length;++i)if(e[n+i]!=t[i])continue e;let i=e[n+8]|e[n+9]<<8,r=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let s=n+i+r;if(s>e.length)continue;let o=e.slice(n,n+i),a=e.slice(n+i,s);return{meta:c(o),text:a}}return null}function h(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let i;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(i=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(i=d(t)),58==t[0]){i=function(e){if(!e)return;let t,n=0,i=0,r=0,s=0;if(e.split(/\r?\n/).forEach((e=>{let o=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(o)n=parseInt(u(o[1]),16),i=parseInt(u(o[2]),16),r=n+i,t=new Uint8Array(r);else if(r>0){if(o=/^:10....0[0E](.*)(..)$/.exec(e),!o)return;let n=o[1];for(;r>0&&n.length>0;)t[s++]=parseInt(n[0]+n[1],16),n=n.slice(2),r--}})),!t||0!=r||s!=t.length)return;let o=new Uint8Array(n),a=new Uint8Array(i);for(let e=0;e<n;++e)o[e]=t[e];for(let e=0;e<i;++e)a[e]=t[n+e];return{meta:c(o),text:a}}(c(t)||"")}if(!i||!i.meta||!i.text)return n("This .hex file doesn't contain source.");let r=JSON.parse(i.meta);return r?"LZMA"==r.compression?e.lzmaDecompressAsync(i.text).then((t=>{if(!t)return null;let n=t.slice(0,r.headerSize||r.metaSize||0),i=t.slice(n.length);return n&&e.Util.jsonCopyFrom(r,JSON.parse(n)),{meta:r,source:i}})):r.compression?n(`Compression type ${r.compression} not supported.`):Promise.resolve({source:c(i.text)}):n("This .hex file is not valid.")}t.PkgConflictError=l,t.getExtensionInfo=function(t){const c={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",h="",p=[];const f=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of f)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(h&&(h+=", "),h+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(p.push(t),t.addSnapshot(c,[u,".h",".cpp"]));const m=JSON.stringify(c),g=a[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,x="codal"==y.buildEngine||"dockercodal"==y.buildEngine,k="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,A="dockerespidf"==y.buildEngine,T=!(w||x||k||A),E=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":x||k?d="/pxtapp/":A&&(d="/main/");let C="// Configuration defines\n",S="\nPXT_SHIMS_BEGIN\n",I="",P="",U='#include "pxt.h"\n',_="",N=e=>_+=` ${D}(${O}): ${e}\n`,O=0,D="",R=s("namespace"),M=s("declare namespace"),L=s("declare namespace"),B="",F={},$={};const j={true:"1",false:"0",null:"0",NULL:"0"};function H(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of p){if(t.getFiles().indexOf(u)>=0){const n=t.host().readFile(t,u);e.Util.assert(!!n,`dal.d.ts not found in ${t.id}`),n.split(/\r?\n/).forEach((e=>{let t=/^\s*(\w+) = (.*),/.exec(e);t&&(j[t[1]]=t[2])}))}for(const e of t.getFiles())(["Makefile","sdkconfig.defaults","CMakeLists.txt"].indexOf(e)>=0||n.endsWith(e,".mk"))&&(b.generatedFiles["/"+e]=t.host().readFile(t,e))}let V=["0","false","PXT_UTF8"],G={};function z(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(G.PXT_BOX_DEBUG=1),v.utf8&&(G.PXT_UTF8=1),v.switches.profile&&(G.PXT_PROFILE=1),v.switches.gcDebug&&(G.PXT_GC_DEBUG=1),v.switches.numFloat&&(G.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(G.PXT_VM=1);let W=0,q=!1,J="",Y="",K="",X=!1;function Q(){M.setNs(""),M.write(""),M.write(""),(K||Y)&&(M.write(Y),M.write(K),K="",Y="")}function Z(e,t){let s;J="",Y="",K="",X=!1;let a=-1;function l(){let e=J.replace(/Methods$/,"");return e==J?null:e}function c(e){switch(e.replace(/\s+/g,"")){case"void":return"void";case"int32_t":case"int":return"int32";case"uint32_t":case"unsigned":return"uint32";case"TNumber":case"float":case"double":return"number";case"uint16_t":return"uint16";case"int16_t":case"short":return"int16";case"uint8_t":case"byte":return"uint8";case"int8_t":case"sbyte":return"int8";case"bool":return v.shortPointers&&N("use 'boolean' not 'bool' on 8 bit targets"),"boolean";case"StringData*":case"String":case"ImageLiteral_":case"ImageLiteral":return"string";case"Action":return"() => void";case"TValue":return"any";default:return H(e)}}function u(e){switch(e=e.replace(/\s+/g,"")){case"int32_t":case"uint32_t":case"unsigned":case"uint16_t":case"int16_t":case"short":case"uint8_t":case"byte":case"int8_t":case"sbyte":case"int":case"ramint_t":return"I";case"void":return"V";case"float":return"F";case"TNumber":return"N";case"TValue":return"T";case"bool":return"B";case"double":return"D";case"ImageLiteral_":return"T";case"String":return"S";default:return n.lookup(F,e)?"I":"_"+e.replace(/[\*_]+$/,"")}}e=e.replace(/^(\s*#\s*if\s+(\w+)\s*$)([^]*?)(^\s*#\s*(elif|else|endif)\s*$)/gm,((e,t,n,i,r)=>V.indexOf(n)>=0&&!G[n]?t+i.replace(/[^\n]/g,"")+r:e)),O=0,q=!1,W=0,L.setNs(""),M.setNs(""),e.split(/\r?\n/).forEach((e=>{++O;let d=z(e);!function(e){let t=z(e);if(q&&t.indexOf("}")>=0&&(q=!1,L.write("}")),!q)return;let i=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(i){let e=i[1],r=i[3],s="";if(r){r=r.trim();let e=n.lookup(j,r);null!=e&&(s=" // "+r,r=e),W=o(r),null==W&&N("cannot determine value of "+t)}else W++,r=W+"";L.write(` ${H(e)} = ${r},${s}`)}else L.write(e)}(e);let h=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var p,f;if(h&&(p=h[2],f=h[3],q=!0,W=-1,L.write(""),L.write(""),(K||Y)&&(L.write(Y),L.write(K),K="",Y=""),L.write(`declare const enum ${H(p)} ${f}`),F[p]=!0,t||(R.setNs(J),R.write(`enum ${h[2]} : int;`))),function(e){return!(!q&&(/^\s*\/\*\*/.test(e)?(X=!0,Y=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(Y+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(K+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(R.setNs(J),R.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(m)if(J=m[1],l()){Q();let e=l();M.setNs(J,`declare interface ${e} {`)}else(K||Y)&&(Q(),M.setNs(H(J)),L.setNs(H(J)));else{if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!E&&(S+=`PXT_FNPTR(::${m[1]}),\n`,P+=`extern "C" void ${m[1]}();\n`,b.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(b.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!K||!m){if(m=/^\s*extern const (\w+) (\w+);/.exec(e),K&&m){let e={name:J+"::"+m[2],argsFmt:[],value:null};return b.functions.push(e),E||(S+="PXT_FNPTR(&::"+e.name+"),\n"),void(K="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),K&&m){let e=pxtc.parseCommentString(K);e.indexedInstanceNS&&(s=e,M.setNs(e.indexedInstanceNS),a=0);let t=m[1],n=m[2];if(s)return K=K.trim(),K+=` fixedInstance shim=${s.indexedInstanceShim}(${a++})`,M.write(""),M.write(Y),M.write(K),M.write(`const ${n}: ${c(t)};`),Y="",void(K="")}return K&&e.trim()?(N("declaration not understood: "+e),K="",void(Y="")):void 0}{s=null;let e=pxtc.parseCommentString(K);J||N("missing namespace declaration");let a=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],h=m[4];K=K.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(a)],f=[],g=h.split(/,/).filter((e=>!!e)).map((t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),r="",s="";if(i&&(r=i[2],s="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return N("invalid argument: "+t),{name:"???",type:"int"};let a=i[2];e.paramDefl[a]&&(r=e.paramDefl[a],s="?");let l=r?n.lookup(j,r):null;return null!=l&&(r=l),r&&(null==o(r)&&N("Invalid default value (non-integer): "+r),K+=` ${a}.defl=${r}`),{name:a+s,type:i[1]}}(e,t);return p.push(u(i.type)),f.push(i.type.replace(/ /g,"")),`${i.name}: ${c(i.type)}`})),y={name:J+"::"+d,argsFmt:p,value:null};if(Y)if(M.setNs(H(J)),M.write(""),M.write(Y),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(K)&&(K+=" imageLiteral=1"),K+=` shim=${y.name}`,M.write(K),d=H(d),l()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&N(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(K)?M.write(`${d}: ${c(a)};`):M.write(`${d}(${g.join(", ")}): ${c(a)};`)}else M.write(`function ${d}(${g.join(", ")}): ${c(a)};`);if(Y="",K="",t||(R.setNs(J),R.write(`${a} ${d}(${h});`)),b.functions.push(y),T)S+="(uint32_t)(void*)::"+y.name+",\n";else if(E){if(n.startsWith(y.name,"pxt::op_")||r[y.name]||e.expose||!n.startsWith(y.name,"pxt::")&&!n.startsWith(y.name,"pxtrt::")){const e=function(e,t){if("FiberContext*"==t[0])return"::"+e.name;let n="_wrp_"+e.name.replace(/:/g,"_");if($[e.name])return n;$[e.name]=!0,I+=`\nvoid ${n}(FiberContext *ctx) {\n`;const i=t.length;let r=[],s=!1,o="";for(let n=0;n<i;++n){const a=e.argsFmt[n+1],l=t[n];let c="I"==a?"toInt":"B"==a?"numops::toBool":"";const u=n==i-1?"ctx->r0":`ctx->sp[${i-n-2}]`;let d="";switch(l){case"TValue":case"TNumber":break;case"Action":c="asRefAction";break;case"String":c="convertToString",d="ctx, ",s=!0;break;default:c||(c="as"+l.replace(/\*/g,""))}o+=` ${l} a${n} = (${l}) ${c}(${d}${u});\n`,r.push("a"+n)}s&&(I+=" auto prevSP = ctx->sp;\n"),I+=o,s&&(I+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const a=`::${e.name}(${r.join(", ")})`;return"V"==e.argsFmt[0]?(I+=` ${a};\n`,I+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?I+=` ctx->r0 = fromInt(${a});\n`:"B"==e.argsFmt[0]?I+=` ctx->r0 = fromBool(${a});\n`:I+=` ctx->r0 = (TValue)${a};\n`,s&&(I+=" ctx->sp = prevSP;\n"),i>1&&(I+=` ctx->sp += ${i-1};\n`),I+="}\n",n}(y,f),t=y.argsFmt.length-1;S+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else S+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},ie={};function re(t){const r=t.config.platformio;r&&r.dependencies&&n.jsonCopyFrom(b.platformio.dependencies,r.dependencies),b.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(b.npmDependencies,t.config.npmDependencies);const s=t.config.codal;if(x&&s)for(const t of s.libraries||[]){const r=e.github.parseRepoId(t);r||n.userError(i("codal library {0} doesn't look like github repo",t));const s=e.github.stringifyRepo(r),o=n.lookup(ie,r.project);o?e.github.stringifyRepo(o)!=s&&n.userError(i("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(o),s)):ie[r.project]=r}const o=t.config.yotta;if(o){if(o.dependencies&&n.jsonCopyFrom(b.yotta.dependencies,o.dependencies),o.config){const e=n.jsonFlatten(o.config);for(const r of Object.keys(e)){const s=n.lookup(ne,r),o=e[r];if(!s||s.config.yotta.configIsJustDefaults)ne[r]=t,ee[r]=o;else if(ee[r]===o);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new l(i("conflict on yotta setting {0} between extensions {1} and {2}",r,t.id,s.id));throw e.pkg0=s,e.pkg1=t,e.settingName=r,e}}}if(o.optionalConfig){const e=n.jsonFlatten(o.optionalConfig);for(const t of Object.keys(e)){const n=e[t];te[t]=n}}}}if(T&&v.hasHex){let e=y;n.assert(!!e.yottaCorePackage),n.assert(!!e.githubCorePackage),n.assert(!!e.gittag);let t=e.githubCorePackage+"#"+y.gittag;b.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let r of p){_="",re(r),r==t?(e=!0,M.clear(),L.clear()):n.assert(!e);const s=e=>n.endsWith(e,".h"),o=".cpp",a=r.getFiles().filter(s).concat(r.getFiles().filter((e=>!s(e))));for(let e of a){const t=s(e);if(t||n.endsWith(e,o)){let s=r.config.name+"/"+e;("base"==r.config.name||/^core($|---)/.test(r.config.name))&&t&&(s=e),t&&(U+=`#include "${T?d.slice(1):""}${s}"\n`);let o=r.readFile(e);null==o&&n.userError(i("C++ file {0} is missing in extension {1}.",e,r.config.name)),D=s,Z(o,t),b.extensionFiles[d+s]=o,0==r.level&&(b.onlyPublic=!1),r.verProtocol()&&"pub"!=r.verProtocol()&&"embed"!=r.verProtocol()&&(b.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=r.readFile(e);b.extensionFiles[d+r.config.name+"/"+e.replace(/\.S$/,".s")]=t}}_&&(B+=i("Extension {0}:\n",r.id)+_)}e||(M.clear(),L.clear())}function se(e){return Object.keys(b.extensionFiles).concat(Object.keys(b.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}B&&n.userError(B),n.jsonCopyFrom(te,ee),n.iterMap(te,((e,t)=>{null===t&&delete te[e]})),Object.keys(te).filter((e=>/-/.test(e))).forEach((e=>{const t=te[e];delete te[e],te[e.replace(/-/g,"_")]=t})),!T&&y.yottaConfigCompatibility&&Object.keys(te).forEach((e=>te["YOTTA_CFG_"+e]=te[e])),te.PXT_TARGET=JSON.stringify(e.appTarget.id);const oe=n.jsonUnFlatten(te);if(k){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(A){const e=n.concatArrayLike([se(".c"),se(".cpp"),se(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),b.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(x){let t=y,i=n.clone(t.codalDefinitions)||{},r=t.codalTarget;"string"==typeof r&&(r+=".json");let s={target:r,definitions:i,config:i,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(ie).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==s.libraries.length&&delete s.libraries,n.iterMap(n.jsonFlatten(oe),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),i[e]=t})),b.generatedFiles["/codal.json"]=JSON.stringify(s,null,4)+"\n",e.debug(`codal.json: ${b.generatedFiles["/codal.json"]}`)}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,((t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)})),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=oe;let t="pxt-app";y.yottaBinary&&(t=y.yottaBinary.replace(/-combined/,"").replace(/\.hex$/,""));let n={name:t,version:"0.0.0",description:"Auto-generated. Do not edit.",license:"n/a",dependencies:b.yotta.dependencies,targetDependencies:{},bin:"./source"};b.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${b.generatedFiles["/module.json"]}`)}for(let e of Object.keys(G))C+=`#define ${e} ${G[e]}\n`;if(v.uf2Family&&(C+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),b.generatedFiles[d+"pointers.cpp"]=U+R.finish()+P+I+S+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=C,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),T&&(b.generatedFiles["/config.json"]=JSON.stringify(oe,null,4)+"\n",e.debug(`yotta config.json: ${b.generatedFiles["/config.json"]}`)),b.generatedFiles[d+"main.cpp"]='\n#include "pxt.h"\n#ifdef PXT_MAIN\nPXT_MAIN\n#else\nint main() {\n uBit.init();\n pxt::start();\n release_fiber();\n return 0; // your program will never reach this line.\n}\n#endif\n',b.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${se(n).join(" ")}\n`};t("PXT_C",".c"),t("PXT_CPP",".cpp"),t("PXT_S",".s"),t("PXT_HEADERS",".h"),e+="PXT_SOURCES := $(PXT_C) $(PXT_S) $(PXT_CPP)\n",e+="PXT_OBJS := $(addprefix bld/, $(PXT_C:.c=.o) $(PXT_S:.s=.o) $(PXT_CPP:.cpp=.o))\n",b.generatedFiles["/Makefile.inc"]=e}b.generatedFiles["/functions.json"]=JSON.stringify(b.functions,null,1);let ae=b.extensionFiles;n.jsonCopyFrom(ae,b.generatedFiles);let le={config:y.serviceId,tag:y.gittag,replaceFiles:ae,dependencies:T?b.yotta.dependencies:null},ce=JSON.stringify(le);return b.sha=n.sha256(ce),b.skipCloudBuild=!!y.skipCloudBuild,b.compileData=ts.pxtc.encodeBase64(n.toUTF8(ce)),b.shimsDTS=M.finish(),b.enumsDTS=L.finish(),Object.keys(a).length>10&&(a={}),a[m]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>h(new Uint8Array(e))))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,r={};function s(r){return n.hasOwnProperty(r.sha)||(n[r.sha]=function(n){let r="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then((t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()})).catch((t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve())));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then((e=>e.json))).then((e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)));var n,i}(n).then((s=>s?(e.tickEvent("cppcompile.cachehit"),s):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(r=t+"/compile/"+n.sha,e.U.httpGetTextAsync(r+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,i)=>{let s=0;const o=8e3,a=3e5,l=e.U.now(),c=()=>{if(s++,e.U.now()-l>a)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:s}),n(null),null;let i=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${i} (attempt #${s})`),e.tickEvent("cppcompile.poll",{retry:s}),e.Util.httpGetJsonAsync(i).then((t=>{e.log(`build log ${i.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:s,duration:e.U.now()-l}),t.success?(e.log("fetching "+r+".hex"),n(e.U.httpGetTextAsync(r+".hex"))):(e.log("build failed"),t.mbedresponse&&t.mbedresponse.result&&t.mbedresponse.result.exception&&e.log(t.mbedresponse.result.exception),n(null))}),(t=>(e.log(`waiting ${o/1e3|0}s for C++ build...`),setTimeout(c,o),null)))};c()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(r)),n[r.sha]}function o(t,n,i,r,s=10){return t.cacheStoreAsync(i,r).then((()=>t.cacheGetAsync(n))).then((r=>{let o;try{o=JSON.parse(r||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),o=[]}o=o.filter((e=>e!=i)),o.unshift(i);let a=o.slice(s);return o=o.slice(0,s),e.U.promiseMapAll(a,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(o))))}))}function a(e,t,n){return e.cacheGetAsync(t).then((i=>{let r;try{r=JSON.parse(i||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return r[0]!=n?(r=r.filter((e=>e!=n)),r.unshift(n),e.cacheStoreAsync(t,JSON.stringify(r))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=o,t.recordGetAsync=a,t.getHexInfoAsync=function(t,n,i){if(!n.sha)return Promise.resolve(null);const l=r[n.sha];if(l)return Promise.resolve(l);e.debug("get hex info: "+n.sha);let c="hex-"+n.sha;return t.cacheGetAsync(c).then((i=>{let r;try{r=i?JSON.parse(i):null}catch(e){console.log("invalid cache entry, clearing entry"),r=null}return r&&r.hex?(e.debug("cache hit, size="+i.length),r.hex=function(t){let n=[];for(let i=0;i<t.length;i++){let r=/^([@!])(....)$/.exec(t[i]);if(!r){n.push(t[i]);continue}let s=parseInt(r[2],16),o=t[++i],a="";if("@"==r[1]){a="";let e=parseInt(o,16);for(;e-- >0;)a+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else a=ts.pxtc.decodeBase64(o);e.Util.assert(a.length>0),e.Util.assert(a.length%16==0);for(let e=0;e<a.length;){let t=[16,s>>8&255,255&s,0];s+=16;for(let n=0;n<16;++n)t.push(a.charCodeAt(e++));let i=0;for(let e=0;e<t.length;++e)i+=t[e];t.push(255&-i);let r=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(r+="0"),r+=n.toString(16)}n.push(r.toUpperCase())}}return n}(r.hex),a(t,"hex-keys",c).then((()=>r))):s(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let i=0;i<e.length;i+=n){let r=-1,s="";n=0;let o=!1;for(;n<500;){let a=/^:10(....)00(.{32})(..)$/.exec(e[i+n]);if(!a)break;let l=a[2],c=/^0+$/.test(l),u=parseInt(a[1],16);if(-1==r)o=c,t.push((o?"@":"!")+a[1]),r=u-16;else{if(c!=o)break;if(r+16!=u)break}o||(s+=l),r=u,n++}if(0==n)t.push(e[i]),n=1;else if(o)t.push(n.toString(16));else{let e="";for(let t=0;t<s.length;t+=2)e+=String.fromCharCode(parseInt(s.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let i=JSON.stringify(e);return e.hex=n,o(t,"hex-keys",c,i).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(r).length>20&&(r={}),r[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){function n(n,i,r={},s=null,o=null){if(t.testMode||n==t.TEST_KEY){const e={success:!0};return Promise.resolve({statusCode:200,headers:{},text:JSON.stringify(e),json:e})}return e.Util.multipartPostAsync(i,r,s,o)}function i(n,i,r,s,o){e.Util.assert(!!i&&!!r&&!!s);const a="https://api.crowdin.com/api/project/"+i+"/";return o=o||{},t.testMode?delete o.key:o.key=r,n&&(o.branch=n),a+s+"?"+Object.keys(o).map((e=>`${e}=${encodeURIComponent(o[e])}`)).join("&")}function r(e){let t=0;return function(){if(t++>10)throw new Error("Too many API calls for "+e)}}function s(t,a,l,c,u){return c=o(c),e.debug(`create directory ${t||""}/${c}`),u||(u=r(c)),n(l,i(t,a,l,"add-directory"),{json:"true",name:c}).then((n=>{if(e.debug(`crowdin resp: ${n.statusCode}`),200==n.statusCode||400==n.statusCode)return Promise.resolve();if(500==n.statusCode&&n.text){if(50===JSON.parse(n.text).error.code)return e.log("directory already exists"),Promise.resolve()}const i=n.json||JSON.parse(n.text)||{error:{}};if(404==n.statusCode&&17==i.error.code){e.log(`parent directory missing for ${c}`);const n=c.replace(/\/[^\/]+$/,"");if(n!=c)return s(t,a,l,n,u).then((()=>s(t,a,l,c,u)))}throw new Error(`cannot create directory ${t||""}/${c}: ${n.statusCode} ${JSON.stringify(i)}`)}))}function o(e){return e.replace(/\\/g,"/")}function a(e,t,n,i){const r=t.name,s=n?n+"/"+r:r;switch(t.fullName=s,t.branch=i||"",t.node_type){case"file":e.push(t);break;case"directory":(t.files||[]).forEach((t=>a(e,t,s,i)));break;case"branch":(t.files||[]).forEach((i=>a(e,i,n,t.name)))}}function l(t,n){const i=e.appTarget.versions.pxtCrowdinBranch||"",r=e.appTarget.versions.targetCrowdinBranch||"";let s=[];if(t.forEach((e=>a(s,e,""))),s=s.filter((e=>e.fullName.indexOf("/")<0?e.branch==i:e.branch==r)),n&&(s=s.filter((e=>0==e.fullName.indexOf(n)))),"core"!=e.appTarget.id){const t=e.appTarget.id+"/";s=s.filter((e=>e.fullName.indexOf("/")<0||e.fullName.substr(0,t.length)==t||e.fullName.indexOf("common-docs")>=0))}return s}function c(t,n){const r=i("",t,n,"info",{json:"true"});return e.Util.httpGetTextAsync(r).then((e=>JSON.parse(e)))}t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.TEST_KEY="!!!testmode!!!",t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.downloadTranslationsAsync=function(t,n,r,s,a={}){const l=i(t,n,r,"info",{json:"true"}),c={};return s=o(s),e.Util.httpGetTextAsync(l).then((o=>{const l=JSON.parse(o);if(!l)throw new Error("info failed");let u=l.languages.filter((e=>"en"!=e.code));e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.availableLocales&&(u=u.filter((t=>e.appTarget.appTheme.availableLocales.indexOf(t.code)>-1))),e.log("languages: "+u.map((e=>e.code)).join(", "));const d=()=>{const o=u.pop();if(!o)return Promise.resolve();const l=i(t,n,r,"export-file",{file:s,language:o.code,export_translated_only:a.translatedOnly?"1":"0",export_approved_only:a.validatedOnly?"1":"0"});return e.log(`downloading ${o.name} - ${o.code} (${u.length} more)`),e.Util.httpGetTextAsync(l).then((t=>{try{const e=JSON.parse(t);e&&(c[o.code]=e)}catch(t){e.log(l+" "+t)}return d()})).then((()=>e.Util.delay(1e3)))};return d()})).then((()=>c))},t.createDirectoryAsync=s,t.uploadTranslationAsync=function t(a,l,c,u,d){e.Util.assert(!!l),e.Util.assert(!!c);const h=r(u=o(u));function p(){return f("update-file",{update_option:"update_as_unapproved"})}function f(r,o){return o.type="auto",o.json="",o.escape_quotes="0",h(),n(c,i(a,l,c,r),o,u,d).then((n=>function(n){const i=n.statusCode,r=e.Util.jsonTryParse(n.text)||{};if(e.debug(`upload result: ${i}`),404==i&&r.error&&8==r.error.code)return e.log(`create new translation file: ${u}`),f("add-file",{});if(404==i&&r.error&&17==r.error.code)return s(a,l,c,u.replace(/\/[^\/]+$/,""),h).then((()=>p()));if(!r.success&&r.error&&53==r.error.code)return e.log(`${u} being updated, waiting 5s and retry...`),e.U.delay(5e3).then((()=>t(a,l,c,u,d)));if(200==i||r.success)return Promise.resolve();throw new Error(`Error, upload translation: ${u}, ${i}, ${n.text}`)}(n)))}return p()},t.projectInfoAsync=c,t.listFilesAsync=function(t,n,i){return e.log(`crowdin: listing files under ${i}`),c(t,n).then((t=>{if(!t)throw new Error("info failed");let n=l(t.files,i);return e.debug(`crowdin: found ${n.length} under ${i}`),n.map((e=>({fullName:e.fullName,branch:e.branch||""})))}))},t.languageStatsAsync=function(t,n,r){const s=i("",t,n,"language-status",{language:r,json:"true"});return e.Util.httpGetJsonAsync(s).then((e=>l(e.files)))},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise(((i,r)=>{const s=new MutationObserver((()=>{if(t==n.value)return;const r=e.Util.rlf(n.value);n.remove(),s.disconnect(),i(r)}));s.observe(n,{attributes:!0})}));return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function i(e,t,i={}){i.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const r=n(e),s=n(t),o=Math.min(i.maxDiffSize||1024,r.length+s.length);if(0==o)return[];const a=r.length>65520?Uint32Array:Uint16Array,l={};let c=0;const u=h(r),d=h(s);function h(e){const t=new a(e.length);let n=0;for(let r of e)i.ignoreWhitespace&&(r=r.replace(/\s+$/g,"").replace(/^\s+/g,"")),l.hasOwnProperty(r)?t[n]=l[r]:(++c,t[n]=c,l[r]=c),n++;return t}const p=new a(2*o+1);let f=-1;for(let e=0;e<=o;e++)null!=T(e,p)&&(f=e);if(-1==f)return null;const m=[];let g=null;for(let e=0;e<=f;e++){const t=m.length?m[m.length-1].slice(0):new a(2*f+1);if(m.push(t),g=T(e,t),null!=g)break}const b=[];let y=g;for(let e=m.length-1;e>=0;e--){const t=m[e];let n=0,i=0;y==-e||y!=e&&t[o+y-1]<t[o+y+1]?(i=y+1,n=t[o+i]):(i=y-1,n=t[o+i]+1);let a=n-y;for(let e=t[o+y]-n-1;e>=0;--e)b.push(" "+s[a+e]);i==y-1?b.push("- "+r[n-1]):a>0&&b.push("+ "+s[a-1]),y=i}if(b.reverse(),i.context==1/0||i.full)return b;let v=1,w=1,x=0;const k=[],A=i.context||3;for(;x<b.length;){let e=x;for(;e<b.length&&" "==b[e][0];)e++;if(e==b.length)break;const t=e-A,n=t-x;n>0&&(v+=n,w+=n,x=t);const i=k.length,r=v,s=w;k.push("@@");let o=x,a=0;for(;o<b.length;){if(" "==b[o][0]){if(a++,a>2*A+2){o-=A+2;break}}else a=0;o++}for(;x<o;){k.push(b[x]);switch(b[x][0]){case"-":v++;break;case"+":w++;break;case" ":v++,w++}x++}k[i]=`@@ -${r},${v-r} +${s},${w-s} @@`}return k;function T(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let r=i-n;for(;i<u.length&&r<d.length&&u[i]==d[r];)i++,r++;if(t[o+n]=i,i>=u.length&&r>=d.length)return n}return null}}function r(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function s(e){const t=/^@@ -(\d+),(\d+) \+(\d+),(\d+)/.exec(e);return t&&{oldStart:parseInt(t[1])-1,oldLength:parseInt(t[2]),newStart:parseInt(t[3])-1,newLength:parseInt(t[4])}}t.toLines=n,t.compute=i,t.diff3=function(t,r,s,o,a){const l=g(t),c=g(s);if(!l||!c)return;const u=n(t),d=n(s);let h=0,p=[],f=0,m=0;for(let t=0;t<l.length-1;)if(l[t]==f&&c[t]==m)p.push(u[f]),f++,m++,t++;else{let n=!0,i=!0,r=t;for(;r<l.length&&(l[r]!=f+r-t&&(n=!1),c[r]!=m+r-t&&(i=!1),null==l[r]||null==c[r]);)r++;if(e.U.assert(r<l.length),n)for(;m<c[r];)p.push(d[m++]);else if(i)for(;f<l[r];)p.push(u[f++]);else if(u.slice(f,l[r]).join("\n")==d.slice(m,c[r]).join("\n"))for(;f<l[r];)p.push(u[f++]);else{for(h++,p.push("<<<<<<< "+o);f<l[r];)p.push(u[f++]);for(p.push("=======");m<c[r];)p.push(d[m++]);p.push(">>>>>>> "+a)}t=r,f=l[r],m=c[r]}return{merged:p.join("\n"),numConflicts:h};function g(t){const n=i(r,t,{context:1/0});if(!n)return;const s=[];let o=0,a=0;for(let t of n)"+"==t[0]?o++:"-"==t[0]?(s[a]=null,a++):" "==t[0]?(s[a]=o,o++,a++):e.U.oops();return s.push(o+1),s}},t.removeTrailingSemiColumns=r,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let i=n[0].replace(/\n$/,""),s=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=r(i),s=r(s)),{fileA:i,fileB:s}},t.parseDiffMarker=s,t.render=function(t,n,r={}){const o=i(t,n,r);if(!o)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const a={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let l=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(r.update?"update":"")},d);let p=null;return o.forEach(((t,n)=>{const h=s(t);h?(l=h.oldStart,c=h.newStart):("+"!=t[0]&&l++,"-"!=t[0]&&c++);const f=o[n+1]?o[n+1][0]:"",m=o[n+2]?o[n+2][0]:"",g=t.slice(2);let b=e.dom.el("code",null,g);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=m&&"@"!=m&&""!=m)){const r=function(t,n){const r=i(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!r)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const s=[],o=[];for(let t=0;t<r.length;){let n=t;const i=r[t][0];for(;r[n]&&r[n][0]==i;)n++;const a=r.slice(t,n).map((e=>e.slice(2))).join("");" "==i?(s.push(e.dom.el("code",{class:"ch-common"},a)),o.push(e.dom.el("code",{class:"ch-common"},a))):"-"==i?s.push(e.dom.el("code",{class:"ch-removed"},a)):"+"==i?o.push(e.dom.el("code",{class:"ch-added"},a)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},s),b:e.dom.el("div",{class:"inline-diff"},o)}}(t.slice(2),o[n+1].slice(2));b=r.a,p=r.b}if(u=t[0],r.hideMarkerLine&&"@"==u||r.hideRemoved&&"-"==u)return;const y="@"==u,v=`${a[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!r.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":l}),!r.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":c}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!r.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},b)]))})),h},t.resolveMergeConflictMarker=function(t,n,i,r){let s=e.diff.toLines(t),o=n;for(;o<s.length&&!/^<<<<<<<[^<]/.test(s[o]);)o++;let a=o+1;for(;a<s.length&&!/^=======$/.test(s[a]);)a++;let l=a+1;for(;l<s.length&&!/^>>>>>>>[^>]/.test(s[l]);)l++;if(l>=s.length)return e.debug(`diff marker mistmatch: ${s.length} -> ${o} ${a} ${l}`),t;if(s[o]=void 0,s[a]=void 0,s[l]=void 0,!i)for(let e=o;e<=a;++e)s[e]=void 0;if(!r)for(let e=a;e<=l;++e)s[e]=void 0;return s.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,i){let r=e.Util.jsonTryParse(t),s=e.Util.jsonTryParse(n),o=e.Util.jsonTryParse(i);if(r&&!o)return t;if(!r)return i||n;if(!s&&o&&(s=o),!r||!s||!o)return;delete r.installedVersion,delete s.installedVersion,delete o.installedVersion;const a={},l=e.U.unique(Object.keys(s).concat(Object.keys(r)).concat(Object.keys(o)),(e=>e));for(const t of l){const n=r[t],i=s[t],l=o[t];if(JSON.stringify(n)==JSON.stringify(l))void 0!==n&&(a[t]=n);else switch(t){case"name":a[t]=c(n,i,l);break;case"version":a[t]=e.semver.strcmp(n,l)>0?n:l;break;case"languageRestriction":case"preferredEditor":case"targetVersion":a[t]=n;break;case"public":a[t]=n&&l;break;case"files":case"testFiles":{const e=u(n||[],i||[],l||[]);if(!e)return;a[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},i||{},l||{});if(Object.keys(e).length)return;a[t]=e;break}case"description":if(n&&!l)a[t]=n;else{if(n||!l)return;a[t]=l}break;default:return}}return e.Package.stringifyConfig(a);function c(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,i){const r=[],s=e.U.unique(n.concat(t).concat(i),(e=>e));for(const e of s){const s=t.indexOf(e)>-1,o=i.indexOf(e)>-1,a=n.indexOf(e)>-1;s==o||o==a?s&&r.push(e):o&&r.push(e)}return r}function d(t,n,i){const r={},s=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(i)),(e=>e));for(const o of s){const s=t[o],a=i[o],l=n[o];if(s==a)s&&(r[o]=s);else{const t=e.github.parseRepoId(s),n=e.github.parseRepoId(a);if(t&&n&&e.semver.tryParse(t.tag)&&e.semver.tryParse(n.tag)&&t.owner&&t.project&&t.owner==n.owner&&t.project==n.project){const i=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;r[o]=`github:${t.owner}/${t.project}#${i}`}else a==l?s&&(r[o]=s):a&&(r[o]=a)}}return r}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,i,r){let s={},o=i.tree.tree.map((e=>e.path)).filter((e=>/\.(ts|blocks|md|jres|asm|json)$/.test(e))).filter((t=>t!=e.CONFIG_NAME));return t.fileName&&(o=o.filter((e=>0===e.indexOf(t.fileName))).map((e=>e.slice(t.fileName.length+1)))),o.find((e=>/\.ts$/.test(e)))||(r.config.files.filter((e=>o.indexOf(e)<0)).forEach((e=>{o.push(e),n[e]=r.files[e]})),e.Util.jsonCopyFrom(s,r.config.dependencies)),Object.keys(s).length||(s[e.appTarget.corepkg]="*"),{name:"",files:o,dependencies:s,preferredEditor:o.find((e=>/.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME}}}(e.diff||(e.diff={}))}(pxt||(pxt={})),function(e){!function(t){t.extractSharedIdFromPostUrl=function(t){return e.Util.httpGetJsonAsync(t+".json").then((t=>t.post_stream&&t.post_stream.posts&&t.post_stream.posts[0]&&t.post_stream.posts[0].link_counts.map((t=>e.Cloud.parseScriptId(t.url))).filter((e=>!!e))[0]))},t.topicsByTag=function(t,n){const i=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(i).then((n=>{const i=e.Util.toDictionary(n.users,(e=>e.id.toString()));return n.topic_list.topics.map((e=>({id:e.id,title:e.title,url:`${t}/t/${e.slug}/${e.id}`,imageUrl:e.image_url,author:i[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i,r={},s={};const o="\x3c!-- @CMD@ @ARGS@ --\x3e";let a={parent:o,short:o,description:"\x3c!-- desc --\x3e",activities:"\x3c!-- activities --\x3e",explicitHints:"\x3c!-- hints --\x3e",flyoutOnly:"\x3c!-- flyout --\x3e",hideIteration:"\x3c!-- iter --\x3e",codeStart:"\x3c!-- start --\x3e",codeStop:"\x3c!-- stop --\x3e",autoOpen:"\x3c!-- autoOpen --\x3e",autoexpandOff:"\x3c!-- autoexpandOff --\x3e",preferredEditor:"\x3c!-- preferredEditor --\x3e",tutorialCodeValidation:"\x3c!-- tutorialCodeValidation --\x3e"};function l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&"),e=l(e,"<","<"),e=l(e,">",">"),e=l(e,'"',"""),e=l(e,"'","'")}function u(e){return e?c(e.replace(/\&([#a-z0-9A-Z]+);/g,((e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';default:return"#"==t[0]?String.fromCharCode(parseInt(t.slice(1))):e}}))):e}t.htmlQuote=c,t.html2Quote=u;const d=[{rx:/^vimeo\.com\/(\d+)/i,cmd:"### @vimeo $1"},{rx:/^(www\.youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+(\#t=([0-9]+m[0-9]+s|[0-9]+m|[0-9]+s))?)/i,cmd:"### @youtube $2"}];t.requireMarked=()=>"undefined"!=typeof marked?marked:"undefined"!=typeof require?require("marked"):void 0,t.requireDOMSanitizer=()=>"undefined"!=typeof DOMPurify?DOMPurify.sanitize:"undefined"!=typeof require?require("DOMPurify").sanitize:void 0;const h=e=>`<div class='ui negative message'>${c(e)}</div>`;function p(e){let t=n.clone(r),i=n.clone(s),o=n.clone(a),l={},c={},d=e.params,p=e.theme;e.boxes=t,e.macros=i,e.settings=o,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,r)=>{let s=function(e){let t={};for(;e.trim();){let n=/\s*([^=\s]+)=("([^"]*)"|'([^']*)'|(\S*))/.exec(e);if(n){let e=n[3]||n[4]||n[5]||"";t[n[1].toLowerCase()]=e}else n=/^\s*(\S+)/.exec(e),t[n[1]]="true";e=e.slice(n[0].length)}return t}(n),a=s["data-name"]||s.id;return a?(/box/.test(s.class)?t[a]=r:/aside/.test(s.class)?t[a]=`\x3c!-- BEGIN-ASIDE ${a} --\x3e${r}\x3c!-- END-ASIDE --\x3e`:/setting/.test(s.class)?o[a]=r:/menu/.test(s.class)?l[a]=r:/toc/.test(s.class)?c[a]=r:i[a]=r,`\x3c!-- macro ${a} --\x3e`):h("id or data-name missing on macro")}));let f=(e,t)=>{let n=l.item,i={NAME:e.name};if(e.subitems)n=l["toc-dropdown"]?l["toc-dropdown"]:0==t?l["top-dropdown"]:l["inner-dropdown"],i.ITEMS=e.subitems.map((e=>f(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=l.divider),e.path&&!/^(https?:|\/)/.test(e.path))return h("Invalid link: "+e.path);i.LINK=e.path}return g(n,i,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||0!=e.filepath.indexOf(t.path))&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,r={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),r.LINK=t.path,y.indexOf(t)>=0?(r.ACTIVE="active",r.EXPANDED="true",m.push({name:t.name,href:t.path})):r.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],r.ITEMS=t.subitems.map((e=>w(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),g(i,r,["ITEMS"]))};d.menu=(p.docMenu||[]).map((e=>f(e,0))).join("\n"),d.TOC=b.map((e=>w(e,0))).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let x="";m.length>1&&(x=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${m.map(((e,t)=>`<a class="${t==m.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==m.length-1?"page":""}">${u(e.name)}</a>`)).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=x,p.boardName&&(d.boardname=u(p.boardName)),p.boardNickname&&(d.boardnickname=u(p.boardNickname)),p.driveDisplayName&&(d.drivename=u(p.driveDisplayName)),p.homeUrl&&(d.homeurl=u(p.homeUrl)),d.targetid=p.id||"???",d.targetname=p.name||"Microsoft MakeCode",d.docsheader=p.docsHeader||"Documentation",d.orgtitle="MakeCode";const k=p.docsLogo&&n.htmlEscape(p.docsLogo),A=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),T=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=k?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${k}" />`:"",d.orglogo=A?`<img aria-hidden="true" role="presentation" class="ui image" src="${A}" />`:"",d.orglogomobile=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"";let E=e.ghEditURLs||[];if(E.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of E)e+=`<a href="${n}"><i class="write icon"></i>${t}</a><br>\n`,t=lf("Edit template of this page on GitHub");e+="</p>\n",d.github=e}else d.github="";const C=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=C;const S=lf("Print this page"),I=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${S}" aria-label="${S}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=I;const P=`\n <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="${lf("Side menu")}" role="menuitem" aria-expanded="false">\n <i class="content icon"></i>\n </a>\n `;d.sidebarToggle=P;const U=["tocsearch1","tocsearch2"].map((e=>`\n <input type="search" name="q" placeholder="${lf("Search...")}" aria-label="${lf("Search Documentation")}">\n <i onclick="document.getElementById('${e}').submit();" tabindex="0" class="search link icon" aria-label="${lf("Search")}" role="button"></i>\n `));d.searchBar1=U[0],d.searchBar2=U[1];let _="";p.accentColor&&(_+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=_,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>g(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e){e.image=function(e,t,n){let i='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(i+=' title="'+t+'"'),i+=' loading="lazy"',i+=this.options.xhtml?"/>":">",i},e.listitem=function(e){const t=/^\s*\[( |x)\]/i.exec(e);return t?`<li class="${" "==t[1]?"unchecked":"checked"}">`+e.slice(t[0].length)+"</li>\n":"<li>"+e+"</li>\n"},e.heading=function(e,t,n){let i=/(.*)#([\w\-]+)\s*$/.exec(e),r="";return i?(e=i[1],r=i[2]):r=n.toLowerCase().replace(/[^\w]+/g,"-"),e&&(e=e.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"")),(e=e.trim()).match(/^\{([\s\S]+)\}$/)&&(e=e.substr(1,e.length-2)),`<h${t} id="${this.options.headerPrefix}${r}">${e}</h${t}>`}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,i,r)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${r}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`))}function g(e,t,i=[]){return e?e.replace(/@(\w+)@/g,((e,r)=>{let s=n.lookup(t,r)||"";return s+="",i.indexOf(r)<0&&(s=u(s)),s})):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let r=!0;e.pubinfo||(r=!1,e.pubinfo={});let s=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,s.time){let e=parseInt(s.time);s.timems||(s.timems=1e3*e+""),s.humantime||(s.humantime=n.isoTime(e))}s.name&&(s.dirname=s.name.replace(/[^A-Za-z0-9_]/g,"-"),s.title=s.name),r&&(s.JSON=JSON.stringify(s,null,4).replace(/</g,"\\u003c"));let o=e.template;o=o.replace(/<!--\s*@include\s+(\S+)\s*-->/g,((t,n)=>"\x3c!-- include "+n+" --\x3e\n"+((e.theme.htmlDocIncludes||{})[n]||"")+"\n\x3c!-- end include --\x3e\n")),o=m(o,s),e.locale&&(o=y(o,e.locale).text);let a={html:o,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:s,TOC:e.TOC};p(a),i||(i=t.requireMarked());let l=new i.Renderer;f(l);const c=l.link;l.link=function(e,t,n){const i=new RegExp("^[/#]").test(e),r=i?"":"_blank";i&&a.versionPath&&(e=`/${a.versionPath}${e}`);return c.call(l,e,t,n).replace(/^<a /,`<a ${r?`target="${r}"`:""} rel="nofollow noopener" `)};let b=t.requireDOMSanitizer();i.setOptions({renderer:l,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:b,smartLists:!0,smartypants:!0});let v=e.markdown;e.repo&&(v+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),v=v.replace(/^\s*https?:\/\/(\S+)\s*$/gm,((e,t)=>{for(let e of d){let n=e.rx.exec(t);if(n)return e.cmd.replace(/\$(\d+)/g,((e,t)=>n[parseInt(t)]||""))+"\n"}return e})),v=v.replace(/@([a-z]+)@/gi,((t,i)=>{let r=s[i];return!r&&e.throwOnError&&n.userError(`unknown macro ${i}`),r||"unknown macro"}));let w=i(v);w=w.replace(/<br\s*\/>/gi,"<br/>"),w=w.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let x="",k=0;function A(e,t,n){let i=n;return e<=k&&(i=x+i,x="",k=0),i}if(w=w.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,i,r,o)=>{let l=/^(\w+)\s+(.*)/.exec(o),c=l?l[1]:o,d=l?l[2]:"";if(d=u(d),c=u(c),i=parseInt(i),r){if("@"==r){let t=n.lookup(a.settings,c);if(null!=t)s[c]=d;else if(t=n.lookup(a.macros,c),null==t)return e.throwOnError&&n.userError(`Unknown command: @${c}`),h(`Unknown command: @${c}`);return A(i,0,g(t,{ARGS:d,CMD:c},["ARGS","CMD"]))}{if(!c){let e=x;return x="",e}let t=n.lookup(a.boxes,c);if(t){let e=t.split("@BODY@"),n=A(i,0,e[0].replace("@ARGS@",d));x=e[1];let r=t.match(/data-[^>\s]+/gi);return r&&r.indexOf("data-inferred")>=0&&(k=i),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return A(i,0,t)})),x&&(w+=x),!s.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(w);e&&(s.title=u(e[1]))}if(!s.description){let e=/<p>([^]+?)<\/p>/.exec(w);e&&(s.description=u(e[1]))}const T=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(w)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(w);T&&(s.cardLogo=u(T[1])),s.twitter=u(e.theme.twitter||"@msmakecode");let E={main:""};w=w.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,i)=>{let r=n.lookup(E,t);return E[t]=(r||"")+i,"\x3c!-- aside --\x3e"})),w=w.replace(/\n<\/code>/g,"</code>"),E.main=w,w="";for(let e of Object.keys(E))w+=(C=e+"-container",S=E[e],g(a.boxes[C]||"@BODY@",{BODY:S},["BODY"]));var C,S;s.body=w,s.name=s.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(s["theme_"+t]=n)}return a.finish()},t.embedUrl=function(e,t,n,i){return`<div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${`${e}#${t}:${n}`}" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div>`},t.runUrl=function(e,t,n){return`<div style="position:relative;height:0;padding-bottom:${t};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${e}?id=${encodeURIComponent(n)}" allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div>`},t.codeEmbedUrl=function(e,t,n){const i=`${e}---codeembed#pub:${t}`;return`<div style="position:relative;height:calc(${n=Math.ceil(n||300)}px + 5em);width:100%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const b={b:1,strong:1,em:1};function y(e,t){const i={};function r(e){let r=/^(\s*)([^]*?)(\s*)$/.exec(e),s=r[2].replace(/\s+/g," ");if(""==s||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|( )+)\s*)+$/.test(s))return null;let o=n.lookup(t,s);return o?s=o:i[s]="",r[1]+s+r[3]}function s(e){return e.replace(/&llt;/g,"<").replace(/&ggt;/g,">")}return{text:e=(e=(e=(e="<start>"+(e=e.replace(/<([\/\w]+)([^<>]*)>/g,((e,t,n)=>{let i=t.replace(/^\//,"").toLowerCase();return 1===b[i]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,i,o)=>{if("script"==n||"style"==n)return s(e);let a=r(s(o));return null==a?s(e):t+a}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,i)=>null==r(i)?e:t+n+'="'+i.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:i}}function v(e,t){if(e.id==t)return e;for(let n of e.children){let e=v(n,t);if(e)return e}return null}function w(e,t){let n=0,i=[{level:0,id:"",title:"",start:n,text:"",children:[]}],r=(e=e.replace(/\r/g,"")).split(/\n/),s={};for(let e of r){let r=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),o=null;if(t&&r)if(r[4])if(s[r[4]])r=null;else{o=v(t,r[4]);let e=t=>{t.id&&(s[t.id]=!0),t.children.forEach(e)};o&&e(o)}else r=null;if(r){let s={level:t?1:r[1].length,title:r[2].trim(),id:r[4]||"",start:n,text:"",children:[]};if(o){e="";for(let t=0;t<o.level;++t)e+="#";e+=" ",e+=s.title||o.title,e+=" #"+s.id}for(;i[i.length-1].level>=s.level;)i.pop();i[i.length-1].children.push(s),i.push(s)}i[i.length-1].text+=e+"\n",n++}return i[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const i=e.docs.requireMarked(),r=t.requireDOMSanitizer(),s={renderer:new i.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:r,smartLists:!1,smartypants:!1};let o={name:"dummy",subitems:[]},a=[];a.push(o);let l=i.lexer(n,s),c=!1;l.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":c=!0;let t={name:"",path:"",subitems:[]};return void a.push(t);case"text":let n=a[a.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,i){n.name=t,n.path=i.replace(".md","")})):c&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let i=a.pop();a[a.length-1].subitems.push(i)}c=!1}));let u=o.subitems;return u&&0!=u.length?u:null},t.visitTOC=function(e,t){e.forEach((function(e){t(e),e.subitems&&e.subitems.forEach(t)}))};let x=!1;function k(e,t){if(x||function(){function e(e,t,n){let i=k(e,t).trim();if(i!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${i}`),new Error("augment docs test fail")}x=!0;let t="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nTEx2\n### Example 3\nTEx3\n\n## See also #also\nTAlso\n",n="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",i="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nMy example\n### Example 3\nTEx3\n\n## See Also These! #also\nMy links\n",r="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",s="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";e(t,"",t),e(t," ",t),e(t,n,i),e(t,r,s)}(),!t)return e;let i=w(e,null),r=w(t,i),s={},o={};for(let e of r.children)n.assert(0==e.children.length),n.assert(!!e.id),s[e.id]=e.text;let a=e=>{e.id&&void 0!==s[e.id]&&(o[e.id]=!0,e.text=s[e.id],e.children=[]),e.children.forEach(a)};a(i);let l="",c=e=>{l+=e.text,e.children.forEach(c)};c(i);let u="",d=r.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of r.children)o[e.id]||(u+=e.text);return u&&(l+="## Couldn't apply replacement logic to:\n"+u),l}t.augmentDocs=k}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const i=document.createElement(e);return t&&Object.keys(t).forEach((e=>i.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?i.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&i.appendChild(t)}(n),i}}(e.dom||(e.dom={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){const t=/```package\s+((.|\s)+?)\s*```/i.exec(e);let n;return t&&(n={},t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).forEach((e=>n[e[0]]=e[1]||"*"))),n}function i(e){const t=/```config\s+((.|\s)+?)\s*```/i.exec(e);let n=[];return t&&t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).filter((e=>"feature"==e[0]&&!!e[1])).forEach((e=>n.push(e[1]))),n.length?n:void 0}function r(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],i=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(i)}}}function s(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function o(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter((e=>!!e)).map((e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,((e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map((e=>null==e?void 0:e.trim()));(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function a(t){if(!t)return[];const n=[];let i,r=!1,s="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))r=!0;else if(/^(### ~|```)$/.test(t)){if(r=!1,i&&s){const t=o(s);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}s="",i=void 0}else r&&(s+=t+"\n")})),n.forEach((t=>t.cards.forEach((t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map((e=>({url:t.url,cardType:t.cardType,editor:e})))}})))),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=r,t.parseTemplateProjectJSON=s,t.parseExampleMarkdown=function(t,o){if(!o)return;const a=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(o);if(!a)return;const l=n(o),c=a[1],u=a[2],d=i(o),h=r(o),p={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===a[1]?e.MAIN_PY:e.MAIN_TS]:u},dependencies:l,features:d,snippetType:c,source:u};return p.filesOverride=Object.assign(Object.assign({},p.filesOverride),s(o)),h&&(p.filesOverride[e.TILEMAP_JRES]=h.jres,p.filesOverride[e.TILEMAP_CODE]=h.ts),p},t.parseCodeCards=o,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach((e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach((e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&i.push(n),n=void 0)})),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=a,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>a(e)))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map((e=>Object.keys(e).filter((t=>!!e[t])).map((t=>"otherActions"===t?e[t].map((e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`)).join("\n"):`* ${t}: ${e[t]}`)).join("\n"))).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,r=t.charAt(t.length-1);for(;i-- >0;)t+=r}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,(e=>"OK"==e))}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(i).then((()=>null)):new Promise((r=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),r(i)},this.io.sendPacketAsync(i)}))))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",(()=>new Promise((r=>{this.onResponse=n=>{var s;"OK"!=n&&"O"==n[0]?i+=(s=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(s))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),r(i))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const i=this.pktSize/2-6;if(n>i){const r=new Uint8Array(n),s=o=>{const a=Math.min(n-o,i);return 0==a?Promise.resolve(r):this.readMemAsync(t+o,a).then((t=>(e.U.memcpy(r,o,t),s(o+a))))};return s(0)}return this.sendCmdAsync("m"+t.toString(16)+","+n.toString(16)).then((t=>e.U.fromHex(t)))}initBMPAsync(){return Promise.resolve().then((()=>this.sendRCmdAsync("swdp_scan"))).then((e=>(this.targetInfo=e,this.sendCmdAsync("vAttach;1",(e=>"T"==e[0]))))).then((()=>{}))}initAsync(){return e.U.delay(1e3).then((()=>this.sendCmdAsync("!"))).then((()=>this.sendCmdAsync("qSupported"))).then((t=>{let n={};return t=(t=";"+t+";").replace(/;([^;]+)[=:]([^:;]+)/g,((e,t,i)=>(n[t]=i,";"))),this.pktSize=parseInt(n.PacketSize)||1024,e.log("GDB-server caps: "+JSON.stringify(n)+" "+t.replace(/;+/g,";")),this.bmpMode?this.initBMPAsync():this.sendCmdAsync("c").then((()=>{}))}))}}}(pxt||(pxt={})),function(e){!function(t){function n(){var n,i;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(i=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===i?void 0:i.noGithubProxy)}t.token=null,t.forceProxy=!1;const i={};function r(n){var i;return n.method=null!==(i=n.method)&&void 0!==i?i:"GET",function i(r){var s;const o=e.U.clone(n);t.token&&(o.headers||(o.headers={}),o.url==_?o.headers.Authorization=`bearer ${t.token}`:(o.url=e.BrowserUtils.cacheBustingUrl(o.url),o.headers.Authorization=`token ${t.token}`));return o.allowHttpErrors=null!==(s=o.allowHttpErrors)&&void 0!==s&&s,e.U.requestAsync(o).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(o,n))return i(!1)}throw n}))}(t.token)}function s(e){return r({url:e,method:"GET"}).then((e=>e.json))}function o(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then((e=>e.json))}function a(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return r({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class l{constructor(){this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let r=this.packages[i];if(r)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(r);const s=E(t);return o(I(s.slug,n,s.fileName,"text")).then((e=>this.packages[i]={files:e}))}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(i="master");const r=`${t}/${i}`;let s=this.configs[r];if(s)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(s);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(r,n.files[e.CONFIG_NAME])}catch(e){a(e)}const o=await u(t,i,e.CONFIG_NAME);return this.cacheConfig(r,o)}async loadPackageAsync(t,i){if(i||(i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then((t=>e.U.clone(t)))}catch(e){a(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return g(t,n).then((i=>{const r=`${t}/${i}`;let s=this.packages[r];return s?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(s))):(e.log(`Downloading ${t}/${n} -> ${i}`),u(t,i,e.CONFIG_NAME).then((n=>{const s={files:{}};s.files[e.CONFIG_NAME]=n;const o=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(o).slice(1),(e=>u(t,i,e).then((t=>{s.files[e]=t})))).then((()=>(this.packages[r]=s,e.U.clone(s))))})))}))}}function c(t,n,s){return r({url:"https://api.github.com/repos/"+I(t.slug,"contents",t.fileName,s+"?ref="+n),method:"GET"}).then((n=>{const r=n.json;return i[t.slug]=!0,r&&"base64"==r.encoding&&null!=r.content?atob(r.content):e.U.httpGetTextAsync(r.download_url)}))}function u(t,n,r){const s=E(t);return i[s.slug]?c(s,n,r):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+I(s.slug,n,s.fileName,r),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:c(s,n,r)))}function d(e,t,n,i){return r({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:i||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function h(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function p(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function f(i,r="tags",o,a){const l=E(i),c=(u=o,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const h=c?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${l.slug}/refs${a?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+r+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):s(`https://api.github.com/repos/${l.slug}/git/refs/${r}/?per_page=100`);let p=e=>e.replace(/^refs\/[^\/]+\//,"");return h.then((t=>{t.sort(((t,n)=>e.semver.strcmp(p(t.ref),p(n.ref))));let n={};for(let e of t)n[p(e.ref)]=e.object.sha;return{refs:n,head:d}}),(e=>404==e.statusCode?{refs:{}}:Promise.reject(e)))}function m(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?s(e.object.url).then((e=>"commit"==e.object.type?e.object.sha:Promise.reject(new Error("Bad type (2nd order) "+e.object.type)))):Promise.reject(new Error("Bad type "+e.object.type))}function g(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=E(e);return s(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(m,(e=>s(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(m)))}function b(e,n="master"){return t.db.loadConfigAsync(e,n)}function y(n,i){const r=E(n);return r?A(r,i)?(e.tickEvent("github.download.banned"),e.log("Github repo is banned"),Promise.resolve(void 0)):t.db.loadPackageAsync(r.fullName,r.tag).then((t=>{const r=U(i,n);if(r){const i=e.Package.parseAndValidConfig(t.files[e.CONFIG_NAME]);i&&(e.log(`auto-disable ${r.join(",")} due to targetconfig entry for ${n}`),i.disablesVariants=r,t.files[e.CONFIG_NAME]=e.Package.stringifyConfig(i))}return t})):(e.log("Unknown GitHub syntax"),Promise.resolve(void 0))}let v;function w(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function x(e,t){var n;if(!e)return;const i={owner:e.owner.login.toLowerCase(),slug:e.full_name.toLowerCase(),fullName:((null==t?void 0:t.fullName)||e.full_name).toLowerCase(),fileName:null===(n=null==t?void 0:t.fileName)||void 0===n?void 0:n.toLocaleLowerCase(),name:e.name,description:e.description,defaultBranch:e.default_branch,tag:null==t?void 0:t.tag,updatedAt:Math.round(new Date(e.updated_at).getTime()/1e3),fork:e.fork,private:e.private};return i.status=k(i,null==t?void 0:t.config),i}function k(e,t){return e?A(e,t)?v.Banned:function(e,t){return!!function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t)||!(!e||!t)&&!!(e.fullName&&t.approvedRepos&&t.approvedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase())))}(e,t)?v.Approved:v.Unknown:v.Unknown}function A(e,t){return!!function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase()))))}(e,t)||!!t&&(!e||!e.fullName||!(!t.bannedRepos||!t.bannedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase()))))}async function T(t,i){const r=E(t);if(!r)return;const l=k(r,i);if(l==v.Banned)return;if(n())try{return await function(t,n){return o(t.slug).then((e=>{if(e)return{github:!0,owner:t.owner,fullName:t.fullName,fileName:t.fileName,slug:t.slug,name:t.fileName?`${e.name}-${t.fileName}`:e.name,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}})).catch((t=>{e.reportException(t)}))}(r,l)}catch(e){a(e)}return x(await s("https://api.github.com/repos/"+r.slug),{config:i,fullName:r.fullName,fileName:r.fileName,tag:r.tag})}function E(e){if(!e)return;e=(e=e.trim()).replace(/\/$/,"");const t=/^https:\/\/([^./#]+)\.github\.io\/([^/#]+)\/?$/i.exec(e);t&&(e=`github:${t[1]}/${t[2]}`),e=(e=(e=e.replace(/^github:/i,"")).replace(/^https:\/\/github\.com\//i,"")).replace(/\.git\b/i,"");const n=/^([^#\/:]+)\/([^#\/:]+)(\/([^#]+))?(#([^\/:]*))?$/.exec(e);if(!n)return;const i=n[1],r=n[2];let s=n[4];const o=n[6],a=s&&/^tree\/([^\/]+\/)/.exec(s);return a&&(s=s.slice(a[0].length)),{owner:i,project:r,slug:I(i,r),fullName:I(i,r,s),tag:o,fileName:s}}function C(e){return!!e&&"github:"==e.slice(0,7)}function S(e){return e?"github:"+e.fullName.toLowerCase()+"#"+(e.tag||"master"):void 0}function I(...e){return e.filter((e=>!!e)).join("/")}function P(t,n){if(!t||!t.upgrades)return null;const i=E(n);return i?e.U.lookup(t.upgrades,i.fullName.toLowerCase()):null}function U(e,t){const n=P(e,t),i=/^dv:(.*)/.exec(n);if(i){const e=i[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}return null}t.MemoryGithubDb=l,t.downloadTextAsync=u,t.db=new l,t.authenticatedUserAsync=function(){return t.token?s("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return s("https://api.github.com/repos/"+E(e).slug+"/commits?sha="+t).then((e=>e.map((e=>{const t=e.commit;return t.url=e.url,t.sha=e.sha,t}))))},t.getCommitAsync=function(e,t){return s("https://api.github.com/repos/"+E(e).slug+"/git/commits/"+t).then((e=>s(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(E(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,i,r){return d(`${E(e).slug}/commits/${t}/comments`,{body:n,path:i,position:r}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const i=E(e);return 200==(await r({url:`https://api.github.com/repos/${i.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,i){const s=E(t);await r({url:`https://api.github.com/repos/${e.github.join(s.slug,"contents",s.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(i)),branch:"master"},successCodes:[201]})},t.createTagAsync=async function(e,t,n){await d(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await d(e+"/releases",{tag_name:t,target_commitish:n,name:t,draft:!1,prerelease:!1})},t.createPRFromBranchAsync=async function(e,t,n,i,r){const s=await d(e+"/pulls",{title:i,body:r||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==s?void 0:s.html_url},t.mergeAsync=function(t,n,i,s){return r({url:`https://api.github.com/repos/${E(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:s}}).then((n=>{if(201==n.statusCode||204==n.statusCode)return n.json.sha;if(409==n.statusCode)return null;throw e.U.userError(lf("Cannot merge in github.com/{1}; code: {2}",t,n.statusCode))}))},t.getRefAsync=function(e,t){return s("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(m).catch((e=>{404!=e.statusCode&&Promise.reject(e)}))},t.getNewBranchNameAsync=async function(e,t="patch-"){return h(await f(e,"heads"),t)},t.createNewBranchAsync=p,t.forkRepoAsync=async function(t,n,i="pr-"){const r=E(t),s=x(await d(`${r.slug}/forks`,{}),{fullName:r.fullName,fileName:r.fileName}),o=Date.now()+3e5;let a=null;for(;!a&&Date.now()<o;){await e.U.delay(1e3);try{a=await f(s.slug,"heads")}catch(e){}}if(!a)throw new Error(lf("Timeout waiting for fork"));const l=h(a,i);return await p(s.slug,l,n),s.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return f(e,t,n,i).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=f,t.pkgConfigAsync=b,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t){const n=await e.packagesConfigAsync(),i=await e.github.latestVersionAsync(t.slug,n),r=`${t.fullName}#${i}`;return await e.github.downloadPackageAsync(r,n),{version:`github:${r}`,config:await b(t.fullName,i)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>C(t.dependencies[e])));if(i.length){const n=await e.packagesConfigAsync();await Promise.all(i.map((async e=>{const i=t.dependencies[e];if(!await y(i,n))throw new Error(lf("Cannot load extension {0} from {1}",e,i))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.listUserReposAsync=function(){return N('{\n viewer {\n repositories(first: 100, affiliations: [OWNER, COLLABORATOR], orderBy: {field: PUSHED_AT, direction: DESC}) {\n nodes {\n name\n description\n full_name: nameWithOwner\n private: isPrivate\n fork: isFork\n updated_at: updatedAt\n owner {\n login\n }\n defaultBranchRef {\n name\n }\n pxtjson: object(expression: "master:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "master:README.md") {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n}').then((t=>t.data.viewer.repositories.nodes.filter((e=>e.pxtjson)).filter((t=>{t.default_branch=t.defaultBranchRef.name;const n=e.Package.parseAndValidConfig(t.pxtjson&&t.pxtjson.text),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>x(e,{fullName:e.full_name})))))},t.createRepoAsync=function(e,t,n){return d("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then((e=>x(e)))},t.enablePagesAsync=async function(t){const n=E(t);let i;try{const e=await s(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await d(`https://api.github.com/repos/${n.slug}/pages`,{source:{branch:"master",path:"/"}},{Accept:"application/vnd.github.switcheroo-preview+json"})).html_url}catch(t){e.tickEvent("github.pages.error"),e.reportException(t)}if(i){const n=await s(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:i},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return w(e)},t.mkRepoIconUrl=w,t.repoStatus=k,t.repoAsync=T,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(E).filter((e=>!!e));return i.length>0?Promise.all(i.map((e=>T(e.fullName,n)))).then((e=>e.filter((e=>e&&e.status!=v.Banned)))):e.U.httpGetJsonAsync(`${e.Cloud.apiRoot}ghsearch/${e.appTarget.id}/${e.appTarget.platformid||e.appTarget.id}?q=${encodeURIComponent(t)}`).then((t=>t.items.map((e=>x(e,{config:n,fullName:e.full_name}))).filter((e=>e.status==v.Approved||n.allowUnapproved&&e.status==v.Unknown)).filter((t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())))).catch((e=>[]))},t.parseRepoId=E,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=C,t.stringifyRepo=S,t.normalizeRepoId=function(e){const t=E(e);if(t)return t.tag=t.tag||"master",S(t)},t.join=I,t.upgradedPackageReference=function(t,n){const i=P(t,n);if(!i)return null;const r=/^min:(.*)/.exec(i),s=r&&e.semver.tryParse(r[1]);if(s){const t=E(n),i=e.semver.tryParse(t.tag);return i&&e.semver.cmp(i,s)<0?(t.tag=r[1],e.debug(`upgrading ${n} to ${r[1]}`),S(t)):(i||e.log(`not upgrading ${n} - cannot parse version`),null)}return U(t,n)||e.log(`invalid upgrade rule: ${n} -> ${i}`),n},t.upgradedPackageId=function(e,t){const n=U(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,i,r){const s=E(t);return s?T(s.slug,n).then((t=>{if(t)return f(t.slug,"tags",i,r).then((i=>{let r=Object.keys(i.refs);r=e.semver.sortLatestTags(r);const o=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(o&&n.releases&&n.releases["v"+o.major]){const i=n.releases["v"+o.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==s.fullName.toLowerCase()))[0];if(i){if(r.some((e=>e==i.tag)))return e.debug(`approved release ${i.fullName}#${i.tag} for v${o.major}`),Promise.resolve(i.tag);e.reportError("packages",`approved release ${i.fullName}#${i.tag} for v${o.major} not found anymore`,{repo:t.fullName})}}return r[0]?Promise.resolve(r[0]):i.head||g(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const i={};return Object.keys(n).map((e=>({id:e,ghid:t.parseRepoId(n[e])}))).filter((e=>{var t;return null===(t=e.ghid)||void 0===t?void 0:t.tag})).forEach((t=>{const{id:n,ghid:r}=t;let s=i[r.slug];s||(s=i[r.slug]={tag:r.tag,deps:[]}),s.deps.push(t),e.semver.strcmp(s.tag,r.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(r)}`),s.tag=r.tag)})),e.U.values(i).forEach((t=>t.deps.forEach((i=>{i.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(i.ghid)} -> ${t.tag}`),i.ghid.tag=t.tag,n[i.id]=e.github.stringifyRepo(i.ghid))})))),n},t.GIT_JSON=".git.json";const _="https://api.github.com/graphql";function N(e){const t=JSON.stringify({query:e});return d(_,t)}t.lookupFile=function(e,t,n){if(!t)return null;const i=I(e.fileName,n);return t.tree.tree.find((e=>e.path==i))},t.ghGraphQLQueryAsync=N,t.findPRNumberforBranchAsync=function(e,t){const n=E(e);return N(`\n{\n repository(owner: ${JSON.stringify(n.owner)}, name: ${JSON.stringify(n.project)}) {\n pullRequests(last: 1, states: [OPEN, MERGED], headRefName: ${JSON.stringify(t)}) {\n edges {\n node {\n number\n state\n mergeable\n baseRefName\n url\n isDraft\n }\n }\n }\n }\n}\n`).then((e=>{const t=e.data.repository.pullRequests.edges[0];if(t&&t.node){const e=t.node;return{number:e.number,mergeable:e.mergeable,state:e.state,title:e.title,url:e.url,base:e.baseRefName}}return{number:-1}}))},t.getPagesStatusAsync=function(e){return s(`https://api.github.com/repos/${e}/pages`).catch((e=>({status:null})))}}(e.github||(e.github={}))}(pxt||(pxt={})),function(e){let t;e.REFCNT_FLASH="0xfffe",e.VTABLE_MAGIC=249,e.ValTypeObject=4,function(e){e[e.BoxedString=1]="BoxedString",e[e.BoxedNumber=2]="BoxedNumber",e[e.BoxedBuffer=3]="BoxedBuffer",e[e.RefAction=4]="RefAction",e[e.RefImage=5]="RefImage",e[e.RefCollection=6]="RefCollection",e[e.RefRefLocal=7]="RefRefLocal",e[e.RefMap=8]="RefMap",e[e.RefMImage=9]="RefMImage",e[e.MMap=10]="MMap",e[e.BoxedString_SkipList=11]="BoxedString_SkipList",e[e.BoxedString_ASCII=12]="BoxedString_ASCII",e[e.ZPin=13]="ZPin",e[e.User0=16]="User0"}(t=e.BuiltInType||(e.BuiltInType={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function i(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function r(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return e[t]|e[t+1]<<8}function o(e){let t=new Uint8Array(4*e.length);for(let i=0;i<e.length;++i)n(t,4*i,e[i]);return t}t.HF2_CMD_BININFO=1,t.HF2_MODE_BOOTLOADER=1,t.HF2_MODE_USERSPACE=2,t.HF2_CMD_INFO=2,t.HF2_CMD_RESET_INTO_APP=3,t.HF2_CMD_RESET_INTO_BOOTLOADER=4,t.HF2_CMD_START_FLASH=5,t.HF2_CMD_WRITE_FLASH_PAGE=6,t.HF2_CMD_CHKSUM_PAGES=7,t.HF2_CMD_READ_WORDS=8,t.HF2_CMD_WRITE_WORDS=9,t.HF2_CMD_DMESG=16,t.HF2_FLAG_SERIAL_OUT=128,t.HF2_FLAG_SERIAL_ERR=192,t.HF2_FLAG_CMDPKT_LAST=64,t.HF2_FLAG_CMDPKT_BODY=0,t.HF2_FLAG_MASK=192,t.HF2_SIZE_MASK=63,t.HF2_STATUS_OK=0,t.HF2_STATUS_INVALID_CMD=1,t.HF2_STATUS_EXEC_ERR=2,t.HF2_STATUS_EVENT=128,t.HF2_CMD_JDS_CONFIG=32,t.HF2_CMD_JDS_SEND=33,t.HF2_EV_JDS_PACKET=8388640,t.CUSTOM_EV_JACDAC="jacdac",t.HF2_EV_MASK=8388608,t.write32=n,t.write16=i,t.read32=r,t.read16=s,t.encodeU32LE=o,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(r(e,n));return t};let a=!1;function l(t){a?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){a=!0};class c{constructor(n){var i;this.io=n,this.cmdSeq=e.U.randomUint32(),this.lock=new e.U.PromiseQueue,this.flashing=!1,this.rawMode=!1,this.maxMsgSize=63,this.bootloaderMode=!1,this.reconnectTries=0,this.autoReconnect=!1,this.icon=(null===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{};let s=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let r=i[0]&t.HF2_FLAG_MASK,o=63&i[0],a=new Uint8Array(o);if(e.U.memcpy(a,0,i,1,o),r&t.HF2_FLAG_SERIAL_OUT)this.onSerial(a,r==t.HF2_FLAG_SERIAL_ERR);else if(s.push(a),r!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(r==t.HF2_FLAG_CMDPKT_LAST);let i=0;for(let e of s)i+=e.length;let o=new Uint8Array(i),a=0;for(let t of s)e.U.memcpy(o,a,t),a+=t.length;s=[],o[2]&t.HF2_STATUS_EVENT?n.onEvent(o):this.msgs.push(o)}},n.onEvent=t=>{let n=r(t,0),i=e.U.lookup(this.eventHandlers,n+"");i?i(t.slice(4)):l("unhandled event: "+n.toString(16))},n.onError=e=>{l("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{l("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then((()=>{})):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(r,o){if(this.io.talksAsync)return this.io.talksAsync([{cmd:r,data:o}]).then((e=>e[0]));let a=8;o&&(a+=o.length);let c=new Uint8Array(a),u=65535&++this.cmdSeq;n(c,0,r),i(c,4,u),i(c,6,0),o&&e.U.memcpy(c,8,o,0,o.length);let d=0,h=()=>this.msgs.shiftAsync(1e3).then((e=>{if(s(e,0)!=u){if(d<3)return d++,l(`message out of sync, (${u} vs ${s(e,0)}); will re-try`),h();this.error("out of sync")}let n="";switch(e[3]&&(n="; info="+e[3]),e[2]){case t.HF2_STATUS_OK:return e.slice(4);case t.HF2_STATUS_INVALID_CMD:this.error("invalid command"+n);break;case t.HF2_STATUS_EXEC_ERR:this.error("execution error"+n);break;default:this.error("error "+e[2]+n)}return null}));return this.sendMsgAsync(c).then(h)}sendMsgAsync(e){return this.sendMsgCoreAsync(e)}sendSerialAsync(e,t=!1){return this.io.sendSerialAsync?this.io.sendSerialAsync(e,t):this.sendMsgCoreAsync(e,t?2:1)}sendMsgCoreAsync(e,n=0){let i=new Uint8Array(64),r=s=>{let o=e.length-s;if(o<=0)return Promise.resolve();o>63?(o=63,i[0]=t.HF2_FLAG_CMDPKT_BODY):i[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(i[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),i[0]|=o;for(let t=0;t<o;++t)i[t+1]=e[s+t];return this.io.sendPacketAsync(i).then((()=>r(s+o)))};return this.lock.enqueue("out",(()=>r(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(l("Switching into bootloader mode"),this.io.isSwitchingToBootloader&&this.io.isSwitchingToBootloader(),this.maybeReconnectAsync().then((()=>this.talkAsync(t.HF2_CMD_START_FLASH).then((()=>{}),(e=>this.talkAsync(t.HF2_CMD_RESET_INTO_BOOTLOADER).then((()=>{}),(e=>{})).then((()=>this.reconnectAsync().catch((e=>{throw"devicenotfound"===e.type&&(e.type="repairbootloader"),e})))))))).then((()=>this.initAsync())).then((()=>{this.bootloaderMode||this.error("cannot switch into bootloader mode")})))}isFlashing(){return!!this.flashing}reflashAsync(t){l("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],i=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(i))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,i){return e.U.assert(i.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,o([n,i.length].concat(i))).then((()=>{}))}readWordsAsync(i,r){let s=new Uint8Array(8);return n(s,0,i),n(s,4,r),e.U.assert(r<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,s)}pingAsync(){return this.rawMode?Promise.resolve():this.talkAsync(t.HF2_CMD_BININFO).then((e=>{}))}maybeReconnectAsync(){return this.pingAsync().catch((e=>this.reconnectAsync().then((()=>this.pingAsync()))))}flashAsync(i){let r=Date.now(),s=0,o=r=>{if(r>=i.length)return Promise.resolve();let s=i[r],a=new Uint8Array(4+s.payloadSize);return n(a,0,s.targetAddr),e.U.memcpy(a,4,s.data,0,s.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,a).then((()=>o(r+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*i.length;return l(`Starting flash (${Math.round(e/1024)}kB).`),s=Date.now(),this.pageSize>16384?i:u(i,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=i.length){let t=256*(i=e).length;l(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>o(0))).then((()=>{let e=Date.now(),t=e-r,n=e-s;l(`Flashing done at ${Math.round(256*i.length/n*1e3/1024)} kB/s in ${t}ms (reset ${t-n}ms). Resetting.`)})).then((()=>this.talkAsync(t.HF2_CMD_RESET_INTO_APP).catch((e=>{})))).then((()=>{}))}initAsync(){return this.rawMode?Promise.resolve():Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=r(e,4),this.flashSize=r(e,8)*this.pageSize,this.maxMsgSize=r(e,12),this.familyID=r(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO)))).then((t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,((e,t,i)=>(n[t.replace(/-/g,"")]=i,""))),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)})).then((()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then((()=>{this.jacdacAvailable=!0}),(e=>{this.jacdacAvailable=!1})))).then((()=>{this.reconnectTries=0}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),s=pxtc.parseChecksumBlock(i);return s?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then((t=>r(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>s.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;l("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let i=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const r=i.read32;let s,o,a,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function m(e){return 1&e?e>>1:0!=e?2&e?e==t.taggedNull?null:e!=t.taggedFalse&&(e==t.taggedTrue||{tagged:e>>2}):{ptr:e}:void 0}function g(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let r=[];for(;t>0;){let n=Math.min(i,t);r.push(g(e,n)),t-=n,e+=n}return Promise.all(r).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let r=0;return g(t.ptr,56).then((s=>{r=i.read16(s,2);let o=s.length;return r==e.BuiltInType.BoxedString||r==e.BuiltInType.BoxedBuffer?o=i.read16(s,4)+6:r==e.BuiltInType.BoxedNumber&&(o=12),o>s.length?g(t.ptr+s.length,o-s.length).then((e=>n.uint8ArrayConcat([s,e]))):o<s.length?s.slice(0,o):s})).then((t=>r==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):r==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:r==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:r,refcnt:i.read16(t,0),data:t.slice(4)}))}return Promise.resolve(t)}function y(e){let t=[];for(let n of Object.keys(e))t.push(b(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=s.breakpoints,n=t[0],i=1/0;for(let r of t){let t=e-r.binAddr;t>=0&&t<i&&(i=t,n=r)}return n}function w(e){if(p)return Promise.resolve();let r;return p=!0,T().then((t=>{let o=i.decodeU32LE(e)[0],l={};for(let e of s.procDebugInfo[0].locals){let r=t.globals,s=(()=>{switch(e.type){case"uint32":return i.read32(r,e.index);case"int32":return 0|i.read32(r,e.index);case"uint16":return i.read16(r,e.index);case"int16":return i.read16(r,e.index)<<16>>16;case"uint8":return r[e.index];case"int8":return r[e.index]<<24>>24;default:return null}})();null===s&&(n.assert(0==(3&e.index)),s=m(i.read32(r,e.index))),l[e.name]=s}return c=v(o),r={type:"debugger",subtype:"breakpoint",breakpointId:c.id,globals:l,stackframes:[]},a(),h.talkAsync(1888490768)})).then((e=>{!function(e,t){let i=c.binAddr,r=0,o=s.procDebugInfo.filter((e=>e.codeStartLoc<=i&&i<=e.codeEndLoc))[0];for(;o&&o!=s.procDebugInfo[0];){let s=v(i),a=n.clone(s);a.functionName=o.name,a.argumentNames=o.args&&o.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:a,breakpointId:s.id});let l=t.stackframes[t.stackframes.length-1],c=0;for(let t of o.locals)n.assert(t.index==c++),l.locals[t.name]=m(e[r++]);i=2147483646&e[r++];let d=u[i+""];for(let t of o.args)l.locals[t.name]=m(e[r+(o.args.length-1-t.index)]);if(!d)break;o=d.from,r+=d.stack-o.localsMark}}(i.decodeU32LE(e),r);let t=[r.globals].concat(r.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(r)))}function x(){p=!1,o=new Promise(((e,t)=>{a=e}))}function k(e=!1){return Promise.resolve().then((()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3])))).then(x)}function A(){return o||(o=Promise.resolve()),o}function T(){return(l?Promise.resolve(l):h.talkAsync(1409050336).then((e=>l={numGlobals:r(e,0),globalsPtr:r(e,4)}))).then((e=>h.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:l,globals:e})))}t.taggedUndefined=0,t.taggedNull=f(1),t.taggedFalse=f(2),t.taggedTrue=f(16),t.postMessage=e=>console.log(e),t.decodeValue=m,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,s=null,l=null,Promise.resolve()).then((()=>{s=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}})).then((()=>{let e=s.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(s).then((()=>h.reconnectAsync()))})).then((()=>h.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>h.reconnectAsync())).then(x).then(A)},t.handleMessage=function(e){if(console.log("HWDBGMSG",e),"debugger"!=e.type)return;let t=!1;switch(e.subtype){case"stepinto":t=!0;case"stepover":k(t)}},t.resumeAsync=k,t.waitForHaltAsync=A,t.getHwStateAsync=T}(e.HWDBG||(e.HWDBG={}))}(pxt||(pxt={})),function(e){e.ImageConverter=class{logTime(){if(this.start){let t=Date.now()-this.start;e.debug("Icon creation: "+t+"ms")}}convert(t){this.start||(this.start=Date.now());let n=atob(t.slice(t.indexOf(",")+1)),i=n.charCodeAt(0),r=n.charCodeAt(1),s=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),r=n.charCodeAt(2)|n.charCodeAt(3)<<8,s=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(!this.palette){let t=e.appTarget.runtime.palette.map((function(e){const t=parseInt(e.replace(/#/,""),16);return[t>>0&255,t>>8&255,t>>16&255,255]}));t[0][3]=0,this.palette=new Uint8Array(4*t.length);for(let e=0;e<t.length;++e)this.palette[4*e+0]=t[e][0],this.palette[4*e+1]=t[e][1],this.palette[4*e+2]=t[e][2],this.palette[4*e+3]=t[e][3]}if(225==i)return this.genMonochrome(n,r,s);const o=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&r<100&&s<100?3:1;return this.genColor(n,r,s,o)}genMonochrome(t,n,i){let r=n+3&-4,s=54+this.palette.length,o=s+r*i,a=new Uint8Array(o);a[0]=66,a[1]=77,e.HF2.write32(a,2,o),e.HF2.write32(a,10,s),e.HF2.write32(a,14,40),e.HF2.write32(a,18,n),e.HF2.write32(a,22,-i),e.HF2.write16(a,26,1),e.HF2.write16(a,28,8),e.HF2.write32(a,38,2835),e.HF2.write32(a,42,2835),e.HF2.write32(a,46,this.palette.length>>2),a.set(this.palette,54);let l=4,c=s,u=1,d=t.charCodeAt(l++);for(let e=0;e<n;++e){c=s+e;for(let e=0;e<i;++e)a[c]=d&u?1:0,c+=r,u<<=1,256==u&&(u=1,d=t.charCodeAt(l++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(a))}genColor(t,n,i,r){const s=n*(r=Math.max(1,0|r)),o=i*r;let a=s<<2,l=138,c=l+a*o,u=new Uint8Array(c);u[0]=66,u[1]=77,e.HF2.write32(u,2,c),e.HF2.write32(u,10,l),e.HF2.write32(u,14,124),e.HF2.write32(u,18,s),e.HF2.write32(u,22,-o),e.HF2.write16(u,26,1),e.HF2.write16(u,28,32),e.HF2.write16(u,30,3),e.HF2.write32(u,38,2835),e.HF2.write32(u,42,2835),e.HF2.write32(u,54,16711680),e.HF2.write32(u,58,65280),e.HF2.write32(u,62,255),e.HF2.write32(u,66,4278190080),u[70]=66,u[71]=71,u[72]=82,u[73]=115;let d=4,h=l,p=!0;for(let e=0;e<s;e++){let n=!1;h=l+(e<<2);let s=d,c=t.charCodeAt(d++),f=n?(c>>4&15)<<2:(15&c)<<2;for(let e=0;e<o;e++)c&&(p=!1),u[h]=this.palette[f],u[h+1]=this.palette[f+1],u[h+2]=this.palette[f+2],u[h+3]=this.palette[f+3],h+=a,e%r==r-1&&(n&&(c=t.charCodeAt(d++)),n=!n,f=n?(c>>4&15)<<2:(15&c)<<2);if(p&&(u[141]=1),e%r==r-1)for(i%2||--d;3&d;)d++;else d=s}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}}}(pxt||(pxt={})),function(e){!function(t){function n(){const e={"tsconfig.json":t.TS_CONFIG,"test.ts":`// ${lf("tests go here; this will not be compiled when this package is used as an extension.")}\n`,"_config.yml":"makecode:\n target: @TARGET@\n platform: @PLATFORM@\n home_url: @HOMEURL@\ntheme: jekyll-theme-slate\ninclude:\n - assets\n - README.md\n",Makefile:"all: deploy\n\nbuild:\n\tpxt build\n\ndeploy:\n\tpxt deploy\n\ntest:\n\tpxt test\n",Gemfile:"source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins","README.md":`\n> ${lf("Open this page at {0}","[https://@REPOOWNER@.github.io/@REPONAME@/](https://@REPOOWNER@.github.io/@REPONAME@/)")}\n\n## ${lf("Use as Extension")}\n\n${lf("This repository can be added as an **extension** in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **New Project**")}\n* ${lf("click on **Extensions** under the gearwheel menu")}\n* ${lf("search for **https://github.com/@REPO@** and import")}\n\n## ${lf("Edit this project")} \n\n${lf("To edit this repository in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **Import** then click on **Import URL**")}\n* ${lf("paste **https://github.com/@REPO@** and click import")}\n\n## ${lf("Blocks preview")}\n\n${lf("This image shows the blocks code from the last commit in master.")}\n${lf("This image may take a few minutes to refresh.")}\n\n\n\n#### ${lf("Metadata (used for search, rendering)")}\n\n* for PXT/@TARGET@\n<script src="https://makecode.com/gh-pages-embed.js"><\/script><script>makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");<\/script>\n`,".gitignore":"# MakeCode\nbuilt\nnode_modules\nyotta_modules\nyotta_targets\npxt_modules\n_site\n*.db\n*.tgz\n.header.json\n.simstate.json\n",".vscode/settings.json":'{\n "editor.formatOnType": true,\n "files.autoSave": "afterDelay",\n "files.watcherExclude": {\n "**/.git/objects/**": true,\n "**/built/**": true,\n "**/node_modules/**": true,\n "**/yotta_modules/**": true,\n "**/yotta_targets": true,\n "**/pxt_modules/**": true\n },\n "files.associations": {\n "*.blocks": "html",\n "*.jres": "json"\n },\n "search.exclude": {\n "**/built": true,\n "**/node_modules": true,\n "**/yotta_modules": true,\n "**/yotta_targets": true,\n "**/pxt_modules": true\n }\n}',".github/workflows/makecode.yml":"name: MakeCode\n\non: [push]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [14.x]\n\n steps:\n - uses: actions/checkout@v1\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: build\n run: |\n pxt install\n pxt build --cloud\n env:\n CI: true\n",".github/workflows/cfg-check.yml":"name: Check pxt.json\n\non:\n push:\n branches:\n - 'master'\n - 'main'\n\njobs:\n check-cfg:\n runs-on: ubuntu-latest\n strategy:\n matrix:\n node-version: [14.x]\n steps:\n - uses: actions/checkout@v2\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: Checkout current state\n run: |\n git checkout -- .\n git clean -fd\n - name: Fix files listed in config if necessary\n run: pxt checkpkgcfg\n - name: Create Pull Request\n uses: peter-evans/create-pull-request@v3\n continue-on-error: true\n with:\n title: 'Removing missing files from pxt.json'\n commit-message: 'Removing missing files from pxt.json'\n delete-branch: true\n",".vscode/tasks.json":'\n// A task runner that calls the MakeCode (PXT) compiler\n{\n "version": "2.0.0",\n "tasks": [{\n "label": "pxt deploy",\n "type": "shell",\n "command": "pxt deploy --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt build",\n "type": "shell",\n "command": "pxt build --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt install",\n "type": "shell",\n "command": "pxt install",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt clean",\n "type": "shell",\n "command": "pxt clean",\n "group": "test",\n "problemMatcher": [ "$tsc" ]\n }]\n}\n'},n=i();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,r=e.U.clone(i.config);delete r.installedVersion,delete r.additionalFilePath,delete r.additionalFilePaths,r.preferredEditor=r.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,r.name=t,r.public=!0,r.version||(r.version="0.0.0");const s={},o=n();for(const e in o)s[e]=o[e];for(const e in i.files)"README.md"!=e&&(s[e]=i.files[e]);const a=Object.keys(s).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return r.files=a.filter((e=>!/test/.test(e))),r.testFiles=a.filter((e=>/test/.test(e))),r.supportedTargets=[e.appTarget.id],s[e.CONFIG_NAME]=e.Package.stringifyConfig(r),s},t.packageFilesFixup=function(t,n){const i=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(i,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>i[t.toLowerCase()]=e.webConfig[t])),i.platform=e.appTarget.platformid||e.appTarget.id,i.target=e.appTarget.id,i.docs=e.appTarget.appTheme.homeUrl||"./",i.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>i[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.Prefix=0]="Prefix",e[e.Postfix=1]="Postfix",e[e.Infix=2]="Infix",e[e.Block=3]="Block",e[e.NewLine=4]="NewLine"}(n=t.NT||(t.NT={})),function(e){e[e.None=0]="None",e[e.WithSpace=1]="WithSpace",e[e.NoSpace=2]="NoSpace"}(i=t.GlueMode||(t.GlueMode={}));const r=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"];function s(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function o(e){return e.length>20&&/\n/.test(e)?s(e):JSON.stringify(e)}function a(e,t,n){return{type:e,op:t,children:n}}function l(){return a(n.NewLine,"",[])}function c(e,t){return a(n.Prefix,e,t)}function u(e,t,i){return a(n.Infix,t,null==e?[i]:[e,i])}function d(e){return c(e,[])}function h(e){return a(n.Block,"",e)}function p(e){return c("",e)}function f(e,t=!1){const n=[];for(const i of e)t?(n.length>0&&n.push(d(",")),n.push(l())):n.length>0&&n.push(d(", ")),n.push(i);return t&&n.push(l()),p(n)}let m;t.backtickLit=s,t.stringLit=o,t.mkNode=a,t.mkNewLine=l,t.mkPrefix=c,t.mkPostfix=function(e,t){return a(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=h,t.mkGroup=p,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(l()),p(e)},t.mkCommaSep=f,function(t){function n(e,t,n=!1,i=!1){return p(i?[u(t[0],".",d(e)),d("("),f(t.slice(1),n),d(")")]:[d(e),d("("),f(t,n),d(")")])}function i(e,t,i,r){return n(e+"."+t,i,r)}function r(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return p([d("["),f(e,t),d("]")])},t.mkNumberLiteral=function(e){return d(e.toString())},t.mkBooleanLiteral=function(e){return d(e?"true":"false")},t.mkStringLiteral=function(e){return d(o(e))},t.mkPropertyAccess=function(e,t){return p([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,i){return n(e,t,i)},t.extensionCall=function(e,t,i){return n(e,t,i,!0)},t.namespaceCall=i,t.mathCall=function(e,t){return i("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=r,t.mkWhile=function(e,t){return p([d("while ("),e,d(")"),h(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),l()];return e.split("\n").forEach(((e,n,i)=>{e&&(t.push(d(" * "+e)),t.push(l()),n<i.length-1&&(t.push(d(" * ")),t.push(l())))})),p(t.concat([d(" */"),l()]))},t.mkAssign=function(e,t){return r("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(b([e]).output)?e:p([d("("),e,d(")")])}}(m=t.Helpers||(t.Helpers={})),t.H=m;const g={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let r=[],s={},o="",a="",l=[{}],c=0;function u(e){"string"==typeof e&&(c+=(e.match(/\n/g)||[]).length),o+=e}let h=p(t);return function t(i,r){if(i.type!=n.Infix){for(let e of i.children)t(e,-1);return}let s=[];function o(e){"P"==e[0]&&(e=e.slice(1)),s.push(d(e))}let a=e.U.lookup(g,i.op);if(null==a&&e.U.oops("bad infix op: "+i.op),a<r&&o("("),1==i.children.length)o(i.op),t(i.children[0],a),s.push(i.children[0]);else{let e,n=3!=a&&"**"!=i.op;t(i.children[0],n?a:a+.1),s.push(i.children[0]),e&&"number"!=e&&(o(": "),o(e)),"."==i.op?o("."):o(" "+i.op+" "),t(i.children[1],n?a+.1:a),s.push(i.children[1])}a<r&&o(")"),i.type=n.Prefix,i.op="",i.children=s}(h,-1),f(h),o||u("\n"),{output:o,sourceMap:r};function f(t){t.glueToBlock&&(b(),t.glueToBlock==i.WithSpace&&u(" "));let d=c,h=o.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+a);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void m(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),a+=" "," "!=o[o.length-1]&&m(" ");m("{\n");for(let e of t.children)f(e);a=a.slice(4),b(),m("\n}"+n),l.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op),t.children.forEach(f);break;case n.Postfix:t.children.forEach(f),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op)}let p=c,g=Math.max(o.length,1);if(t.id)if(s[t.id]){const e=s[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,p),e.startPos=Math.min(e.startPos,h),e.endPos=Math.max(e.endPos,g)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:g};s[t.id]=e,r.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+a))}function b(){o=o.replace(/\n *$/,(function(){return c--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const i=e[n];if("("===i)t++;else if(")"===i&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=b,t.isReservedWord=function(e){return-1!==r.indexOf(e)},t.isParenthesized=y}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];t.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",t.TILE_PREFIX="tile",t.TILE_NAMESPACE="myTiles",t.IMAGES_NAMESPACE="myImages",t.IMAGE_PREFIX="image",t.ANIMATION_NAMESPACE="myAnimations",t.ANIMATION_PREFIX="anim";class i{constructor(e,t,n=0,i=0,r){this.width=e,this.height=t,this.x0=n,this.y0=i,this.width||(this.width=16),this.height||(this.height=16),this.buf=r||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}set(e,t,n){if(e<this.width&&t<this.height&&e>=0&&t>=0){const i=this.coordToIndex(e,t);this.setCore(i,n)}}get(e,t){if(e<this.width&&t<this.height&&e>=0&&t>=0){const n=this.coordToIndex(e,t);return this.getCore(n)}return 0}copy(e=0,t=0,n=this.width,r=this.height){const s=new i(n,r);s.x0=e,s.y0=t;for(let i=0;i<n;i++)for(let n=0;n<r;n++)s.set(i,n,this.get(e+i,t+n));return s}apply(e,t=!1){let n;for(let i=0;i<e.width;i++)for(let r=0;r<e.height;r++)n=e.get(i,r),!n&&t||this.set(e.x0+i,e.y0+r,n)}equals(e){if(this.width===e.width&&this.height===e.height&&this.x0===e.x0&&this.y0===e.y0&&this.buf.length===e.buf.length){for(let t=0;t<this.buf.length;t++)if(this.buf[t]!==e.buf[t])return!1;return!0}return!1}data(){return{width:this.width,height:this.height,x0:this.x0,y0:this.y0,data:this.buf}}resize(e,t){return h(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}t.Bitmap=i;class r extends i{static fromData(e){return new r(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const s=new r(n,i);s.x0=e,s.y0=t;for(let r=0;r<n;r++)for(let n=0;n<i;n++)s.set(r,n,this.get(e+r,t+n));return s}resize(e,t){return p(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=r;class s{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(){const e=this.tilemap.copy(),t={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map((e=>Object.assign(Object.assign({},e),{bitmap:i.fromData(e.bitmap).copy().data()})))},n=i.fromData(this.layers).copy().data();return new s(e,t,n)}equals(t){if(!this.tilemap.equals(t.tilemap)||this.tileset.tileWidth!=t.tileset.tileWidth||this.tileset.tiles.length!=t.tileset.tiles.length||!y(this.layers,t.layers))return!1;for(let n=0;n<this.tileset.tiles.length;n++)if(!e.assetEquals(this.tileset.tiles[n],t.tileset.tiles[n]))return!1;return!0}}t.TilemapData=s;function o(e){return a(atob(e.slice(e.indexOf(",")+1)))}function a(t){let n=t.charCodeAt(0),i=t.charCodeAt(1),r=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),i=t.charCodeAt(2)|t.charCodeAt(3)<<8,r=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const s=new e.sprite.Bitmap(i,r);let o=4;if(225===n){let e=1,n=t.charCodeAt(o++);for(let a=0;a<i;++a)for(let i=0;i<r;++i)s.set(a,i,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(o++))}else for(let e=0;e<i;e++){for(let n=0;n<r;n+=2){let i=t.charCodeAt(o++);s.set(e,n,15&i),n!=r-1&&s.set(e,n+1,i>>4&15)}for(;3&o;)o++}return s}function l(e,t){!(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,s=x(e.substring(8));return r.fromData({width:n,height:i,x0:0,y0:0,data:s})}function c(e){return`${d(e.width,2)}${d(e.height,2)}${k(e.data().data)}`}function u(e,t){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e,t){if(0===(e=e.trim()).indexOf("img")){const n=f(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const i=t<<1;for(1&n.length&&(n="0"+n);n.length<i;)n+="0";return n}function h(e,t,n){const r=new i(t,n);return r.apply(e),r}function p(e,t,n){const i=new r(t,n);return i.apply(e),i}function f(e){const t=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),n=[];let r=0;for(let e=0;e<t.length;e++){const i=t[e],s=[];for(let e=0;e<i.length;e++)switch(i[e]){case"0":case".":s.push(0);break;case"1":case"#":s.push(1);break;case"2":case"T":s.push(2);break;case"3":case"t":s.push(3);break;case"4":case"N":s.push(4);break;case"5":case"n":s.push(5);break;case"6":case"G":s.push(6);break;case"7":case"g":s.push(7);break;case"8":s.push(8);break;case"9":s.push(9);break;case"a":case"A":case"R":s.push(10);break;case"b":case"B":case"P":s.push(11);break;case"c":case"C":case"p":s.push(12);break;case"d":case"D":case"O":s.push(13);break;case"e":case"E":case"Y":s.push(14);break;case"f":case"F":case"W":s.push(15);break;default:if(!/\s/.test(i[e]))return}s.length&&(n.push(s),r=Math.max(r,s.length))}const s=n.length,o=new i(r,s);for(let e=0;e<s;e++){const t=n[e];for(let n=0;n<r;n++)n<t.length?o.set(n,e,t[n]):o.set(n,e,0)}return o}function m(e){let t="";switch(e){case"python":t='img("""';break;default:t="img`"}return t}function g(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function b(e,t){if(!e||0===e.height||0===e.width)return"";let i=m(t);if(e){const t=e.width*e.height>300?"":" ";for(let r=0;r<e.height;r++){i+="\n";for(let s=0;s<e.width;s++)i+=n[e.get(s,r)]+t}}return i+="\n",i+=g(t),i}function y(t,n){return e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function v(e){switch(e){case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function w(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function x(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function k(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function A(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function T(e){const t=function(e){if(e){if(6===e.length)return parseInt("0x"+e);if(7===e.length)return parseInt("0x"+e.substr(1))}return 0}(e);return[E(t),C(t),S(t)]}function E(e){return e>>16&255}function C(e){return e>>8&255}function S(e){return 255&e}t.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const n=e+this.width*t,i=n>>3,r=7&n;this.mask[i]|=1<<r}get(e,t){const n=e+this.width*t,i=n>>3,r=7&n;return this.mask[i]>>r&1}},t.encodeTilemap=function(e,t){return e?`tiles.createTilemap(${function(e){return e?`hex\`${c(e)}\``:"hex``"}(e.tilemap)}, ${b(i.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t){return e.id}(e)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const r=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),o=(t=t.substr(r.length+1)).substr(0,t.indexOf(",")),a=(t=t.substr(o.length+1)).substr(0,t.lastIndexOf("]")+1),c=t=t.substr(a.length+1);return new s(l(r),{tiles:u(a,i),tileWidth:w(c)},f(o).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,i={};i[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let r=0;r<n.height;r++)i[t[n.get(e,r)].id]=!0;const r=e.editedTiles||[],s=t.filter((e=>i[e.id]||"*"===e.id.charAt(0)||-1!==r.indexOf(e.id)));if(s.length===t.length)return;const o=[];for(let e=0;e<t.length;e++)o.push(s.indexOf(t[e]));for(let e=0;e<n.width;e++)for(let t=0;t<n.height;t++)n.set(e,t,o[n.get(e,t)]);e.tileset.tiles=s},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,i=t[0].id;for(let e=0;e<n.width;e++)for(let r=0;r<n.height;r++)if(t[n.get(e,r)].id!==i)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(T),i=[0,0,0];let r=0;for(let t=0;t<e.width;t++)for(let s=0;s<e.height;s++){const o=e.get(t,s);if(o){++r;const e=n[o];i[0]+=e[0],i[1]+=e[1],i[2]+=e[2]}}return r?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(i.map((e=>Math.floor(e/r)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},t.getBitmapFromJResURL=o,t.hexToBitmap=a,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),i=t.filter((e=>0===e.indexOf("!")&&e.length>1)).map((e=>e.substring(1)));return e.filter((e=>{return t=e,n.every((e=>{const n=`?${e}`;return t.tags.some((t=>t===e||t===n))}))&&function(e){return i.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,i){let r=function(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,i);return r=r.filter((e=>e.namespace!=t.TILE_NAMESPACE)),function(t){const n=new e.ImageConverter;t.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&0==e.attributes.jresURL.indexOf("data:image/x-mkcd-f")&&(e.attributes.iconURL=n.convert(e.attributes.jresURL))}))}(r),r.map((t=>{const n=(t.attributes.tags||"").split(" ").filter((e=>!!e)).map((t=>e.Util.startsWith(t,"category-")?t:t.toLowerCase()));return{qName:t.qName,src:t.attributes.iconURL,alt:t.qName,tags:n}}))},t.base64EncodeBitmap=function(t){const n=i.fromData(t),r=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(x(r)))},t.tilemapLiteralToTilemap=l,t.hexEncodeTilemap=c,t.formatByte=d,t.resizeBitmap=h,t.resizeTilemap=p,t.imageLiteralToBitmap=f,t.encodeAnimationString=function(t,n){const i=t.map((e=>e.data)),r=new Uint8ClampedArray(8+i[0].length*i.length);A(r,0,n),A(r,2,t[0].width),A(r,4,t[0].height),A(r,6,t.length);let s=8;return i.forEach((e=>{r.set(e,s),s+=e.length})),btoa(e.sprite.uint8ArrayToHex(r))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const i of n.tiles)t.data.tileset.tiles.some((e=>e.id===i.id))||t.data.tileset.tiles.push(i),e.isAssetUsed(i,null,[t.id])&&t.data.projectReferences.push(i.id)},t.updateTilemapReferencesFromResult=function(t,n){const i=n.data;if(i.deletedTiles)for(const e of i.deletedTiles)t.deleteTile(e);if(i.editedTiles)for(const e of i.editedTiles){const n=i.tileset.tiles.findIndex((t=>t.id===e)),r=i.tileset.tiles[n];r&&(i.tileset.tiles[n]=t.updateTile(r))}for(let e=0;e<i.tileset.tiles.length;e++){const n=i.tileset.tiles[e];n.jresData||(i.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(i)},t.imageLiteralFromDimensions=function(e,t,i,r){let s=m(r);const o=e*t>300?"":" ";for(let r=0;r<t;r++){s+="\n";for(let t=0;t<e;t++)s+=n[i]+o}return s+="\n",s+=g(r),s},t.bitmapToImageLiteral=b,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=w,t.hexToUint8Array=x,t.uint8ArrayToHex=k,t.colorStringToRGB=T}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const i=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class r{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function s(e){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e){if(0===(e=e.trim()).indexOf("img")){return{data:t.imageLiteralToBitmap(e).data()}}const n=i.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=r,n.decodeTilemap=function(n,i){var o;if(!(null==(n=null===(o=e.Util.htmlUnescape(n))||void 0===o?void 0:o.trim())?void 0:n.trim()))return new r(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const a=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),l=(n=n.substr(a.length+1)).substr(0,n.indexOf(",")),c=(n=n.substr(l.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(c.length+1);return new r(t.tilemapLiteralToTilemap(a),{tiles:s(c),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(l).data())},n.tileToBlocklyVariable=function(e){return`${e.projectId};${e.data.width};${e.data.height};${pxtc.Util.toHex(e.data.data)}`},n.blocklyVariableToTile=function(e){const t=e.split(";");return 4!==t.length?null:{projectId:parseInt(t[0]),data:{width:parseInt(t[1]),height:parseInt(t[2]),data:new Uint8ClampedArray(pxtc.Util.fromHex(t[3])),x0:0,y0:0}}}}(t.legacy||(t.legacy={}))}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.items={}}removeItem(e){delete this.items[e]}getItem(e){return this.items[e]}setItem(e,t){this.items[e]=t}clear(){this.items={}}}class i{constructor(e){this.storageId=e}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach((e=>window.localStorage.removeItem(e)))}}function r(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let s;function o(){if(s)return;const t=r();let o=!1;if(!e.shell.isSandboxMode())try{window.localStorage[t]="1";window.localStorage[t];o=!0}catch(e){}o?(s=new i(t),e.debug(`storage: local under ${t}`)):(s=new n,e.debug("storage: in memory"))}t.storageId=r,t.setLocal=function(e,t){o(),s.setItem(e,t)},t.getLocal=function(e){return o(),s.getItem(e)},t.removeLocal=function(e){o(),s.removeItem(e)},t.clearLocal=function(){o(),s.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function i(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function r(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,s){if(i()){t+="-"+r();const i=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(s)}`,method:"GET",allowHttpErrors:!0});return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${s}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,s,o){if(void 0===o)return void await e.storage.shared.delAsync(t,s);let a="";if(a="object"==typeof o?JSON.stringify(o):o.toString(),i()){t+="-"+r();const i={type:"object"==typeof o?"json":"text",val:a},l=JSON.stringify(i);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(s)}`,method:"POST",data:l})}else e.storage.setLocal(`${t}:${s}`,a)},t.delAsync=async function(t,s){i()?(t+="-"+r(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(s)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${s}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i){this.id=e,this._verspec=t,this.parent=n,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every((e=>"string"==typeof e))&&n.dependencies&&Object.keys(n.dependencies).every((e=>"string"==typeof n.dependencies[e]))&&n}static getConfigAsync(t,n,i){return Promise.resolve().then((()=>{if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i);return e.packagesConfigAsync().then((n=>e.github.repoAsync(t.fullName,n))).then((n=>n?e.github.pkgConfigAsync(t.fullName,t.tag):null))}{const r=e.patching.upgradePackageReference(t,n,i),s=e.appTarget.bundledpkgs[r];return JSON.parse(s[e.CONFIG_NAME])}}))}static corePackages(){const t=e.appTarget.bundledpkgs;return Object.keys(t).map((n=>JSON.parse(t[n][e.CONFIG_NAME]))).filter((e=>!!e))}disablesVariant(e){return this.config&&this.config.disablesVariants&&this.config.disablesVariants.indexOf(e)>=0}invalid(){return/^invalid:/.test(this.version())}version(){return this.resolvedVersion||this._verspec}verProtocol(){let e=this.version().split(":");return e.length>1?e[0]:""}verArgument(){let e=this.verProtocol();return e?this.version().slice(e.length+1):this.version()}targetVersion(){return this.parent&&this.parent!=this?this.parent.targetVersion():this.config.targetVersions?this.config.targetVersions.target:void 0}commonDownloadAsync(){const t=this.verProtocol();if("pub"==t)return e.Cloud.downloadScriptFilesAsync(this.verArgument());if("github"==t)return e.packagesConfigAsync().then((t=>e.github.downloadPackageAsync(this.verArgument(),t))).then((e=>e.files));if("embed"==t){const t=e.getEmbeddedScript(this.verArgument());return Promise.resolve(t)}if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),n=ts.pxtc.Util.jsonTryParse(t);return n||e.log(`unable to find ${this.verArgument()}`),Promise.resolve(n)}return Promise.resolve(null)}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}readGitJson(){const t=this.readFile(e.github.GIT_JSON);return e.Util.jsonTryParse(t)}resolveDep(e){return this.parent.deps.hasOwnProperty(e)?this.parent.deps[e]:null}saveConfig(){const t=e.U.clone(this.config);delete t.additionalFilePaths;const n=e.Package.stringifyConfig(t);this.host().writeFile(this,e.CONFIG_NAME,n)}setPreferredEditor(e){this.config.preferredEditor!=e&&(this.config.preferredEditor=e,this.saveConfig())}getPreferredEditor(){let t=this.config.preferredEditor;if(!t){if(!(this.getFiles().indexOf(e.MAIN_BLOCKS)>=0))return e.JAVASCRIPT_PROJECT_NAME;const t=this.readFile(e.MAIN_BLOCKS),n=this.readFile(e.MAIN_TS);return!t&&n?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME}return t}parseJRes(t={}){for(const n of this.getFiles())e.U.endsWith(n,".jres")&&i(JSON.parse(this.readFile(n)),t);return t}resolveVersionAsync(){var t;let n=this._verspec;if(e.getEmbeddedScript(this.id))this.resolvedVersion=n="embed:"+this.id;else if(n&&"*"!=n){if("github"==this.verProtocol()){const i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const r=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map((t=>e.github.parseRepoId(t.version()))).filter((e=>(null==e?void 0:e.slug)===i.slug)).map((e=>e.tag)))[0];r&&(i.tag=r,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then((t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then((()=>{this.loadConfig(),e.debug(`installed ${this.id} /${t}`)}))}))}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const r=e.patching.computePatches(this.targetVersion(),"missingPackage");return r&&r.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(i=new RegExp(n,"g"))}))})),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,i={};return e.U.iterMap(this.config.dependencies,((r,s)=>{if(e.github.isGithubId(s)){const o=e.github.upgradedPackageReference(t,s);o&&o!=s&&(e.log(`upgrading dep ${r}: ${s} -> ${o}`),i[s]=o,this.config.dependencies[r]=o,n++)}})),n&&this.saveConfig(),n&&i}))}getMissingPackages(t,n){const i=e.patching.computePatches(this.targetVersion(),"missingPackage"),r={};return n&&i&&i.forEach((e=>{Object.keys(e.map).forEach((i=>{const s=new RegExp(i,"g"),o=e.map[i];n.replace(s,(e=>(t.dependencies[o]||(r[o]="*"),"")))}))})),r}findConflictsAsync(t,i){let r,s=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,i):Promise.resolve(t))).then((t=>{if(r=t,r){const t=r.yotta?e.U.jsonFlatten(r.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(r.core&&n.config.core&&r.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",r.name,n.id));return t.pkg0=n,void s.push(t)}let o=!1;if(t){const i=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!i&&!!i.yotta&&!!n.config.yotta.config){const a=e.U.jsonFlatten(i.yotta.config);for(const l of Object.keys(t)){const c=a[l],u=r.yotta.configIsJustDefaults||i.yotta.configIsJustDefaults;if(a.hasOwnProperty(l)&&c!==t[l]&&!u&&(!n.parent.config.yotta||!n.parent.config.yotta.ignoreConflicts)){const t=new e.cpp.PkgConflictError(lf("conflict on yotta setting {0} between extensions {1} and {2}",l,r.name,n.id));t.pkg0=n,t.settingName=l,s.push(t),o=!0}}}}if(!o&&r.name===n.id&&n._verspec!==i&&!/^file:/.test(n._verspec)&&!/^file:/.test(i)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),r=/^github:/.test(i)&&e.github.parseRepoId(i);if(!t||!r||t.fullName!==r.fullName||r.tag&&e.semver.strcmp(t.tag,r.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (installed: {1}, installing: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,s.push(t)}}}))}return Object.keys(r.dependencies).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,r.dependencies[t]))).then((e=>s.push.apply(s,e)))),Promise.resolve())})).then((()=>{const t=e=>{const n=[];return e.addedBy.forEach((e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))})),n},n=[];return s.forEach((s=>{n.push.apply(n,t(s.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(s.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (installed: {1}, installing: {2})",t.id,r.name,s.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",s.settingName,r.name,s.pkg0.id));return n.pkg0=t,n})))})),s.push.apply(s,n),s=s.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===s[n].pkg0.id)return!1;return!0})),s}))}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const i=JSON.stringify(this.config);for(const t in this.config.dependencies){const n=e.patching.upgradePackageReference(this.targetVersion(),t,this.config.dependencies[t]);n!=t&&(delete this.config.dependencies[t],n&&(this.config.dependencies[n]="*"))}n&&(this.config.targetVersions={target:n}),JSON.stringify(this.config)!=i&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter((t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core)));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach((t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]})))}resolvedDependencies(){return Object.keys(this.dependencies()).map((e=>this.resolveDep(e)))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,((t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}loadAsync(t=!1,i){if(this.isLoaded)return Promise.resolve();let r=Promise.resolve();0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const s=this.readFile(e.CONFIG_NAME);null==s?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):r=r.then((()=>this.parseConfig(s))),0!=this.level||t||(r=r.then((()=>this.upgradePackagesAsync().then((()=>{}))))),t&&(r=r.then((()=>this.downloadAsync()))),0==this.level&&t&&(r=r.then((()=>this.upgradePackagesAsync())).then((t=>t?(Object.keys(t).forEach((t=>e.tickEvent("package.doubleload",{extension:t}))),e.log("upgraded, downloading again"),e.debug(t),this.downloadAsync()):Promise.resolve()))),e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&(r=r.then((()=>this.patchCorePackage()))),r=r.then((()=>{if(this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")<0)return;const t=e.appTarget.simulator.boardDefinition=JSON.parse(this.readFile("board.json"));t.id=this.config.name,e.appTarget.appTheme.boardName=t.boardName||lf("board"),e.appTarget.appTheme.driveDisplayName=t.driveDisplayName||lf("DRIVE");let n=t=>{let n=/^pkg:\/\/(.*)/.exec(t);if(n){let t=n[1],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}})));const o=(t,n)=>{var i;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const r=e.github.parseRepoId(t._verspec),s=e.github.parseRepoId(n);if((null==r?void 0:r.slug)&&(null==r?void 0:r.slug)===(null==s?void 0:s.slug)){const o=(null==r?void 0:r.tag)||(null===(i=t.config)||void 0===i?void 0:i.version),a=e.semver.strcmp(o,s.tag);if(0==a)return void e.debug(`resolved version are ${o}`);if(a<0)return void e.debug(`auto-upgraded ${n} to ${o}`)}}/^file:/.test(t._verspec)||/^file:/.test(n)?e.debug("ignore file: mismatch issues"):t.configureAsInvalidPackage(lf("version mismatch"))},a=async(i,r,s=!1)=>{i||(i=r.dependencies(s)),e.debug(`deps: ${r.id}->${Object.keys(i).join(", ")}`),i=e.github.resolveMonoRepoVersions(i),e.debug(`deps: resolved ${r.id}->${Object.keys(i).join(", ")}`);for(let a of Object.keys(i)){let l=i[a]||"*";e.debug(`dep: load ${r.id}.${a}${s?"++":""}: ${l}`),"hw"==a&&e.hwVariant&&(a="hw---"+e.hwVariant);let c=r.resolveDep(a);if(c){if(c.invalid()||c._verspec===l||o(c,l),c.invalid()){c.level=Math.min(c.level,r.level+1),c.addedBy.push(r);continue}s||(c.level=Math.min(c.level,r.level+1),c.addedBy.push(r))}else{let e=new n(a,l,r.parent,r);s&&(e.cppOnly=!0),r.parent.deps[a]=e,r.parent.deps[a.replace(/---.*/,"")]=e,await e.loadAsync(t)}}};return r.then((()=>a(null,this))).then((()=>{if(this.config.palette&&e.appTarget.runtime&&(e.appTarget.runtime.palette=e.U.clone(this.config.palette),this.config.paletteNames&&(e.appTarget.runtime.paletteNames=this.config.paletteNames)),this.config.screenSize&&e.appTarget.runtime&&(e.appTarget.runtime.screenSize=e.U.clone(this.config.screenSize)),0===this.level){const t=this.readFile(e.MAIN_TS);if(!t)return Promise.resolve(null);const n=this.getMissingPackages(this.config,t);let i=!1;return Object.keys(n).reduce(((t,r)=>t.then((()=>this.findConflictsAsync(r,n[r]))).then((t=>{if(t.length){const n=t.map((e=>e.pkg0.id)).join(", "),i=t.map((e=>e.settingName)).filter((e=>!!e)).join(", ");return e.log(`skipping missing package ${r} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`),Promise.resolve(null)}{e.log(`adding missing package ${r}`),i=!0,this.config.dependencies[r]="*";const t={};return t[r]=n[r],a(t,this)}}))),Promise.resolve(null)).then((()=>(i&&(this.saveConfig(),this.validateConfig()),Promise.resolve(null))))}return Promise.resolve(null)})).then((()=>0!=this.level?Promise.resolve():Promise.all(e.U.values(this.parent.deps).map((e=>a(null,e,!0)))))).then((()=>{e.debug(` installed ${this.id}`)}))}getFiles(){let t;t=0!=this.level||this.ignoreTests?this.config.files.slice(0):this.config.files.concat(this.config.testFiles||[]);const i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const r=i=>{if("!"==(i=i.trim())[0])return!r(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const s=/^target:(\w+)$/.exec(i);return s?s[1]==e.appTarget.id||s[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},s=e.U.lookup(i,t);return!s||!s.trim()||s.split("||").some((e=>e.split("&&").every(r)))}))),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some((t=>e.U.endsWith(i,t)))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],r={},s=e.appTarget.appTheme||{};return this.config.skipLocalization?Promise.resolve(r):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map((i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`,s.crowdinBranch).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(r,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(r,this.bundledStringsForFile(t,i)))})).catch((s=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(r,this.bundledStringsForFile(t,i))}))))).then((()=>r))):(i.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(r,t))),Promise.resolve(r))}bundledStringsForFile(t,n){let i={},[r,s,o]=e.Util.normalizeLanguageCode(t);const a=this.config.files;let l=`_locales/${r}/${n}-strings.json`;return a.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):o&&(l=`_locales/${o}/${n}-strings.json`,a.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):s&&(l=`_locales/${s}/${n}-strings.json`,a.indexOf(l)>-1&&(i=JSON.parse(this.readFile(l))))),i}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let r=e[i];"string"==typeof r&&(r={data:r});let s=r.namespace||n.namespace||"";s&&(s+=".");let o=r.id||s+i,a=r.icon,l=r.mimeType||n.mimeType,c=r.dataEncoding||n.dataEncoding||"base64";a||"base64"!=c||"image/png"!=l&&"image/jpeg"!=l||(a="data:"+l+";base64,"+r.data),t[o]={id:o,data:r.data,dataEncoding:c,icon:a,namespace:s,mimeType:l,tilemapTile:r.tilemapTile,displayName:r.displayName,tileset:r.tileset}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",null,null),this._host=e,this.deps={},this.parent=this,this.addedBy=[this],this.level=0,this.deps[this.id]=this}installAllAsync(e){return this.loadAsync(!0,e)}sortedDeps(t=!1){let n={},i=[];const r=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,s=o=>{if(!o||e.U.lookup(n,o.id))return;n[o.id]=!0;const a=Object.keys(o.dependencies(t)).map((e=>this.resolveDep(e)));a.sort(((t,n)=>r(n)-r(t)||e.U.strcmp(t.id,n.id))),a.forEach(s),i.push(o.id)};return s(this),i.map((e=>this.resolveDep(e)))}localizationStringsAsync(t){const n={};return Promise.all(e.Util.values(this.deps).map((e=>e.packageLocalizationStringsAsync(t).then((e=>{e&&Object.keys(e).forEach((t=>{n[t]||(n[t]=e[t])}))}))))).then((()=>{const t=e.U.getLocalizedStrings();return Object.keys(n).forEach((i=>{(e.U.startsWith(i,"{id:subcategory}")||e.U.startsWith(i,"{id:group}"))&&(t[i]||(t[i]=n[i]))})),e.U.setLocalizedStrings(t),Promise.resolve(n)}))}getTargetOptions(){let t=e.U.clone(e.appTarget.compile);return e.U.assert(!!t),t.utf8||this.sortedDeps(!0).forEach((n=>{n.config&&n.config.utf8&&(e.debug("forcing utf8 mode: pkg="+n.id),t.utf8=!0)})),t}getJRes(){if(!this._jres){this._jres={};for(const e of this.sortedDeps())e.parseJRes(this._jres);const t=(e.appTarget.runtime&&e.appTarget.runtime.palette?e.appTarget.runtime.palette:["#000000","#ffffff"]).map((e=>("000000"+parseInt(e.replace(/#/,""),16).toString(16)).slice(-6))).join("");this._jres.__palette={id:"__palette",data:t,dataEncoding:"hex",mimeType:"application/x-palette"}}return this._jres}updateJRes(){this._jres&&this.parseJRes(this._jres)}resolveBannedCategories(){if(void 0!==this._resolvedBannedCategories)return this._resolvedBannedCategories;let t=[];return e.appTarget&&e.appTarget.runtime&&e.appTarget.runtime.bannedCategories&&e.appTarget.runtime.bannedCategories.length&&(t=e.appTarget.runtime.bannedCategories.slice(),Object.keys(this.deps).map((e=>this.deps[e])).filter((e=>!!e)).map((t=>e.Util.jsonTryParse(t.readFile(e.CONFIG_NAME)))).filter((e=>e&&e.requiredCategories)).forEach((e=>e.requiredCategories.forEach((e=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)})))),this._resolvedBannedCategories=t),this._resolvedBannedCategories=t,this._resolvedBannedCategories.length||(this._resolvedBannedCategories=null),this._resolvedBannedCategories}async getCompileOptionsAsync(t=this.getTargetOptions()){let n={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const i=(t,n)=>{this.config.files.indexOf(t)<0&&e.U.userError(lf("please add '{0}' to \"files\" in {1}",t,e.CONFIG_NAME)),n="// Auto-generated. Do not edit.\n"+n+"\n// Auto-generated. Do not edit. Really.\n",this.host().readFile(this,t,!0)!==n&&(e.debug(`updating ${t} (size=${n.length})...`),this.host().writeFile(this,t,n,!0))};let r=!1;const s=async n=>{const s={extinfo:null,target:null},o=e.appTargetVariant;n&&e.setAppTargetVariant(n,{temporary:!0});try{let a=e.cpp.getExtensionInfo(this);r||!a.shimsDTS&&!a.enumsDTS||(r=!0,a.shimsDTS&&i("shims.d.ts",a.shimsDTS),a.enumsDTS&&i("enums.d.ts",a.enumsDTS));const l=t.isNative?await this.host().getHexInfoAsync(a):null;a=e.U.flatClone(a),t.keepCppFiles||(delete a.compileData,delete a.generatedFiles,delete a.extensionFiles),a.hexinfo=l,s.extinfo=a,s.target=e.appTarget.compile}finally{n&&e.setAppTargetVariant(o,{temporary:!0})}return s};let o;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),n.target.preferredEditor=this.getPreferredEditor(),e.debug(`building: ${this.sortedDeps().map((e=>e.config.name)).join(", ")}`),o=e.appTarget.multiVariants?e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]]:[null];let a=null;for(let t of o){a&&e.debug(`building for ${t}`);const i=await s(t),r=i.extinfo;r.appVariant=t,r.outputPrefix=1!=o.length&&t?t+"-":"",a?n.otherMultiVariants.push(i):(a=r,n.otherMultiVariants=[])}n.extinfo=a;if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),i=JSON.stringify({name:this.config.name,comment:this.config.description,status:"unpublished",scriptId:this.installedVersion,cloudId:e.CLOUD_ID+e.appTarget.id,editor:this.getPreferredEditor(),targetVersions:e.appTarget.versions}),r=JSON.stringify(t),s=await e.lzmaCompressAsync(i+r);s&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:i.length,textSize:r.length,name:this.config.name,eURL:e.appTarget.appTheme.embedUrl,eVER:e.appTarget.versions?e.appTarget.versions.target:"",pxtTarget:e.appTarget.id}),n.embedBlob=ts.pxtc.encodeBase64(e.U.uint8ArrayToString(s)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let i=t;e.level>0&&(i="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(i),n.fileSystem[i]=e.readFile(t)}n.jres=this.getJRes();const l=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;return n.allowedArgumentTypes=l&&l.extraFunctionEditorTypes&&l.extraFunctionEditorTypes.map((e=>e.typeName)).concat("number","boolean","string"),n}prepareConfigToBePublished(){const t=e.U.clone(this.config);return delete t.installedVersion,delete t.additionalFilePath,delete t.additionalFilePaths,t.targetVersions||(t.targetVersions=e.Util.clone(e.appTarget.versions)),e.U.iterMap(t.dependencies,((n,i)=>{if(!i||/^(file|workspace):/.test(i)){i="*";try{const t=this.resolveDep(n).readGitJson();if(t&&t.repo){let n=e.github.parseRepoId(t.repo);n.tag=t.commit.tag||t.commit.sha,i=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=i}})),t}filesToBePublishedAsync(t=!1){const n={};return this.loadAsync().then((()=>{t||this.config.public||e.U.userError('Only packages with "public":true can be published');const i=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(i);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let i=this.readFile(t);null==i&&e.U.userError("referenced file missing: "+t),n[t]=i}return e.U.sortObjectFields(n)}))}saveToJsonAsync(){return this.filesToBePublishedAsync(!0).then((t=>({meta:{cloudId:e.CLOUD_ID+e.appTarget.id,targetVersions:e.appTarget.versions,editor:this.getPreferredEditor(),name:this.config.name},source:JSON.stringify(t,null,2)})))}compressToFileAsync(){return this.saveToJsonAsync().then((t=>e.lzmaCompressAsync(JSON.stringify(t,null,2))))}computePartDefinitions(t){if(!t||!t.length)return{};let n={};return this.sortedDeps().forEach((i=>{let r=i.readFile("pxtparts.json");if(r)try{let s=JSON.parse(r);Object.keys(s).forEach((r=>{if(t.indexOf(r)>=0){let t=n[r]=s[r];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=i.readFile(t.visual.image);n||e.reportError("parts","invalid part definition",{error:`missing visual ${t.visual.image}`}),/^data:image\/svg\+xml/.test(n)||(n="data:image/svg+xml,"+encodeURIComponent(n)),t.visual.image=n}}}))}catch(t){e.reportError("parts","invalid pxtparts.json file")}})),n}},e.inflateJRes=i,e.allPkgFiles=function(t){return[e.CONFIG_NAME].concat(t.files||[]).concat(t.testFiles||[])},e.isPkgBeta=function(e){return e&&/\bbeta\b/.test(e.description)}}(pxt||(pxt={})),function(e){!function(t){let n,i,r,s,o,a=()=>{};function l(){if(o)return o;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const r=n;t=t.then((()=>r.disconnectAsync())).then((()=>r.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{i=void 0,n=void 0,o=void 0})),a&&(t=t.then((()=>a()))),o=t}return t}t.isActive=function(){return!!n},t.isConnected=function(){return!!n&&n.io.isConnected()},t.isConnecting=function(){return!!n&&n.io.isConnecting()},t.icon=function(){var t;return!!n&&(n.icon||(null===(t=e.appTarget.appTheme.downloadDialogTheme)||void 0===t?void 0:t.deviceIcon)||"usb")},t.unsupportedParts=function(){return(null==n?void 0:n.unsupportedParts)?n.unsupportedParts():[]},t.disconnectAsync=l,t.configureEvents=function(e,t,i){a=e,r=t,s=i,n&&(n.io.onConnectionChanged=a,n.onSerial=r,n.onCustomEvent=i)},t.sendCustomEventAsync=function(e,t){return n?n.sendCustomEventAsync(e,t):Promise.resolve()},t.initAsync=function(o=!1){if(e.debug("packetio: init "+(o?"(force)":"")),!i){let c=Promise.resolve();o&&(c=c.then((()=>l()))),i=c.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=a,n=t.mkPacketIOWrapper(e),r&&(n.onSerial=r),s&&(n.onCustomEvent=s),a&&a(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{i=void 0}))}return i}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){t.computePatches=function(t,n){const i=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(!i)return;const r=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let s=[];return Object.keys(i).filter((t=>e.semver.inRange(t,r))).forEach((e=>s=s.concat(i[e]))),n&&(s=s.filter((e=>e.type==n))),s.length?s:void 0},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const r=e.patching.computePatches(t,"package");let s=n;return r&&r.forEach((e=>{Object.keys(e.map).forEach((t=>{s==t&&(s=e.map[t])}))})),s},t.patchJavaScript=function(t,n){const i=e.patching.computePatches(t);let r=n;return i&&(i.filter((e=>"api"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp(t,"g");r=r.replace(n,e.map[t])}))})),i.filter((e=>"userenum"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");r=r.replace(n,`enum ${e.map[t]} {`);const i=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");r=r.replace(i,`$1${e.map[t]}$2`)}))}))),r}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let r=0;r<t.pre.length+1;++r){let s=t.pre[r],o=n.pre[r];if(!s)return o?-1:0;if(!o)return 1;if(/^\d+$/.test(s)){if(!/^\d+$/.test(o))return-1;if(i=parseInt(s)-parseInt(o),i)return i}else{if(/^\d+$/.test(o))return 1;if(i=e.U.strcmp(s,o),i)return i}}return 0}return-1}return n?1:0}function i(t,n){let i=r(t)||r(n);return i||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),i}function r(e){if(!e)return null;if("*"===e)return{major:Number.MAX_SAFE_INTEGER,minor:Number.MAX_SAFE_INTEGER,patch:Number.MAX_SAFE_INTEGER,pre:[],build:[]};/^v\d/i.test(e)&&(e=e.slice(1));let t=/^(\d+)\.(\d+)\.(\d+)(-([0-9a-zA-Z\-\.]+))?(\+([0-9a-zA-Z\-\.]+))?$/.exec(e);return t?{major:parseInt(t[1]),minor:parseInt(t[2]),patch:parseInt(t[3]),pre:t[5]?t[5].split("."):[],build:t[7]?t[7].split("."):[]}:null}function s(e){let t=e.major+"."+e.minor+"."+e.patch;return e.pre.length&&(t+="-"+e.pre.join(".")),e.build.length&&(t+="+"+e.build.join(".")),t}function o(t,i){let s=r(t),o=r(i);return s||o?n(s,o):e.U.strcmp(t,i)}function a(e,t){let i=e.split(" - ");if(2!=i.length)return!1;let s=r(i[0]),o=r(i[1]);if(!s||!o)return!1;if(!t)return!0;const a=n(s,t),l=n(t,o);return a<=0&&l<0}t.cmp=n,t.parse=i,t.tryParse=r,t.normalize=function(e){return s(i(e))},t.stringify=s,t.majorCmp=function(e,t){let n=r(e),i=r(t);return n.major-i.major},t.strcmp=o,t.inRange=a,t.sortLatestTags=function(e){const n=e.filter((e=>!!t.tryParse(e)));return n.sort(o),n.reverse(),n},t.test=function(){console.log("Test semver");let t=["0.9.0","1.0.0-0.3.7","1.0.0-alpha","1.0.0-alpha.1","1.0.0-alpha.beta","1.0.0-beta","1.0.0-beta.2","1.0.0-beta.11","1.0.0-rc.1","1.0.0-x.7.z.92","1.0.0","1.0.1","1.9.0","1.10.0","1.11.0"];for(let r=0;r<t.length;++r){let o=i(t[r]);console.log(t[r],o),e.U.assert(s(o)==t[r]);for(let s=0;s<t.length;++s){let a=n(o,i(t[s]));console.log(t[r],t[s],a),r<s?e.U.assert(a<0):r>s?e.U.assert(a>0):e.U.assert(0==a)}}const o=r("1.2.3");e.U.assert(a("0.1.2 - 2.2.3",o)),e.U.assert(a("1.2.3 - 2.2.3",o)),e.U.assert(!a("0.0.0 - 1.2.3",o)),e.U.assert(!a("1.2.4 - 4.2.3",o)),e.U.assert(!a("0.0.0 - 0.0.1",o))}}(e.semver||(e.semver={}))}(pxt||(pxt={})),function(e){!function(e){function t(t){return e.Util.values(t.byQName).filter((e=>e.attributes.block&&/^{[^:]+:[^}]+}/.test(e.attributes.block))).forEach((e=>{e.attributes.block=e.attributes.block.replace(/^{[^:]+:[^}]+}/,"")})),t}e.assert=e.Util.assert,e.oops=e.Util.oops,e.U=e.Util,e.ON_START_TYPE="pxt-on-start",e.ON_START_COMMENT="on start",e.HANDLER_COMMENT="code goes here",e.TS_STATEMENT_TYPE="typescript_statement",e.TS_DEBUGGER_TYPE="debugger_keyword",e.TS_BREAK_TYPE="break_keyword",e.TS_CONTINUE_TYPE="continue_keyword",e.TS_OUTPUT_TYPE="typescript_expression",e.TS_RETURN_STATEMENT_TYPE="function_return",e.PAUSE_UNTIL_TYPE="pxt_pause_until",e.COLLAPSED_BLOCK="pxt_collapsed_block",e.FUNCTION_DEFINITION_TYPE="function_definition",e.BINARY_JS="binary.js",e.BINARY_ASM="binary.asm",e.BINARY_HEX="binary.hex",e.BINARY_UF2="binary.uf2",e.BINARY_ELF="binary.elf",e.BINARY_PXT64="binary.pxt64",e.BINARY_ESP="binary.bin",e.BINARY_SRCMAP="binary.srcmap",e.NATIVE_TYPE_THUMB="thumb",e.NATIVE_TYPE_VM="vm",e.BuildSourceMapHelpers=function(e,t,n){const i=e=>{const t=e.split("\n").map((e=>e.length)),n=t.reduce((({lens:e,sum:t},n)=>({lens:[...e,t+n+1],sum:t+n+1})),{lens:[],sum:0}).lens;return{posToLineCol:e=>{const i=n.reduce(((t,n,i)=>e<n?t:i+1),0);return[i,t[i]-(n[i]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},r={ts:i(t),py:i(n)},s=e=>e.endPos-e.startPos,o=(t,n)=>{const{startPos:i,endPos:r}=t;return e.filter((e=>e[n].startPos<=i&&r<=e[n].endPos))},a=(e,t)=>{const n=o(e,t);return n.reduce(((e,n)=>s(n[t])<s(e[t])?n:e),n[0])},l={ts:{allOverlaps:e=>o(e,"ts"),smallestOverlap:e=>a(e,"ts")},py:{allOverlaps:e=>o(e,"py"),smallestOverlap:e=>a(e,"py")}},c=(e,t)=>n=>{const[i,o]=(t=>[r[e].lineColToPos(t.line,t.column),t.length])(n),l=a({startPos:i,endPos:i+o},e);if(!l)return;const[c,u]=r[t].posToLineCol(l[t].startPos);return{fileName:`main.${t}`,start:l[t].startPos,length:s(l[t]),line:c,column:u}},u=c("ts","py"),d=c("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},r.ts),l.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},r.py),l.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t){if(!e.usedSymbols||!pxt.appTarget.simulator||!pxt.appTarget.simulator.parts)return[];let n=[];if(Object.keys(e.usedSymbols).forEach((t=>{let i=e.usedSymbols[t];if(i&&i.attributes.parts){let e=i.attributes.parts;if(e){e.split(/[ ,]+/).forEach((e=>{0<e.length&&n.indexOf(e)<0&&n.push(e)}))}}})),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?n=n.filter((t=>-1===e.indexOf(t))):"onlybuiltin"===t&&(n=n.filter((t=>e.indexOf(t)>=0))))}return n.sort(),n=n.reverse(),n},e.buildSimJsInfo=function(t){return{js:t.outfiles[e.BINARY_JS],targetVersion:pxt.appTarget.versions.target,fnArgs:t.usedArguments,parts:e.computeUsedParts(t,"ignorebuiltin"),usedBuiltinParts:e.computeUsedParts(t,"onlybuiltin")}},e.blocksCategory=function(t){const n=t?t.attributes.blockNamespace||t.namespace:void 0;return n?e.Util.capitalize(n.split(".")[0]):void 0},e.getBlocksInfo=function(t,n){var i,o;let a=[];const l={},c={},u={},d={},h={};function p(t,n){const i="get"==t,r="set"==t,o="number"==n.retType,d=i?c:r?l:u,h=`${n.namespace}.${n.retType}`;let p=e.U.lookup(d,h);if(!p){const l=`@${t}@`;let c,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,i=t.match(/^([^,.]*),?([^,.]*)$/);i&&3==i.length&&(c=i[1].trim(),u=i[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=c,c=""))}const f=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${c||""}`,m=`value=${u||""}`;p=d[h]={attributes:{blockId:`${o?n.namespace:h}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:i?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:l,namespace:n.namespace,fileName:n.fileName,qName:`${h}.${l}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:i?e.U.lf("the name of the property to read"):e.U.lf("the name of the property to change"),isEnum:!0,type:"@combined@"},{name:"value",description:r?e.U.lf("the new value of the property"):e.U.lf("the amount by which to change the property"),type:n.retType}].slice(0,i?1:2),retType:i?n.retType:"void",combinedProperties:[]},p.attributes.block=i?e.U.lf("%{0} %property",f):r?e.U.lf("set %{0} %property to %{1}",f,m):e.U.lf("change %{0} %property by %{1}",f,m),s(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:r?`set %${f} %property to %${m}`:`change %${f} %property by %${m}`,s(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then((e=>{p.attributes.block=e,s(p.attributes)}))),a.push(p)}p.combinedProperties.push(n.qName)}for(let n of e.Util.values(t.byQName)){if("ENUM_GET"===n.attributes.shim&&n.attributes.enumName&&n.attributes.blockId){let e=!1;if(d[n.attributes.enumName]&&(console.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(console.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(console.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(console.warn(`Enum block ${n.attributes.blockId} should specify enumInitialMembers`),e=!0),e)continue;const t=parseInt(n.attributes.enumStartValue);d[n.attributes.enumName]={blockId:n.attributes.blockId,name:n.attributes.enumName,memberName:n.attributes.enumMemberName,firstValue:isNaN(t)?void 0:t,isBitMask:n.attributes.enumIsBitMask,isHash:n.attributes.enumIsHash,initialMembers:n.attributes.enumInitialMembers,promptHint:n.attributes.enumPromptHint}}if("KIND_GET"===n.attributes.shim&&n.attributes.blockId){const i=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(h[i]){console.warn(`More than one block defined for kind ${i}`);continue}const r=[];if(t.byQName[i])for(const n of e.Util.values(t.byQName))n.namespace===i&&n.attributes.isKind&&r.push(n.name);h[i]={blockId:n.attributes.blockId,name:i,memberName:n.attributes.kindMemberName||i,initialMembers:r,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||p("get",n),n.isReadOnly||("number"==n.retType&&p("change",n),p("set",n));else if(n.attributes.block&&!n.attributes.fixedInstance&&7!=n.kind&&5!=n.kind&&9!=n.kind&&8!=n.kind){if(n.attributes.blockId||(n.attributes.blockId=n.qName.replace(/\./g,"_")),"true"==n.attributes.block){let t=e.U.uncapitalize(n.name);1!=n.kind&&2!=n.kind||(t+=" %"+n.namespace.toLowerCase());const a=null!==(o=null===(i=n.parameters)||void 0===i?void 0:i.filter((e=>!r(e))))&&void 0!==o?o:[];for(let e of a)t+=" %"+e.name;n.attributes.block=t,s(n.attributes)}a.push(n)}}for(let n of a){let i=e.U.lookup(t.byQName,n.namespace);if(!i)continue;let r=i.attributes,s=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===s[e]&&r[e]&&(s[e]=r[e])}var f;return n&&((f=n).length&&(a=a.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)})))),{apis:t,blocks:a,blocksById:pxt.Util.toDictionary(a,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let r=t.substr(n+1);return r=e.U.snakify(r).toUpperCase(),`${i}.${r}`}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,i){const r=e.Util.userLanguage();if("en"==r)return Promise.resolve(t(n));const o=r.toLowerCase(),a=o+"|jsdoc",l=o+"|block",c=await i.localizationStringsAsync(r);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(c,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==r));return await e.Util.promiseMapAll(u,(async t=>{var i,u,d;const h=t.attributes.useLoc||t.attributes.blockAliasFor,p=h&&n.byQName[h];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const f=(e,n)=>{var i,r;return c[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||p&&(c[p.qName+e]||(null===(r=p.attributes.locs)||void 0===r?void 0:r[n]))},m=f("",a);m&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=m),null===(i=t.parameters)||void 0===i||i.forEach((e=>{const t=`|param|${e.name}`,n=f(t,o+t);n&&(e.description=n)}));const g=c["{id:category}"+e.Util.capitalize(t.qName)];let b=c[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[l]);if(!b&&p){const e=c[`${p.qName}|block`]||(null===(d=p.attributes.locs)||void 0===d?void 0:d[l]);t.attributes.block===(p.attributes._untranslatedBlock||p.attributes.block)&&e&&(b=e)}if(b&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=b,b=await pxt.crowdin.inContextLoadAsync(b)),g)t.attributes.block?t.attributes.block=b||t.attributes.block:t.attributes.block=g,s(t.attributes);else if(t.attributes.block&&b){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(b,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:r,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){s(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId)return pxt.debug(`Parameter ${n.actualName} type or shadow block does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.log(`block has non matching arguments: ${n} vs ${t.attributes.block}`),pxt.reportError("loc.errors","invalid translations",{block:t.attributes.blockId,lang:r}),t.attributes.block=n,s(t.attributes))}}else s(t.attributes);t.attributes._translatedLanguageCode=r})),t(n)},e.emptyExtInfo=function(){let e=pxt.appTarget.compileService;e||(e={});const t=!!e.platformioIni,n="dockermake"==e.buildEngine||"dockercross"==e.buildEngine||"dockerespidf"==e.buildEngine,i={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?i.platformio={dependencies:{}}:n?i.npmDependencies={}:i.yotta={config:{},dependencies:{}},i};const n=["weight","imageLiteral","topblockWeight"],i=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable"];function r(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function s(e){if(e.block){const n=e.block.split("||");e._def=t(o(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(o(n[1]))),n[1]&&!e._expandedDef&&pxt.debug("Unable to parse expanded block def for id: "+e.blockId)}function t(t){return e._shadowOverrides&&t.parameters.forEach((t=>{const n=e._shadowOverrides[t.name];"unset"===n?delete t.shadowBlockId:null!=n&&(t.shadowBlockId=n)})),t}}function o(e){const t=[];let n,i=0;for(;i<e.length;i++){const r=e[i],s=i;let o;switch(r){case"*":case"_":const t=d((e=>e==r)),n="_"===r?2:0;1===t.length?o={kind:1<<n,content:t}:2===t.length?o={kind:2<<n,content:t}:3===t.length?o={kind:3<<n,content:t}:i=s;break;case"`":const a=h("`");if(void 0===a){i=s;break}o={kind:256,content:a};break;case"|":o={kind:32};break;case"\\":i<e.length-1&&(o={kind:16,content:e[1+i++]});break;case"[":const l=h("]");if(void 0!==l&&"("===e[1+i++]){const e=h(")");if(void 0!==e){o={kind:512,content:l,type:e};break}}i=s;break;case"$":case"%":const c=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(c.length>2){i=s;break}let u;if("("===e[i+1]){const e=i;++i,u=h(")"),u||(i=e)}o={kind:"$"===r?1024:64,content:c[0],type:c[1],name:u}}o?(n&&t.push({kind:128,content:n}),n=void 0,t.push(o)):n?n+=r:n=r}n&&t.push({kind:128,content:n});const r=[],s=[];let o=[],l=0,c="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=o[o.length-1];if(15&n)if(m(t[e].content),n&l)if(i&n){o.pop(),l^=n;const e=i&l|n&l;e&&o.push(e)}else p();else l|=n,o.push(n);else 144&n?c+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),r.push(n),s.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),r.push(n),s.push(n)}else 256==n?(m(),u.push({kind:"image",uri:t[e].content})):512==n?(m(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&r.push({kind:"break"})}return f(),{parts:r,parameters:s};function d(t,n=!1){let r="";for(n&&i++;i<e.length&&t(e[i]);)r+=e[i],++i;return r&&i--,r}function h(t){const n=d((e=>e!==t),!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)a(n)?(t.push({content:e,styles:0}),t.push(n),e=""):(e+=n.content,n.endingToken&&(e+=n.endingToken));u=t,e&&u.push({content:e,styles:0}),o=[],l=0}function f(){for(m(),l&&p();u.length;){const e=u.shift();if(a(e))r.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),r.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:c,styles:l,endingToken:e}),c=""}}function a(e){return!!e.kind}let l;e.parseCommentString=function(t){let r={paramDefl:{},callingConvention:0,_source:t},o=!0;for(;o;)o=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,i,s,a,l,c)=>{let u=a?JSON.parse(a):i?a||l||c:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))r.locs||(r.locs={}),r.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))r.locs||(r.locs={}),r.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){r.locs||(r.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);r.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?r.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:r.paramDefl[n.slice(0,n.length-5)]=u,r.explicitDefaults||(r.explicitDefaults=[]),r.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))r._shadowOverrides||(r._shadowOverrides={}),r._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".fieldEditor"))r.paramFieldEditor||(r.paramFieldEditor={}),r.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){r.paramFieldEditorOptions||(r.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);r.paramFieldEditorOptions[e]||(r.paramFieldEditorOptions[e]={}),r.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){r.paramShadowOptions||(r.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);r.paramShadowOptions[e]||(r.paramShadowOptions[e]={}),r.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(r.paramMin||(r.paramMin={}),r.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(r.paramMax||(r.paramMax={}),r.paramMax[n.slice(0,n.length-4)]=u):r[n]=u;return o=!0,"//% "}));for(let e of n)"string"==typeof r[e]&&(r[e]=parseInt(r[e]));for(let e of i)"string"==typeof r[e]&&(r[e]="true"==r[e]||"1"==r[e]);if(r.trackArgs&&(r.trackArgs=r.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),r.enumInitialMembers&&(r.enumInitialMembers=r.enumInitialMembers.split(/[ ,]+/)),r.blockExternalInputs&&!r.inlineInputMode&&(r.inlineInputMode="external"),r.paramHelp={},r.jsDoc="",t=t.replace(/\/\*\*([^]*?)\*\//g,((e,t)=>(t=(t=t.replace(/\n\s*(\*\s*)?/g,"\n")).replace(/^\s*@param\s+(\w+)\s+(.*)$/gm,((e,t,n)=>{if(r.paramHelp[t]=n,!r.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(n);if(e&&e[1]){let n=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(n){let e=n[1]||n[2]||n[3];e||(e=""),e.indexOf(" ")>-1?r.paramDefl[t]=`"${e}"`:r.paramDefl[t]=e}}}return""})),r.jsDoc+=t,""))),r.jsDoc=r.jsDoc.trim(),r.async&&(r.callingConvention=1),r.promise&&(r.callingConvention=2),r.jres&&(r.whenUsed=!0),r.subcategories)try{r.subcategories=JSON.parse(r.subcategories)}catch(e){r.subcategories=void 0}if(r.groups)try{r.groups=JSON.parse(r.groups)}catch(e){r.groups=void 0}if(r.groupIcons)try{r.groupIcons=JSON.parse(r.groupIcons)}catch(e){r.groupIcons=void 0}if(r.groupHelp)try{r.groupHelp=JSON.parse(r.groupHelp)}catch(e){r.groupHelp=void 0}return s(r),r},e.parameterTypeIsArrowFunction=r,e.updateBlockDef=s,e.parseBlockDefinition=o,e.parseChecksumBlock=function(e,t=0){let n=pxt.HF2.read32(e,t);if(133083260!=(2147483647&n))return pxt.log("no checksum block magic"),null;let i=pxt.HF2.read32(e,t+4),r=pxt.HF2.read32(e,t+8);if(3&i)return pxt.log("invalid end marker position"),null;let s=1<<(255&r);if(s!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+s),null;let o={magic:n,endMarkerPos:i,endMarker:r,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:s*pxt.HF2.read16(e,n),length:s*pxt.HF2.read16(e,n+2),checksum:pxt.HF2.read32(e,n+4)};if(!t.length||!t.checksum)break;o.regions.push(t)}return o},function(t){function n(n){let i=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||i(0)!=t.UF2_MAGIC_START0||i(4)!=t.UF2_MAGIC_START1||i(n.length-4)!=t.UF2_MAGIC_END)return null;let r=i(8),s=i(16);s>476&&(s=256);let o=null,a=0,l=0;if(r&t.UF2_FLAG_FILE){let t=n.slice(32+s),r=t.indexOf(0);r>=0&&(t=t.slice(0,r)),o=e.U.fromUTF8Array(t),l=i(28)}return r&t.UF2_FLAG_FAMILY_ID_PRESENT&&(a=i(28)),{flags:r,targetAddr:i(12),payloadSize:s,blockNo:i(20),numBlocks:i(24),fileSize:l,familyId:a,data:n.slice(32,32+s),filename:o}}function i(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function r(e,t,n){e[t]=255&n,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function s(e){return"string"==typeof e&&(e=parseInt(e)),{currBlock:null,currPtr:-1,blocks:[],ptrs:[],filesize:0,familyId:e||0}}function o(e){for(let t=0;t<e.blocks.length;++t)r(e.blocks[t],20,t),r(e.blocks[t],24,e.blocks.length),e.filename&&r(e.blocks[t],28,e.filesize)}function a(n,i,s,o=0){let l=n.currBlock,c=i>>8,u=256-(255&i);if(s.length>u){let e=new Uint8Array(s);for(a(n,i,e.slice(0,u));u<s.length;){let t=Math.min(u+256,s.length);a(n,i+u,e.slice(u,t)),u=t}return}if(c!=n.currPtr){l=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==c){l=n.blocks[e];break}if(!l){l=new Uint8Array(512),n.filename?o|=t.UF2_FLAG_FILE:n.familyId&&(o|=t.UF2_FLAG_FAMILY_ID_PRESENT),r(l,0,t.UF2_MAGIC_START0),r(l,4,t.UF2_MAGIC_START1),r(l,8,o),r(l,12,c<<8),r(l,16,256),r(l,20,n.blocks.length),r(l,28,n.familyId),r(l,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)l[e]=255;n.filename&&e.U.memcpy(l,288,e.U.toUTF8Array(n.filename)),n.blocks.push(l),n.ptrs.push(c)}n.currPtr=c,n.currBlock=l}let d=32+(255&i);for(let e=0;e<s.length;++e)l[d+e]=s[e];n.filesize=Math.max(n.filesize,s.length+i)}t.UF2_MAGIC_START0=171066965,t.UF2_MAGIC_START1=2656915799,t.UF2_MAGIC_END=179400496,t.UF2_FLAG_NONE=0,t.UF2_FLAG_NOFLASH=1,t.UF2_FLAG_FILE=4096,t.UF2_FLAG_FAMILY_ID_PRESENT=8192,t.parseBlock=n,t.parseFile=function(e){let t=[];for(let i=0;i<e.length;i+=512){let r=n(e.slice(i,i+512));r&&t.push(r)}return t},t.toBin=function(e,t){if(e.length<512)return null;let i=-1,r=-1,s=[];for(let o=0;o<e.length;++o){let a=512*o,l=n(e.slice(a,a+512));if(!l)continue;if(t&&l.targetAddr+256>t)break;-1==i&&(i=l.targetAddr,r=i);let c=l.targetAddr-i;c<0||c%4||c>1048576||(c>0&&s.push(new Uint8Array(c)),s.push(e.slice(a+32,a+32+l.payloadSize)),i=l.targetAddr+l.payloadSize)}let o=0;for(let e of s)o+=e.length;if(0==o)return null;let a=new Uint8Array(o),l=0;for(let e of s)for(let t=0;t<e.length;++t)a[l++]=e[t];return{buf:a,start:r}},t.readBytes=function(e,t,n){let r,s=new Uint8Array(n);for(let o=0;o<n;++o,++t)i(r,t)||(r=e.filter((e=>i(e,t)))[0]),r&&(s[o]=r.data[t-r.targetAddr]);return s},t.newBlockFile=s,t.finalizeFile=o,t.concatFiles=function(t){for(let e of t)o(e),e.filename=null;let n=s();n.blocks=e.U.concat(t.map((e=>e.blocks)));for(let e of t)e.blocks=[];return n},t.serializeFile=function(t){o(t);let n="";for(let i of t.blocks)n+=e.Util.uint8ArrayToString(i);return n},t.readBytesFromFile=function t(n,i,r){let s,o=i>>8;if(o==n.currPtr)s=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==o){s=n.blocks[e];break}s&&(n.currPtr=o,n.currBlock=s)}if(!s)return null;let a=new Uint8Array(r),l=Math.min(r,256-(255&i));e.U.memcpy(a,0,s,32+(255&i),l);let c=r-l;if(c>0){let r=t(n,i+l,c);e.U.memcpy(a,l,r)}return a},t.writeBytes=a,t.writeHex=function(e,t){let n="0000";for(let i=0;i<t.length;++i){let r=/:02000004(....)/.exec(t[i]);if(r&&(n=r[1]),r=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[i]),r){let t=parseInt(n+r[1],16),i=r[2],s=[];for(let e=0;e<i.length;e+=2)s.push(parseInt(i[e]+i[e+1],16));a(e,t,s)}}}}(l=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i;!function(e){e[e.IDE=0]="IDE",e[e.Sandbox=1]="Sandbox",e[e.Widget=2]="Widget",e[e.Controller=3]="Controller"}(n=t.EditorLayoutType||(t.EditorLayoutType={}));let r=!1,s=!1;function o(){if(void 0===i){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),o=/nosandbox=1/i.test(window.location.href),a=/controller=1/i.test(window.location.href)&&e.BrowserUtils.isIFrame(),l=/readonly=1/i.test(window.location.href),c=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),u=/noproject=1/i.test(window.location.href);if(i=n.IDE,o?i=n.Widget:a?i=n.Controller:t&&(i=n.Sandbox),a&&l&&(r=!0),a&&u&&(s=!0),c)switch(c[1].toLowerCase()){case"widget":i=n.Widget;break;case"sandbox":i=n.Sandbox;break;case"ide":i=n.IDE}}else i=n.Sandbox;e.debug(`shell: layout type ${n[i]}, readonly ${l()}`)}}function a(){return o(),i==n.Sandbox}function l(){return!e.BrowserUtils.hasWindow()||a()&&!/[?&]edit=1/i.test(window.location.href)||c()&&r}function c(){return o(),i==n.Controller}t.layoutTypeClass=function(){return o(),e.shell.EditorLayoutType[i].toLowerCase()},t.isSandboxMode=a,t.isReadOnly=l,t.isNoProject=function(){return s},t.isControllerMode=c,t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,((e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))}))}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then((e=>e.map((e=>e.project)).filter((e=>!e.deleted))))}deleteProjectAsync(e){return this.getProjectAsync(e).then((e=>{e.deleted=!0,this.saveProjectAsync(e)}))}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then((e=>{var t;return null===(t=e)||void 0===t?void 0:t.project}))}saveProjectAsync(e){return this.db.setAsync(n.projectTable,{id:e.header.id,project:e})}getUserStateAsync(){return this.db.getAsync(n.userTable,"local-user").then((e=>{var t;return null===(t=e)||void 0===t?void 0:t.user}))}saveUserStateAsync(e){return this.db.setAsync(n.userTable,{id:"local-user",user:e})}}n.version=6,n.databaseName="local-skill-map",n.projectTable="projects",n.projectKey="id",n.userTable="users",n.userKey="id",t.IndexedDBWorkspace=n}(e.skillmap||(e.skillmap={}))}(pxt||(pxt={})),function(e){!function(t){t.createStreamAsync=function(t,n){return e.Cloud.privatePostAsync("streams",{target:t,name:n||"data"}).then((e=>e))},t.postPayloadAsync=function(t,n){return e.Util.assert(!!t.privatekey),e.Cloud.privatePostAsync(`${t.id}/data?privatekey=${t.privatekey}`,n)}}(e.streams||(e.streams={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class r{constructor(e){this.el=A(e)}attr(e){return Object.keys(e).forEach((t=>{this.setAttribute(t,e[t])})),this}setAttribute(e,t){return this.el.setAttribute(e,t.toString()),this}setAttributeNS(e,t,n){return this.el.setAttributeNS(e,t,n.toString()),this}id(e){return this.setAttribute("id",e)}setClass(...e){return this.setAttribute("class",e.join(" "))}appendClass(t){return e.BrowserUtils.addClass(this.el,t),this}removeClass(t){e.BrowserUtils.removeClass(this.el,t)}title(e){this.titleElement||(this.titleElement=A("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=r;class s extends r{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new g;case"path":return new y;default:return new u(e)}}(e);return this.el.appendChild(t.el),t}element(e,t){return t(this.draw(e)),this}group(){const e=new o;return this.el.appendChild(e.el),e}appendChild(e){this.el.appendChild(e.el)}onDown(e){return t.events.down(this.el,e),this}onUp(e){return t.events.up(this.el,e),this}onMove(e){return t.events.move(this.el,e),this}onEnter(e){return t.events.enter(this.el,e),this}onLeave(e){return t.events.leave(this.el,e),this}onClick(e){return t.events.click(this.el,e),this}}t.DrawContext=s;t.SVG=class extends s{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new l(this.el)),e(this.defs),this}};class o extends s{constructor(e){super("g"),e&&e.appendChild(this.el)}translate(e,t){return this.left=e,this.top=t,this.updateTransform()}scale(e){return this.scaleFactor=e,this.updateTransform()}def(){return new l(this.el)}style(){return new c(this.el)}updateTransform(){let e="";return null!=this.left&&(e+=`translate(${this.left} ${this.top})`),null!=this.scaleFactor&&(e+=` scale(${this.scaleFactor})`),this.setAttribute("transform",e),this}}t.Group=o;class a extends s{constructor(){super("pattern")}units(e){return this.setAttribute("patternUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}contentUnits(e){return this.setAttribute("patternContentUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}size(e,t){return this.setAttribute("width",e),this.setAttribute("height",t),this}}t.Pattern=a;class l extends r{constructor(e){super("defs"),e.appendChild(this.el)}create(e,t){let n;switch(e){case"path":n=new y;break;case"pattern":n=new a;break;case"radialGradient":n=new x;break;case"linearGradient":n=new w;break;case"clipPath":n=new k;break;default:n=new r(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=l;class c extends r{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=c;class u extends s{at(e,t){return this.setAttribute("x",e),this.setAttribute("y",t),this}moveTo(e,t){return this.at(e,t)}fill(e,t){return this.setAttribute("fill",e),null!=t&&this.opacity(t),this}opacity(e){return this.setAttribute("fill-opacity",e)}stroke(e,t){return this.setAttribute("stroke",e),null!=t&&this.strokeWidth(t),this}strokeWidth(e){return this.setAttribute("stroke-width",e)}strokeOpacity(e){return this.setAttribute("stroke-opacity",e)}clipPath(e){return this.setAttribute("clip-path",e)}}t.Drawable=u;class d extends u{constructor(e){super("text"),null!=e&&this.text(e)}text(e){return this.el.textContent=e,this}fontFamily(e){return this.setAttribute("font-family",e)}fontSize(e,t){return this.setAttribute("font-size",E(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",E(e,n)),0!==t&&this.setAttribute("dy",E(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class h extends u{constructor(){super("rect")}width(e,t=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}corner(e){return this.corners(e,e)}corners(e,t){return this.setAttribute("rx",e),this.setAttribute("ry",t),this}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}}t.Rect=h;class p extends u{constructor(){super("circle")}at(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}radius(e){return this.setAttribute("r",e)}}t.Circle=p;class f extends u{constructor(){super("line")}at(e,t,n,i){return this.from(e,t),null!=n&&null!=i&&this.to(n,i),this}from(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}to(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.Line=f;class m extends u{points(e){return this.setAttribute("points",e)}with(e){return this.points(e.map((({x:e,y:t})=>e+" "+t)).join(","))}}t.PolyElement=m;class g extends m{constructor(){super("polyline")}}t.Polyline=g;class b extends m{constructor(){super("polygon")}}t.Polygon=b;class y extends u{constructor(){super("path"),this.d=new T}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}}t.Path=y;t.Image=class extends u{constructor(){super("image")}src(e){return this.setAttributeNS("http://www.w3.org/1999/xlink","href",e)}width(e,t=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}};class v extends r{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const i=A("stop");return i.setAttribute("offset",e+"%"),null!=t&&i.setAttribute("stop-color",t),null!=n&&i.setAttribute("stop-opacity",n),this.el.appendChild(i),this}}t.Gradient=v;class w extends v{constructor(){super("linearGradient")}start(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}end(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.LinearGradient=w;class x extends v{constructor(){super("radialGradient")}center(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}focus(e,t,n){return this.setAttribute("fx",e),this.setAttribute("fy",t),this.setAttribute("fr",n),this}radius(e){return this.setAttribute("r",e)}}t.RadialGradient=x;class k extends s{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function A(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=k;class T{constructor(){this.ops=[]}clear(){this.ops=[]}moveTo(e,t){return this.op("M",e,t)}moveBy(e,t){return this.op("m",e,t)}lineTo(e,t){return this.op("L",e,t)}lineBy(e,t){return this.op("l",e,t)}cCurveTo(e,t,n,i,r,s){return this.op("C",e,t,n,i,r,s)}cCurveBy(e,t,n,i,r,s){return this.op("c",e,t,n,i,r,s)}qCurveTo(e,t,n,i){return this.op("Q",e,t,n,i)}qCurveBy(e,t,n,i){return this.op("q",e,t,n,i)}sCurveTo(e,t,n,i){return this.op("S",e,t,n,i)}sCurveBy(e,t,n,i){return this.op("s",e,t,n,i)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,i,r,s,o){return this.op("A",e,t,n,i?1:0,r?1:0,s,o)}arcBy(e,t,n,i,r,s,o){return this.op("a",e,t,n,i?1:0,r?1:0,s,o)}close(){return this.op("z")}toAttribute(){return this.ops.map((e=>e.op+" "+e.args.join(" "))).join(" ")}op(e,...t){return this.ops.push({op:e,args:t}),this}}function E(e,t){switch(t){case i.em:return e+"em";case i.ex:return e+"ex";case i.px:return e+"px";case i.in:return e+"in";case i.cm:return e+"cm";case i.mm:return e+"mm";case i.pt:return e+"pt";case i.pc:return e+"pc";case i.percent:return e+"%";default:return e.toString()}}t.PathContext=T}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.isTouchEnabled=t,e.hasPointerEvents=n,e.down=function(e,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",(e=>{i(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{i(!0)})):e.addEventListener("mouseover",(e=>{i(!!(1&e.buttons))}))},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation";class t{constructor(){this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=o(e);return this.takenNames[t.id]=!0,this.takenNames[u(t)]=!0,t.meta.displayName&&t.meta.displayName!==t.id&&(this.takenNames[t.meta.displayName]&&(t.meta.displayName=this.generateNewDisplayName(t.meta.displayName)),this.takenNames[t.meta.displayName]=!0),this.assets.push(t),o(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(o):this.assets.map(o)}update(e,t){let n;if(this.takenNames[e]){l(this.lookupByID(e),t)?n=t:(this.removeByID(e),n=this.add(t),this.notifyListener(t.internalID))}else n=this.add(t);return n}removeByID(e){const t=this.lookupByID(e);this.assets=this.assets.filter((t=>t.id!==e)),delete this.takenNames[e],t&&delete this.takenNames[u(t)],(null==t?void 0:t.meta.displayName)&&delete this.takenNames[null==t?void 0:t.meta.displayName]}getByID(e){const t=this.lookupByID(e);return t&&o(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||u(t)===e)return o(t)}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t;return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={}){for(const t of this.assets)a(t,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter((t=>t.callback!==e))}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&l(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter((e=>!n[e.internalID])))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,r=n?t.before:t.after;e.Util.assert(i.length===r.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),r[e]&&this.assets.push(r[e]),this.notifyListener(i[e].internalID)):(this.assets.push(r[e]),this.notifyListener(r[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[u(t)]=!0,t.meta.displayName&&(t.meta.displayName!==t.id&&e.Util.assert(!this.takenNames[t.meta.displayName]),this.takenNames[t.meta.displayName]=!0)}lookupByID(e){for(const t of this.assets)if(t.id===e)return t;return null}lookupByInternalID(e){for(const t of this.assets)if(t.internalID===e)return t;return null}removeByInternalID(e){this.assets=this.assets.filter((t=>t.internalID!==e))}notifyListener(e){for(const t of this.listeners)t.internalID===e&&t.callback()}generateNewDisplayName(e){e=e.replace(/\d+$/,"");let t=0;for(;this.takenNames[e+t];)++t;return e+t}}function n(t){const n=[];for(const i of Object.keys(t)){const r=t[i];r.mimeType===e.TILEMAP_MIME_TYPE&&n.push(r)}return n}function i(e,t){return`\n helpers._registerFactory("${e}", function(name: string) {\n switch(helpers.stringTrim(name)) {\n`+t.map((e=>e.keys.filter((e=>!!e)).map((e=>` case "${e}":`)).join("\n")+`return ${e.expression};`)).join("\n")+"\n }\n return null;\n })\n"}function r(t){return e.sprite.Bitmap.fromData(t).copy().data()}function s(t,n){const i=atob(t.data),r=e.U.fromHex(i),s=r[1]|r[2]<<8,o=r[3]|r[4]<<8,a={tileWidth:r[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},l=r.slice(5,5+s*o),c=new e.sprite.Tilemap(s,o,0,0,new Uint8ClampedArray(l)),u=r.slice(5+l.length),d=new e.sprite.Bitmap(s,o,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(c,a,d)}function o(e){switch(e.meta=Object.assign({},e.meta),e.type){case"tile":case"image":return Object.assign(Object.assign({},e),{bitmap:r(e.bitmap)});case"animation":return Object.assign(Object.assign({},e),{frames:e.frames.map((e=>r(e)))});case"tilemap":return Object.assign(Object.assign({},e),{data:e.data.cloneData()})}}function a(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1);switch(t.type){case"image":n[i]=t.jresData,t.meta.displayName&&(n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,displayName:t.meta.displayName});break;case"tile":n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};break;case"tilemap":const r=function(t,n,i){const r=t.tilemap.data(),s=new Uint8ClampedArray(5+r.data.length+t.layers.data.length);return s[0]=t.tileset.tileWidth,s[1]=255&r.width,s[2]=r.width>>8&255,s[3]=255&r.height,s[4]=r.height>>8&255,s.set(r.data,5),s.set(t.layers.data,5+r.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(s)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:i}}(t.data,t.id,t.meta.displayName);n[r.id]=r;break;case"animation":n[i]=function(t){return{namespace:t.id.substr(0,t.id.lastIndexOf(".")),id:t.id.substr(t.id.lastIndexOf(".")+1),mimeType:e.ANIMATION_MIME_TYPE,data:e.sprite.encodeAnimationString(t.frames,t.interval),displayName:t.meta.displayName}}(t)}}function l(t,n){if(t==n)return!0;if(t.id!==n.id||t.type!==n.type||!e.U.arrayEquals(t.meta.tags,n.meta.tags)||!e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)||t.meta.displayName!==n.meta.displayName)return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data)}}function c(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap))|(tilemap))\s*(?:`|\(""")([^`"]+)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function u(e){return d(e.type,e.id)}function d(t,n,i=!1){let r;switch(t){case"image":r=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":r=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":r="";break;case"animation":r=e.sprite.ANIMATION_NAMESPACE+"."}if(r)if(n.startsWith(r)){const e=n.substr(r.length);if(-1===e.indexOf("."))return e}else if(!i)return null;return n}function h(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),r=p(i,0),s=p(i,2),o=p(i,4),a=p(i,6),l=Math.ceil(s*o/2);let c=8;const u=[];for(let e=0;e<a;e++){const e=i.slice(c,c+l);u.push({x0:0,y0:0,width:s,height:o,data:e}),c+=l}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:r,frames:u,meta:{displayName:t.displayName}}}function p(e,t){return e[t]|e[t+1]<<8}e.TilemapProject=class{constructor(){this.needsRebuild=!0,this.nextID=0,this.nextInternalID=0,this.committedState={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.state={revision:this.nextID++,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.gallery={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){const i=this.generateNewID("image"),r=new e.sprite.Bitmap(t,n).data(),s={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:r,meta:{},jresData:e.sprite.base64EncodeBitmap(r)};return this.state.images.add(s)}createNewAnimation(t=16,n=16){const i=this.generateNewID("animation"),r=new e.sprite.Bitmap(t,n).data(),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[r],interval:500,meta:{}};return this.state.animations.add(s)}createNewAnimationFromData(e,t=500,n){const i=this.generateNewID("animation"),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(r)}getGalleryTiles(e){return this.extensionTileSets?this.extensionTileSets.map((t=>t.tileSets.find((t=>t.tileWidth===e)))).filter((e=>null==e?void 0:e.tiles.length)):null}getProjectImages(){return this.state.images.getSnapshot()}getProjectTiles(t,n){const i=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===i.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:i}}createNewTile(t,n,i){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const r={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:i},isProjectTile:!0};return this.state.tiles.add(r)}createNewProjectImage(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(i)}updateTile(t){this.onChange();const n=this.resolveProjectTileByInternalID(t.internalID);if(n){if(this.state.tiles.update(n.id,t),n.id!==t.id||!e.sprite.bitmapEquals(n.bitmap,t.bitmap))for(const e of this.getAssets("tilemap"))e.data.tileset.tiles.some((e=>e.internalID===t.internalID))&&(e.data.tileset.tiles=e.data.tileset.tiles.map((e=>e.internalID===t.internalID?t:e)),this.updateTilemap(e.id,e.data));return t}return null}deleteTile(e){this.onChange(),this.state.tiles.removeByID(e)}getProjectTilesetJRes(){const t={};return this.state.tiles.serializeToJRes(t),this.state.tilemaps.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.TILE_NAMESPACE},t}getProjectAssetsJRes(){const t={};return this.state.images.serializeToJRes(t),this.state.animations.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.IMAGES_NAMESPACE},t}getTilemap(e){return this.state.tilemaps.getByID(e)}updateTilemap(e,t){const n=this.state.tilemaps.getByID(e);if(n){this.onChange();const i=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,i),i}return null}createNewTilemap(e,t,n=16,i=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,i),e)}blankTilemap(t,n=16,i=16){const r=new e.sprite.Tilemap(n,i),s=new e.sprite.Bitmap(n,i),o={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(r,o,s.data())}resolveTile(e){return this.lookupAsset("tile",e)}resolveProjectTileByInternalID(e){return this.state.tiles.getSnapshot((t=>t.internalID===e))[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.state.tiles.getSnapshot((e=>e.jresData===n))[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.state.tiles.getByID(n);if(!i){const r=new e.sprite.Bitmap(t,t).data();return i={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:r,jresData:e.sprite.base64EncodeBitmap(r),meta:{},isProjectTile:!0},this.state.tiles.add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.state.tilemaps.add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName:n},data:e}),[n,e]}cloneState(){return{revision:this.state.revision,images:this.state.images.clone(),tilemaps:this.state.tilemaps.clone(),animations:this.state.animations.clone(),tiles:this.state.tiles.clone()}}undo(){if(this.state.revision!==this.committedState.revision&&this.pushUndo(),this.undoStack.length){const e=this.undoStack.pop();this.state.tiles.applyDiff(e.tiles,!0),this.state.images.applyDiff(e.images,!0),this.state.tilemaps.applyDiff(e.tilemaps,!0),this.state.animations.applyDiff(e.animations,!0),this.state.revision=e.beforeRevision,this.redoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}redo(){if(this.redoStack.length){const e=this.redoStack.pop();this.state.tiles.applyDiff(e.tiles),this.state.images.applyDiff(e.images),this.state.tilemaps.applyDiff(e.tilemaps),this.state.animations.applyDiff(e.animations),this.state.revision=e.afterRevision,this.undoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}pushUndo(){this.undoStack.length&&this.committedState.revision===this.state.revision||(this.redoStack=[],this.undoStack.push({beforeRevision:this.committedState.revision,afterRevision:this.state.revision,tiles:this.state.tiles.diff(this.committedState.tiles),images:this.state.images.diff(this.committedState.images),tilemaps:this.state.tilemaps.diff(this.committedState.tilemaps),animations:this.state.animations.diff(this.committedState.animations)}),this.committedState=this.cloneState(),this.cleanupTemporaryAssets())}revision(){return this.state.revision}encodeTilemap(t,n){const i=t.tilemap.data(),r=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return r[0]=t.tileset.tileWidth,r[1]=255&i.width,r[2]=i.width>>8&255,r[3]=255&i.height,r[4]=i.height>>8&255,r.set(i.data,5),r.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(r)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>{switch(e){case"image":return this.state.images.isIDTaken(t)||this.gallery.images.isIDTaken(t);case"tile":return this.state.tiles.isIDTaken(t)||this.gallery.tiles.isIDTaken(t);case"tilemap":return this.state.tilemaps.isIDTaken(t)||this.gallery.tilemaps.isIDTaken(t);case"animation":return this.state.animations.isIDTaken(t)||this.gallery.animations.isIDTaken(t)}},i=d(e,t),r=i&&i!==t;return n(t)||r&&n(i)}isAssetUsed(t,n,i){var r,s,o;if(((null===(s=null===(r=t.meta)||void 0===r?void 0:r.blockIDs)||void 0===s?void 0:s.filter((e=>!i||(null==i?void 0:i.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==i?void 0:i.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const r=e.Util.escapeForRegex(u(t)),s=e.Util.escapeForRegex(null===(o=t.meta)||void 0===o?void 0:o.displayName)||"";let a;switch(t.type){case"tile":a=`myTiles.${r}|assets.tile\`${r}\``,s&&(a+=`|assets.tile\`${s}\``);break;case"tilemap":a=`tilemap\`${r}\``;break;case"animation":a=`assets.animation\`${r}\``,s&&(a+=`|assets.animation\`${s}\``);break;default:a=`assets.image\`${r}\``,s&&(a+=`|assets.image\`${s}\``)}const l=new RegExp(a,"gm");let c;switch(t.type){case"tile":c=`myTiles.${r}|assets.tile("""${r}""")`,s&&(c+=`|assets.tile("""${s}""")`);break;case"tilemap":c=`assets.tilemap("""${r}""")`;break;case"animation":c=`assets.animation("""${r}""")`,s&&(c+=`|assets.animation("""${s}""")`);break;default:c=`assets.image("""${r}""")`,s&&(c+=`|assets.image("""${s}""")`)}const d=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(d))return!0}}return!1}lookupAsset(e,t){switch(e){case"image":return this.state.images.getByID(t)||this.gallery.images.getByID(t);case"tile":return this.state.tiles.getByID(t)||this.gallery.tiles.getByID(t);case"tilemap":return this.state.tilemaps.getByID(t)||this.gallery.tilemaps.getByID(t);case"animation":return this.state.animations.getByID(t)||this.gallery.animations.getByID(t)}}lookupAssetByName(e,t){switch(e){case"image":return this.state.images.getByDisplayName(t);case"tile":return this.state.tiles.getByDisplayName(t);case"tilemap":return this.state.tilemaps.getByDisplayName(t);case"animation":return this.state.animations.getByDisplayName(t)}}getAssets(e){switch(e){case"image":return this.state.images.getSnapshot();case"tile":return this.state.tiles.getSnapshot();case"tilemap":return this.state.tilemaps.getSnapshot();case"animation":return this.state.animations.getSnapshot()}}getGalleryAssets(e){switch(e){case"image":return this.gallery.images.getSnapshot();case"tile":return this.gallery.tiles.getSnapshot();case"tilemap":return this.gallery.tilemaps.getSnapshot();case"animation":return this.gallery.animations.getSnapshot()}}lookupBlockAsset(e,t){let n=e=>{var n,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.indexOf(t))};switch(e){case"image":return this.state.images.getSnapshot(n)[0];case"tile":return this.state.tiles.getSnapshot(n)[0];case"tilemap":return this.state.tilemaps.getSnapshot(n)[0];case"animation":return this.state.animations.getSnapshot(n)[0]}}updateAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.update(e.id,e);case"tile":return this.updateTile(e);case"tilemap":return this.state.tilemaps.update(e.id,e);case"animation":return this.state.animations.update(e.id,e)}}duplicateAsset(e,t){var n;this.onChange();const i=o(e),r=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let s;switch(e.type){case"image":s=this.createNewProjectImage(i.bitmap,r);break;case"tile":s=this.createNewTile(i.bitmap,null,r);break;case"tilemap":const[e,t]=this.createNewTilemapFromData(i.data,r);s=this.getTilemap(e);break;case"animation":s=this.createNewAnimationFromData(i.frames,i.interval,r)}return s}removeAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.removeByID(e.id);case"tile":return this.state.tiles.removeByID(e.id);case"tilemap":return this.state.tilemaps.removeByID(e.id);case"animation":return this.state.animations.removeByID(e.id)}}addChangeListener(e,t){switch(e.type){case"image":this.state.images.addListener(e.internalID,t);break;case"tile":this.state.tiles.addListener(e.internalID,t);break;case"tilemap":this.state.tilemaps.addListener(e.internalID,t);break;case"animation":this.state.animations.addListener(e.internalID,t)}}removeChangeListener(e,t){switch(e){case"image":this.state.images.removeListener(t);break;case"tile":this.state.tiles.removeListener(t);break;case"tilemap":this.state.tilemaps.removeListener(t);break;case"animation":this.state.animations.removeListener(t)}}loadPackage(e){const t=e.sortedDeps();this.extensionTileSets=[];for(const e of t){const t="this"===e.id,n=this.readImages(e.parseJRes(),t);for(const e of n)"tile"===e.type?t?this.state.tiles.add(e):this.gallery.tiles.add(e):"image"===e.type?t?this.state.images.add(e):this.gallery.images.add(e):t?this.state.animations.add(e):this.gallery.animations.add(e)}for(const t of n(e.parseJRes()))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:t.id,meta:{displayName:t.displayName||t.id},data:s(t,(e=>this.resolveTile(e)))});this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,i=!1){t=e.inflateJRes(t);const r=this.readImages(t,!0).filter((e=>"tile"===e.type));let o={};for(const e of r){if(i){const t=this.resolveTileByBitmap(e.bitmap);if(t){o[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(o[e.id]=t.id)}for(const e of n(t))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:s(e,(e=>(o[e]&&(e=o[e]),this.resolveTile(e))))})}loadAssetsJRes(t){t=e.inflateJRes(t);const n=[];for(const i of Object.keys(t)){const r=t[i];if(r.tilemapTile)this.state.tiles.add(this.generateImage(r,"tile"));else if(r.mimeType===e.IMAGE_MIME_TYPE)this.state.images.add(this.generateImage(r,"image"));else if(r.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(r);t?n.push(e):this.state.animations.add(e)}}for(const e of n)this.state.animations.add(this.inflateAnimation(e,this.state.images.getSnapshot()))}removeInactiveBlockAssets(e){function t(t){const n=t.getSnapshot((t=>{var n;return!t.meta.displayName&&(null===(n=t.meta.blockIDs)||void 0===n?void 0:n.some((t=>-1===e.indexOf(t))))})),i=[];for(const t of n)1===t.meta.blockIDs.length?i.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&i.push(t));for(const e of i)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations)}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).data()}}generateAnimation(e){if("json"===e.dataEncoding){let t;try{t=JSON.parse(e.data)}catch(t){console.warn("could not parse json data of '"+e.id+"'")}return[{internalID:this.getNewInternalId(),type:"animation",meta:{displayName:e.displayName},id:e.id,frames:[],frameIds:t.frames,interval:100,flippedHorizontal:t.flippedHorizontal},!0]}return[Object.assign(Object.assign({},h(e)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map((e=>n.find((t=>t.id===e)).bitmap)),t.flippedHorizontal&&(t.frames=t.frames.map((t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()}))),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"))}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const i=n?n+"."+t:t;let r=1;for(;this.isNameTaken(e,i+r);)++r;return i+r}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const i=[],r=[];for(const s of Object.keys(t)){const o=t[s];if(o.tilemapTile){const e=this.generateImage(o,"tile");e.isProjectTile=n,i.push(e)}else if(o.mimeType===e.IMAGE_MIME_TYPE)i.push(this.generateImage(o,"image"));else if(o.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(o);t?r.push(e):i.push(e)}}for(const e of r)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.state.images.getSnapshot((e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)}));for(const t of e)this.state.images.removeByID(t.id)}},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let r="";const o=[],a=[];for(const i of n){if("*"===i)continue;const n=t[i];if(n.tilemapTile&&(r+=" //% fixedInstance jres blockIdentity=images._tile\n",r+=` export const ${i} = image.ofBuffer(hex\`\`);\n`,a.push({keys:[n.displayName,d("tile",i,!0)],expression:i})),n.mimeType===e.TILEMAP_MIME_TYPE){const t=s(n);o.push({keys:[n.displayName,d("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}o.length&&(r+=i("tilemap",o)),a.length&&(r+=i("tile",a));const l=lf("Auto-generated code. Do not edit.");return`// ${l}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${r}\n}\n// ${l}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let r="";const s=[],o=[];for(const i of n){if("*"===i)continue;const n=t[i];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,r=[d("image",i,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),r.push(n.displayName)),s.push({keys:r,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=h(n);o.push({keys:[n.displayName,d("animation",i,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}}const a=lf("Auto-generated code. Do not edit.");return r+=i("image",s),r+=i("animation",o),`// ${a}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${r}\n}\n// ${a}\n`},e.cloneAsset=o,e.assetEquals=l,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:u(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const r=t?'("""':"`",s=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${r}${i}${s}`;case"image":return`assets.image${r}${i}${s}`;case"animation":return`assets.animation${r}${i}${s}`;case"tilemap":return`tilemap${r}${i}${s}`}},e.parseAssetTSReference=c,e.lookupProjectAssetByTSReference=function(e,t){const n=c(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i)}}},e.getDefaultAssetDisplayName=function(e){switch(e){case"image":return lf("myImage");case"tile":return lf("myTile");case"tilemap":return lf("level");case"animation":return lf("myAnim");default:return lf("asset")}},e.getShortIDForAsset=u}(pxt||(pxt={})),function(e){!function(t){t.blockColors={loops:"#107c10",logic:"#006970",math:"#712672",variables:"#A80000",functions:"#005a9e",text:"#996600",arrays:"#A94400",advanced:"#3c3c3c",addpackage:"#717171",search:"#000",debug:"#e03030",default:"#dddddd",topblocks:"#aa8f00",recipes:"#717171"},t.blockIcons={loops:"",logic:"",math:"",variables:"",functions:"",text:"",arrays:"",advancedcollapsed:"",advancedexpanded:"",more:"",addpackage:"",search:"",debug:"",default:"",topblocks:"",recipes:""};let n="";function i(e){const t=function(e,t,n){let i=0,r=0,s=0;if(0==t)i=n,r=n,s=n;else{let o=Math.floor(e/60),a=e/60-o,l=n*(1-t),c=n*(1-t*a),u=n*(1-t*(1-a));switch(o){case 1:i=c,r=n,s=l;break;case 2:i=l,r=n,s=u;break;case 3:i=l,r=c,s=n;break;case 4:i=u,r=l,s=n;break;case 5:i=n,r=l,s=c;break;case 6:case 0:i=n,r=u,s=l}}return[Math.floor(i),Math.floor(r),Math.floor(s)]}(e,.45,165.75);return`#${r(t[0])}${r(t[1])}${r(t[2])}`}function r(e){const t=e.toString(16);return 1==t.length?"0"+t:t}t.appendToolboxIconCss=function(t,i){if(!(n.indexOf(t)>-1))if(1===i.length){const r=e.Util.unicodeToChar(i);n+=`\n .blocklyTreeIcon.${t}::before {\n content: "${r}";\n }\n `}else n+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(i))}")!important;\n width: 30px;\n height: 100%;\n background-size: 20px !important;\n background-repeat: no-repeat !important;\n background-position: 50% 50% !important;\n }\n `},t.getNamespaceColor=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]?e.toolbox.blockColors[t]:""},t.getNamespaceIcon=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockIcons&&e.appTarget.appTheme.blockIcons[t]?e.appTarget.appTheme.blockIcons[t]:e.toolbox.blockIcons[t]?e.toolbox.blockIcons[t]:""},t.advancedTitle=function(){return e.Util.lf("{id:category}Advanced")},t.addPackageTitle=function(){return e.Util.lf("{id:category}Extensions")},t.recipesTitle=function(){return e.Util.lf("{id:category}Tutorials")},t.convertColor=function(e){var t;e=(t=e)?"0x"==t.substring(0,2)?"#"+t.substring(2):t:"#000000";const n=parseInt(e);return isNaN(n)?e:i(n)},t.hueToRgb=i,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let r=0;r<3;r++){let s=parseInt(e.substr(2*r,2),16);s=Math.round(Math.min(Math.max(0,n?s+s*t:s-s*t),255));let o=s.toString(16);i+=("00"+o).substr(o.length)}return i}}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function r(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim}function s(t,i,r){let s=i||n,a=[];if(t.replace(s,(function(e,t,n){n=n.trim();let{header:i,hint:s,requiredBlocks:l}=function(e,t,n){let i,r,s=e=o(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;s=e.replace(t,(function(e,t){return i=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let o=e.match(t);if(o&&o.length>2&&(s=o[1].trim(),i=o[2].trim(),n)){let e=o[2].trim();e=e.replace(/``` *(requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return r=`{\n${n}\n}`,""})),i=e}}return{header:s,hint:i,requiredBlocks:r}}(n,r&&r.explicitHints,r.tutorialCodeValidation);let c={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(c.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(c.showDialog=!0),/@tutorialCompleted/.test(t)&&(c.tutorialCompleted=!0),/@resetDiff/.test(t)&&(c.resetDiff=!0),s&&(c.hintContentMd=s),r.tutorialCodeValidation&&l&&(c.requiredBlockMd=l),a.push(c),""})),0!=t.indexOf("# Not found"))return a;e.debug("tutorial not found")}function o(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|customts)\s*\n([\s\S]*?)\n```/gim,"").trim()}function a(t){if(!t)return;const n=JSON.parse(t);return{[e.TILEMAP_JRES]:n[e.TILEMAP_JRES],[e.TILEMAP_CODE]:n[e.TILEMAP_CODE],[e.IMAGES_JRES]:n[e.IMAGES_JRES],[e.IMAGES_CODE]:n[e.IMAGES_CODE]}}t.parseTutorial=function(t){const{metadata:r,body:l}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},r=t.replace(n,(function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""})),s=i;void 0!==s.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(s.explicitHints=!0);return{metadata:s,body:r}}(t),{steps:c,activities:u}=function(e,t){if(t&&t.activities)return function(e,t){let r=[],o=[];return e.replace(n,(function(e,n,a){let l=o.length;o.push({name:n||lf("Activity {0}",l),step:r.length});let c=s(a,i,t);return c=c.map((e=>(e.activity=l,e))),r=r.concat(c),""})),{steps:r,activities:o}}(e,t);{let n=s(e,null,t);return(!n||n.length<1)&&(n=s(e,i,t)),{steps:n,activities:null}}}(l,r),d=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(l);if(!c)return;const{code:h,templateCode:p,editor:f,language:m,jres:g,assetJson:b,customTs:y,tutorialValidationRulesStr:v}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim;let r,s,o,a,l,c,u=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,(function(t,n,i){switch(n){case"block":case"blocks":case"requiredTutorialBlock":case"filterblocks":if(!d(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!d(e.PYTHON_PROJECT_NAME))return;"python"==n&&(o=n);break;case"typescript":case"ts":case"javascript":case"js":if(!d(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":s=i;break;case"jres":r=i;break;case"assetjson":a=i;break;case"customts":l=i,i="";break;case"tutorialValidationRules":c=i}return u.push("python"==n?`\n${i}\n`:`{\n${i}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:u,templateCode:s,editor:n,language:o,jres:r,assetJson:a,customTs:l,tutorialValidationRulesStr:c};function d(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(l);let w;r.tutorialCodeValidation&&(w=e.Util.jsonTryParse(v),function(t,n){const i=Object.keys(t);for(let r=0;r<i.length;r++){const s={ruleName:i[r],enabled:t[i[r]]?"true":"false",tutorial:n};e.tickEvent("tutorial.validation.setValidationRules",s)}}(w,d)),(!0===r.diffs||!1!==r.diffs&&!0!==r.noDiffs&&(f==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||f!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,r,s){const o=n,a=/^(template|ghost)$/.test(r),l=i.test(s);return s=s.replace(/^\n+/,"").replace(/\n+$/,""),l&&(s=s.replace(i,"")),n=s,!o||l||a?e:`\`\`\`${t[r]}\n${o}\n----------\n${s}\n\`\`\``})):e}e.forEach(((e,r)=>{if((e.resetDiff||t&&t.find((e=>e.step==r)))&&(n=void 0),e.hintContentMd){const t=i(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=i(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(c,u);const x=a(b);return c.forEach((e=>{e.contentMd=o(e.contentMd),e.headerContentMd=o(e.headerContentMd),e.hintContentMd=o(e.hintContentMd),e.requiredBlockMd=o(e.requiredBlockMd)})),{editor:f,title:d,steps:c,activities:u,code:h,templateCode:p,metadata:r,language:m,jres:g,assetFiles:x,customTs:y,tutorialValidationRules:w}},t.getMetadataRegex=r,t.highlight=function(e){let t=e.textContent;if(t=t.replace(/img\s*\(\s*"{3}[\s\da-f.#tngrpoyw]*"{3}\s*\)/g,'img(""" """)'),t=t.replace(/img\s*`[\s\da-f.#tngrpoyw]*`\s*/g,"img` `"),!/@highlight/.test(t))return void(e.textContent=t);e.textContent="";const n=t.split("\n");for(let t=0;t<n.length;++t){t>0&&t<n.length&&e.appendChild(document.createTextNode("\n"));let i=n[t];if(/@highlight/.test(i)){if(i=n[++t],void 0!==i){const t=document.createElement("span");t.className="highlight-line",t.textContent=i,e.appendChild(t)}}else e.appendChild(document.createTextNode(i))}},t.getTutorialOptions=function(t,n,i,r,s){var o;const a=e.tutorial.parseTutorial(t);if(!a)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:a.title||i,tutorialReportId:r,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:a.steps,tutorialActivityInfo:a.activities,tutorialMd:t,tutorialCode:a.code,tutorialRecipe:!!s,templateCode:a.templateCode,autoexpandStep:!(null===(o=a.metadata)||void 0===o?void 0:o.autoexpandOff),metadata:a.metadata,language:a.language,jres:a.jres,assetFiles:a.assetFiles,customTs:a.customTs,tutorialValidationRules:a.tutorialValidationRules},editor:a.editor}},t.parseCachedTutorialInfo=function(t,n){let i=e.Util.jsonTryParse(t);return i?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&i[n]){const t=i[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){const r=(i||t.fileName||"README")+".md";let s;const[o,a,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return s=o&&a&&l?n[`_locales/${o}/${r}`]||n[`_locales/${l}/${r}`]||n[`_locales/${a}/${r}`]:n[`_locales/${o}/${r}`],s=s||n[r],s},t.parseAssetJson=a}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n){const{tutorialStep:i}=t,r=t.tutorialStepInfo[i].requiredBlockMd,s=e.BrowserUtils.getTutorialCodeHash([r]);let o={};return null!=n&&(o=n[s]),o}function i(e,t,n){n.isStrict=!0;const i=Object.keys(e);let r=[],s=[];null!=t&&(r=Object.keys(t));let o=i.length>=r.length;const a=lf("These are the blocks you seem to be missing:");for(let n=0;n<r.length;n++){let i=r[n];(!e[i]||e[i]<t[i])&&(s.push(i),o=!1)}return n.ruleMessage=a,n.ruleStatus=o,n.blockIds=s,n}function r(e,t,n){const i=Object.keys(e),r=Object.keys(null!=t?t:{});let s=i.length>=r.length;for(let t=0;t<r.length;t++){if(!e[r[t]]){s=!1;break}}return n.ruleStatus=s,n}function s(e,t,n){n.isStrict=!0;Object.keys(e);let i=[],r=[];null!=t&&(i=Object.keys(t));let s=!0;const o=lf("You are required to have the following block:");for(let t=0;t<i.length;t++){let n=i[t];e[n]||(r.push(n),s=!1)}return n.ruleMessage=o,n.ruleStatus=s,n.blockIds=r,n}t.validate=async function(t,o,a){let l=function(e){let t=[];if(null!=e){const n=Object.keys(e);for(let i=0;i<n.length;i++){const r=n[i],s={ruleName:r,ruleTurnOn:e[r]};t.push(s)}}return t}(t.tutorialValidationRules);if(l.length>0&&o.length>0){const a=function(e){let t={};for(let n=0;n<e.length;n++)t[e[n]]||(t[e[n]]=0),t[e[n]]=t[e[n]]+1;return t}(o.map((e=>e.type))),{tutorialStepInfo:c,tutorialStep:u}=t,d=(c[u],await function(t,n){return e.BrowserUtils.tutorialInfoDbAsync().then((e=>e.getAsync(t.tutorial,t.tutorialCode).then((e=>(null==e?void 0:e.snippets)?Promise.resolve(e.snippets):Promise.resolve(void 0)))))}(t)),h=function(t,n){const{tutorialStepInfo:i,tutorialStep:r}=t,s=t.tutorialStepInfo[r].hintContentMd;let o="";null!=s&&s.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return o=`{\n${n}\n}`,""}));const a=e.BrowserUtils.getTutorialCodeHash([o]);let l={};null!=n&&(l=n[a]);return l}(t,d);for(let e=0;e<l.length;e++){let o=l[e];const c=l[e].ruleName;if(l[e].ruleTurnOn)switch(c){case"exact":o=i(a,h,o);break;case"atleast":o=r(a,h,o);break;case"required":o=s(a,n(t,d),o)}}}return l}}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){let n;t.flattenDiagnosticMessageText=function(e,t){if("string"==typeof e)return e;{let n=e,i="",r=0;for(;n;){if(r){i+=t;for(let e=0;e<r;e++)i+=" "}i+=n.messageText,r++,n=n.next}return i}},function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES6=2]="ES6",e[e.ES2015=2]="ES2015",e[e.Latest=2]="Latest"}(n=t.ScriptTarget||(t.ScriptTarget={})),t.isIdentifierStart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&a(e,t)},t.isIdentifierPart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return t>=n.ES5?l(e,r):l(e,o)}(e,t)},t.reservedWords=["abstract","any","as","break","case","catch","class","continue","const","constructor","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","is","let","module","namespace","new","null","package","private","protected","public","require","global","return","set","static","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","async","await","of","Math"],t.keywordTypes=["boolean","number","string"],t.escapeIdentifier=function(n){if(!n)return"_";let i=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return i&&e.pxtc.isIdentifierStart(i.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(i)||(i="_"+i),i};const i=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],r=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],s=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],o=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,768,846,864,866,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1155,1158,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1425,1441,1443,1465,1467,1469,1471,1471,1473,1474,1476,1476,1488,1514,1520,1522,1569,1594,1600,1621,1632,1641,1648,1747,1749,1756,1759,1768,1770,1773,1776,1788,1808,1836,1840,1866,1920,1968,2305,2307,2309,2361,2364,2381,2384,2388,2392,2403,2406,2415,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2494,2500,2503,2504,2507,2509,2519,2519,2524,2525,2527,2531,2534,2545,2562,2562,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2649,2652,2654,2654,2662,2676,2689,2691,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2784,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2876,2883,2887,2888,2891,2893,2902,2903,2908,2909,2911,2913,2918,2927,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3006,3010,3014,3016,3018,3021,3031,3031,3047,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3134,3140,3142,3144,3146,3149,3157,3158,3168,3169,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3262,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3297,3302,3311,3330,3331,3333,3340,3342,3344,3346,3368,3370,3385,3390,3395,3398,3400,3402,3405,3415,3415,3424,3425,3430,3439,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3805,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3946,3953,3972,3974,3979,3984,3991,3993,4028,4038,4038,4096,4129,4131,4135,4137,4138,4140,4146,4150,4153,4160,4169,4176,4185,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,4969,4977,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6099,6112,6121,6160,6169,6176,6263,6272,6313,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8319,8319,8400,8412,8417,8417,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12335,12337,12341,12344,12346,12353,12436,12441,12442,12445,12446,12449,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65056,65059,65075,65076,65101,65103,65136,65138,65140,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65381,65470,65474,65479,65482,65487,65490,65495,65498,65500];function a(e,t){return t>=n.ES5?l(e,i):l(e,s)}function l(e,t){if(e<t[0])return!1;let n,i=0,r=t.length;for(;i+1<r;){if(n=i+(r-i)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?r=n:i=n+2}return!1}let c;t.isUnicodeIdentifierStart=a,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(c=t.DiagnosticCategory||(t.DiagnosticCategory={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(){return!!navigator&&!!navigator.bluetooth&&"TextDecoder"in window&&e.appTarget.appTheme.bluetoothUartConsole&&e.appTarget.appTheme.bluetoothUartFilters&&e.appTarget.appTheme.bluetoothUartFilters.length>0}function i(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||i()},t.hasConsole=n,t.hasPartialFlash=i,t.isValidUUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)};class r{constructor(e,t){this.connectionTimeout=2e4,this.connectPromise=void 0,this.id=e,this.aliveToken=t}debug(t){e.debug(`${this.id}: ${t}`)}alivePromise(e){return new Promise(((t,n)=>{this.aliveToken.isCancelled()&&n(new Error),e.then((e=>t(e)),(e=>n(e)))}))}cancelConnect(){this.connectPromise=void 0}createConnectPromise(){return Promise.resolve()}connectAsync(){return this.connectPromise||(this.connectPromise=this.alivePromise(this.createConnectPromise())),e.Util.promiseTimeout(this.connectionTimeout,this.connectPromise,"connection timeout").then((()=>this.aliveToken.throwIfCancelled())).catch((e=>{throw this.connectPromise=void 0,e}))}disconnect(){this.cancelConnect()}kill(){this.disconnect(),this.aliveToken.cancel()}}t.BLERemote=r;class s extends r{constructor(e,t,n){super(e,t.aliveToken),this.device=t,this.autoReconnect=n,this.autoReconnectDelay=1e3,this.disconnectOnAutoReconnect=!1,this.reconnectPromise=void 0,this.failedConnectionServicesVersion=-1,this.handleDisconnected=this.handleDisconnected.bind(this),this.device.device.addEventListener("gattserverdisconnected",this.handleDisconnected)}handleDisconnected(t){this.aliveToken.isCancelled()||(this.disconnect(),this.autoReconnect&&!this.reconnectPromise&&(this.reconnectPromise=e.U.delay(this.autoReconnectDelay).then((()=>this.exponentialBackoffConnectAsync(8,500))).finally((()=>this.reconnectPromise=void 0))))}exponentialBackoffConnectAsync(t,n){return this.debug("retry connect"),this.aliveToken.throwIfCancelled(),this.connectAsync().then((()=>{this.aliveToken.throwIfCancelled(),this.debug("reconnect success"),this.reconnectPromise=void 0})).catch((i=>(this.debug(`reconnect error ${i.message}`),this.aliveToken.throwIfCancelled(),this.device.isPaired?this.autoReconnect?0==t?(this.debug("give up, max tries"),void(this.reconnectPromise=void 0)):this.failedConnectionServicesVersion==this.device.servicesVersion?(this.debug("services haven't changed, giving up"),void(this.reconnectPromise=void 0)):(this.debug(`retry connect ${n}ms... (${t} tries left)`),this.device.connected&&(this.failedConnectionServicesVersion=this.device.servicesVersion),this.disconnectOnAutoReconnect&&this.device.disconnect(),e.U.delay(n).then((()=>this.exponentialBackoffConnectAsync(--t,1.8*n)))):(this.debug("autoreconnect disabled"),void(this.reconnectPromise=void 0)):(this.debug("give up, device unpaired"),void(this.reconnectPromise=void 0)))))}}t.BLEService=s;class o extends s{constructor(e,t,n,i){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=i,this.handleValueChanged=this.handleValueChanged.bind(this)}createConnectPromise(){return this.debug("connecting"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(this.serviceUUID)))).then((e=>(this.debug("service connected"),this.service=e,this.alivePromise(this.service.getCharacteristic(this.txCharacteristicUUID))))).then((e=>(this.debug("tx characteristic connected"),this.txCharacteristic=e,this.txCharacteristic.addEventListener("characteristicvaluechanged",this.handleValueChanged),this.txCharacteristic.startNotifications()))).then((()=>{e.tickEvent("webble.connected",{id:this.id})}))}handlePacket(e){}handleValueChanged(e){const t=e.target.value;this.handlePacket(t)}disconnect(){if(super.disconnect(),this.txCharacteristic&&this.device&&this.device.connected)try{this.txCharacteristic.stopNotifications(),this.txCharacteristic.removeEventListener("characteristicvaluechanged",this.handleValueChanged)}catch(t){e.log(`${this.id}: error ${t.message}`)}this.service=void 0,this.txCharacteristic=void 0}}t.BLETXService=o;class a extends o{constructor(e){super("hf2",e,a.SERVICE_UUID,a.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case a.BLEHF2_FLAG_SERIAL_OUT:case a.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let i="";for(let t=0;t<n;++t)i+=String.fromCharCode(e.getUint8(t+1));i&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:i},"*")}}}a.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",a.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",a.BLEHF2_FLAG_SERIAL_OUT=128,a.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=a;class l extends o{constructor(e){super("uart",e,l.SERVICE_UUID,l.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=(new window.TextDecoder).decode(e);t&&window.postMessage({type:"serial",id:this.device.name||"uart",data:t},"*")}}let c;l.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",l.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=l,function(e){e[e.Idle=1]="Idle",e[e.StatusRequested=2]="StatusRequested",e[e.PairingModeRequested=4]="PairingModeRequested",e[e.RegionDALRequested=8]="RegionDALRequested",e[e.RegionMakeCodeRequested=16]="RegionMakeCodeRequested",e[e.Flash=32]="Flash",e[e.EndOfTransmision=64]="EndOfTransmision",e[e.USBFlashRequired=128]="USBFlashRequired"}(c||(c={}));class u extends s{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=c.Idle,this.disconnectOnAutoReconnect=!0,this.handleCharacteristic=this.handleCharacteristic.bind(this)}clearFlashData(){this.version=0,this.mode=0,this.regions=[],this.chunkDelay=u.CHUNK_MIN_DELAY,this.hex=void 0,this.bin=void 0,this.magicOffset=void 0,this.dalHash=void 0,this.makeCodeHash=void 0,this.flashReject=void 0,this.flashResolve=void 0,this.flashOffset=void 0}createConnectPromise(){return this.debug("connecting to partial flash service"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(u.SERVICE_UUID)))).then((e=>(this.debug("connecting to characteristic"),this.alivePromise(e.getCharacteristic(u.CHARACTERISTIC_UUID))))).then((e=>(this.debug("starting notifications"),this.pfCharacteristic=e,this.pfCharacteristic.startNotifications(),this.pfCharacteristic.addEventListener("characteristicvaluechanged",this.handleCharacteristic),this.state==c.PairingModeRequested?(this.debug("checking pairing mode"),this.autoReconnect=!1,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))):Promise.resolve())))}disconnect(){if(super.disconnect(),this.flashPacketToken&&this.flashPacketToken.cancel(),this.pfCharacteristic&&this.device.connected)try{this.pfCharacteristic.stopNotifications(),this.pfCharacteristic.removeEventListener("characteristicvaluechanged",this.handleCharacteristic)}catch(t){e.log(`ble: partial flash disconnect error ${t.message}`)}this.pfCharacteristic=void 0}findMarker(e,t){if(!this.bin)return-1;for(;e+t.length<this.bin.length;e+=16){let n=!0;for(let i=0;i<t.length;++i)if(t[i]!=this.bin[e+i]){n=!1;break}if(n)return e}return-1}flashAsync(e){return this.hex?(this.debug("flashing already in progress"),Promise.resolve()):(this.device.pauseLog(),this.createFlashPromise(e).finally((()=>this.device.resumeLogOnDisconnection())))}createFlashPromise(t){if(this.hex)return this.debug("flashing already in progress"),Promise.resolve();this.clearFlashData(),this.hex=t;const n=ts.pxtc.UF2.newBlockFile();ts.pxtc.UF2.writeHex(n,this.hex.split(/\r?\n/));const i=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),i).buf,this.debug(`bin bytes ${this.bin.length}`),this.magicOffset=this.findMarker(0,u.MAGIC_MARKER),this.debug(`magic block ${this.magicOffset.toString(16)}`),this.magicOffset<0&&(this.debug("magic block not found, not a valid HEX file"),e.U.userError(lf("Invalid file"))),this.debug("bytes to flash "+(this.bin.length-this.magicOffset));const r=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(r,r+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(r+8,r+16)),this.debug(`DAL hash ${this.dalHash}`),this.debug(`MakeCode hash ${this.makeCodeHash}`),this.connectAsync().then((()=>new Promise(((e,t)=>(this.flashResolve=e,this.flashReject=t,this.debug("check service version"),this.state=c.StatusRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))))))).then((()=>{}),(t=>{e.log(`pf: error ${t.message}`),this.clearFlashData()}))}checkStateTransition(e,t){return!!(this.state&t)||(this.debug(`flash cmd ${e} in state ${this.state.toString(16)} `),this.flashReject(new Error),this.clearFlashData(),!1)}handleCharacteristic(t){this.aliveToken.isCancelled()&&(this.flashReject(new Error),this.clearFlashData());const n=event.target.value,i=new Uint8Array(n.buffer),r=i[0];if(this.state!=c.Idle)switch(r){case u.STATUS:if(!this.checkStateTransition(r,c.StatusRequested|c.PairingModeRequested))return;this.version=i[1],this.mode=i[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=c.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(r,c.RegionDALRequested|c.RegionMakeCodeRequested))return;const t=this.regions[i[1]]={start:i[2]<<24|i[3]<<16|i[4]<<8|i[5],end:i[6]<<24|i[7]<<16|i[8]<<8|i[9],hash:e.Util.toHex(i.slice(10))};if(this.debug(`read region ${i[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),i[1]==u.REGION_DAL){if(t.hash!=this.dalHash)return e.tickEvent("webble.flash.DALrequired"),this.debug("DAL hash does not match, partial flashing not possible"),this.state=c.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=c.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(i[1]==u.REGION_MAKECODE)if(t.start!=this.magicOffset&&(this.debug("magic offset and MakeCode region.start not matching"),e.U.userError(lf("Invalid file"))),t.hash==this.makeCodeHash)e.tickEvent("webble.flash.noop"),this.debug("MakeCode hash matches, same code!"),this.debug("restart application mode"),this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_APPLICATION])).then((()=>{this.state=c.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=c.PairingModeRequested,this.autoReconnect=!0,void this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_PAIRING])).then((()=>{}));this.flashOffset=t.start,this.flashPacketNumber=0,this.debug(`starting to flash from address ${this.flashOffset.toString(16)}`),this.flashNextPacket()}break;case u.FLASH_DATA:if(!this.checkStateTransition(r,c.Flash))return;switch(i[1]){case u.PACKET_OUT_OF_ORDER:this.debug("packet out of order"),this.flashPacketToken.cancel(),this.flashPacketNumber+=4,this.chunkDelay=Math.min(this.chunkDelay+10,u.CHUNK_MAX_DELAY),this.flashNextPacket();break;case u.PACKET_WRITTEN:this.chunkDelay=Math.max(this.chunkDelay-1,u.CHUNK_MIN_DELAY),this.flashOffset+=64,this.flashPacketNumber+=4,this.flashOffset>=this.bin.length?(this.debug("end transmission"),this.state=c.EndOfTransmision,this.pfCharacteristic.writeValue(new Uint8Array([u.END_OF_TRANSMISSION])).finally((()=>{this.flashResolve&&this.flashResolve(),this.clearFlashData()}))):this.flashNextPacket()}break;default:this.debug(`unknown message ${e.Util.toHex(i)}`),this.disconnect()}}flashNextPacket(){this.state=c.Flash,this.flashPacketToken=new e.Util.CancellationToken,this.flashPacketToken.startOperation();const t=this.bin.slice(this.flashOffset,this.flashOffset+64);this.debug(`flashing ${this.flashOffset.toString(16)} / ${this.bin.length.toString(16)} ${(this.flashOffset-this.magicOffset)/(this.bin.length-this.magicOffset)*100>>0}%`);let n=new Uint8Array(20);e.U.delay(this.chunkDelay).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>8&255,n[2]=this.flashOffset>>0&255,n[3]=this.flashPacketNumber;for(let e=0;e<16;e++)n[4+e]=t[e];return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>24&255,n[2]=this.flashOffset>>16&255,n[3]=this.flashPacketNumber+1;for(let e=0;e<16;e++)n[4+e]=t[16+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+2;for(let e=0;e<16;e++)n[4+e]=t[32+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+3;for(let e=0;e<16;e++)n[4+e]=t[48+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>{const t=this.flashOffset,i=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=c.Flash)return Promise.resolve();this.debug("packet transfer deadlock, force restart"),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=-1;for(let e=0;e<16;e++)n[4+e]=0;return this.pfCharacteristic.writeValue(n).then((()=>i()))}));i().catch((e=>{this.flashReject&&(this.flashReject(new Error("failed packet transfer")),this.clearFlashData())}))})).catch((()=>{this.flashPacketToken.resolveCancel()}))}}u.SERVICE_UUID="e97dd91d-251d-470a-a062-fa1922dfa9a8",u.CHARACTERISTIC_UUID="e97d3b10-251d-470a-a062-fa1922dfa9a8",u.REGION_INFO=0,u.FLASH_DATA=1,u.PACKET_OUT_OF_ORDER=170,u.PACKET_WRITTEN=255,u.END_OF_TRANSMISSION=2,u.STATUS=238,u.RESET=255,u.MODE_PAIRING=0,u.MODE_APPLICATION=1,u.REGION_SOFTDEVICE=0,u.REGION_DAL=1,u.REGION_MAKECODE=2,u.MAGIC_MARKER=e.Util.fromHex("708E3B92C615A841C49866C975EE5197"),u.CHUNK_MIN_DELAY=0,u.CHUNK_MAX_DELAY=75,t.PartialFlashingService=u;class d extends r{constructor(t){super("ble",new e.Util.CancellationToken),this.device=void 0,this.services=[],this.pendingResumeLogOnDisconnection=!1,this.servicesVersion=0,this.device=t,this.handleDisconnected=this.handleDisconnected.bind(this),this.handleServiceAdded=this.handleServiceAdded.bind(this),this.handleServiceChanged=this.handleServiceChanged.bind(this),this.handleServiceRemoved=this.handleServiceRemoved.bind(this),this.device.addEventListener("gattserverdisconnected",this.handleDisconnected),this.device.addEventListener("serviceadded",this.handleServiceAdded),this.device.addEventListener("servicechanged",this.handleServiceChanged),this.device.addEventListener("serviceremoved",this.handleServiceRemoved),n()&&(this.services.push(this.uartService=new l(this)),this.services.push(this.hf2Service=new a(this))),i()&&this.services.push(this.partialFlashingService=new u(this)),this.aliveToken.startOperation()}startServices(){this.services.filter((e=>e.autoReconnect)).forEach((e=>e.connectAsync().catch((()=>{}))))}pauseLog(){this.uartService&&(this.uartService.autoReconnect=!1,this.uartService.disconnect()),this.hf2Service&&(this.hf2Service.autoReconnect=!1,this.hf2Service.disconnect())}resumeLogOnDisconnection(){this.pendingResumeLogOnDisconnection=!0}resumeLog(){this.uartService&&(this.uartService.autoReconnect=!0,this.uartService.connectAsync().catch((()=>{}))),this.hf2Service&&(this.hf2Service.autoReconnect=!0,this.hf2Service.connectAsync().catch((()=>{})))}get isPaired(){return this===t.bleDevice}get name(){return this.device.name||"?"}get connected(){return this.device&&this.device.gatt&&this.device.gatt.connected}get gatt(){return this.device.gatt}createConnectPromise(){return this.debug("connecting gatt server"),this.alivePromise(this.device.gatt.connect().then((()=>this.debug("gatt server connected"))))}handleServiceAdded(e){this.debug("service added"),this.servicesVersion++}handleServiceRemoved(e){this.debug("service removed"),this.servicesVersion++}handleServiceChanged(e){this.debug("service changed"),this.servicesVersion++}handleDisconnected(t){this.debug("disconnected"),this.disconnect(),this.pendingResumeLogOnDisconnection&&(this.pendingResumeLogOnDisconnection=!1,e.U.delay(500).then((()=>this.resumeLog())))}disconnect(){if(super.disconnect(),this.services.forEach((e=>e.disconnect())),this.connected){this.debug("disconnect");try{this.device.gatt&&this.device.gatt.connected&&this.device.gatt.disconnect()}catch(e){this.debug(`gatt disconnect error ${e.message}`)}}}}function h(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const r=[];return n()&&(r.push(l.SERVICE_UUID),r.push(a.SERVICE_UUID)),i()&&r.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:r}).then((n=>(e.log(`ble: received device ${n.name}`),t.bleDevice=new d(n),t.bleDevice.startServices(),t.bleDevice.connectAsync())))}t.BLEDevice=d,t.bleDevice=void 0,t.isPaired=function(){return!!t.bleDevice},t.pairAsync=function(){return t.bleDevice&&(t.bleDevice.kill(),t.bleDevice=void 0),h().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,i){e.tickEvent("webble.flash");const r=n.outfiles[ts.pxtc.BINARY_HEX];return h().then((()=>t.bleDevice.partialFlashingService.flashAsync(r))).then((()=>e.tickEvent("webble.flash.success"))).catch((t=>{throw e.tickEvent("webble.fail.fail",{message:t.message}),t}))}}(e.webBluetooth||(e.webBluetooth={}))}(pxt||(pxt={})),function(e){!function(t){class n extends Error{constructor(e){super(e),this.message=e}}t.USBError=n;t.filters=[{classCode:255,subclassCode:42}];let i,r,s=!0;t.setFilters=function(e){s=!1,t.filters=e};class o{constructor(){this.ready=!1,this.connecting=!1,this.readLoopStarted=!1,this.onDeviceConnectionChanged=e=>{},this.onConnectionChanged=()=>{},this.onData=e=>{},this.onError=e=>{},this.onEvent=e=>{},this.enabled=!1,this.handleUSBConnected=this.handleUSBConnected.bind(this),this.handleUSBDisconnected=this.handleUSBDisconnected.bind(this)}enable(){this.enabled||(this.enabled=!0,this.log("registering webusb events"),navigator.usb.addEventListener("disconnect",this.handleUSBDisconnected,!1),navigator.usb.addEventListener("connect",this.handleUSBConnected,!1))}disable(){this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),navigator.usb.removeEventListener("disconnect",this.handleUSBDisconnected),navigator.usb.removeEventListener("connect",this.handleUSBConnected))}disposeAsync(){return this.disable(),Promise.resolve()}handleUSBDisconnected(e){this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!1))}handleUSBConnected(e){const t=e.device;this.log(`device connected ${t.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!0))}clearDev(){this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,this.onConnectionChanged&&this.onConnectionChanged())}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}disconnectAsync(){return this.ready=!1,this.dev?(this.log("close device"),this.dev.close().catch((e=>{})).then((()=>(this.clearDev(),e.U.delay(500))))):Promise.resolve()}reconnectAsync(){return this.log("reconnect"),this.setConnecting(!0),this.disconnectAsync().then(a).then((e=>this.connectAsync(e))).finally((()=>this.setConnecting(!1)))}setConnecting(e){e!=this.connecting&&(this.connecting=e,this.onConnectionChanged&&this.onConnectionChanged())}isConnecting(){return this.connecting}isConnected(){return!!this.dev&&this.ready}async connectAsync(t){if(this.log(`trying to connect (${t.length} devices)`),0==t.length){const e=new Error("Device not found.");throw e.type="devicenotfound",e}this.setConnecting(!0);try{if(this.lastKnownDeviceSerialNumber){const n=t.find((e=>e.serialNumber===this.lastKnownDeviceSerialNumber));n?(this.log("last known device spotted"),t.splice(t.indexOf(n),1),t.unshift(n)):(this.log("delay for last known device"),await e.U.delay(2e3))}for(let e=0;e<t.length;++e){const n=t[e];this.dev=n,this.log(`connect device: ${n.manufacturerName} ${n.productName}`),this.log(`serial number: ${n.serialNumber} ${this.lastKnownDeviceSerialNumber===n.serialNumber?"(last known device)":""} `);try{return void await this.initAsync()}catch(e){this.dev=void 0,this.log(`connection failed, ${e.message}`)}}const n=new Error(e.U.lf("Device in use or not found."));throw n.type="devicelocked",n}finally{this.setConnecting(!1)}}sendPacketAsync(t){return this.dev?(e.Util.assert(t.length<=64),this.epOut?this.dev.transferOut(this.epOut.endpointNumber,t).then((e=>{"ok"!=e.status&&this.error("USB OUT transfer failed")})):this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t).then((e=>{"ok"!=e.status&&this.error("USB CTRL OUT transfer failed")}))):Promise.reject(new Error("Disconnected"))}readLoop(){if(this.readLoopStarted)return;this.readLoopStarted=!0,this.log("start read loop");let t=()=>{this.ready?this.recvPacketAsync().then((n=>{n[0]?(this.onData(n),t()):e.U.delay(500).then(t)}),(n=>{this.dev&&this.onError(n),e.U.delay(300).then(t)})):e.U.delay(300).then(t)};t()}recvPacketAsync(){let e=e=>{"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);return 0==t.length?this.recvPacketAsync():t};return this.dev?this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64).then(e):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64).then(e):Promise.reject(new Error("Disconnected"))}initAsync(){if(!this.dev)return Promise.reject(new Error("Disconnected"));let n=this.dev;return this.log("open device"),n.open().then((()=>(this.log("select configuration"),n.selectConfiguration(1)))).then((()=>{this.log("got "+n.configurations[0].interfaces.length+" interfaces");const i=n.configurations[0].interfaces.filter((e=>{let n=e.alternates[0];for(let e of t.filters)if((null==e.classCode||n.interfaceClass===e.classCode)&&!(null!=e.subclassCode&&n.interfaceSubclass!==e.subclassCode||null!=e.protocolCode&&n.interfaceProtocol!==e.protocolCode)){if(0==n.endpoints.length)return!0;if(2==n.endpoints.length&&n.endpoints.every((e=>64==e.packetSize)))return!0}return!1}));let r=i[i.length-1];return this.log(`${i.length} matching interfaces; picking ${r?"#"+r.interfaceNumber:"n/a"}`),r||this.error("cannot find supported USB interface"),this.altIface=r.alternates[0],this.iface=r,this.altIface.endpoints.length?(this.log("using dedicated endpoints"),this.epIn=this.altIface.endpoints.filter((e=>"in"==e.direction))[0],this.epOut=this.altIface.endpoints.filter((e=>"out"==e.direction))[0],e.Util.assert(64==this.epIn.packetSize),e.Util.assert(64==this.epOut.packetSize)):this.log("using ctrl pipe"),this.log("claim interface"),n.claimInterface(r.interfaceNumber)})).then((()=>{this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,s&&this.readLoop(),this.onConnectionChanged&&this.onConnectionChanged()}))}}async function a(){e.log("webusb: get devices");try{return await navigator.usb.getDevices()||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==r)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(r=!1);if(e.BrowserUtils.isElectron()||e.BrowserUtils.isWinRT())return e.debug("webusb: off, electron or winrt"),e.tickEvent("webusb.off",{reason:"electronwinrt"}),void(r=!1);const i=navigator.usb;if(!i)return e.debug("webusb: off, not impl"),e.tickEvent("webusb.off",{reason:"notimpl"}),void(r=!1);let s=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(s&&parseFloat(s[1])<6.3)return e.debug("webusb: off, older windows version"),e.tickEvent("webusb.off",{reason:"oldwindows"}),void(r=!1);try{await i.getDevices()}catch(t){return e.debug("webusb: off, security exception"),e.tickEvent("webusb.off",{reason:"security"}),void(r=!1)}r=!0}function c(){return void 0===r&&(console.error("checkAvailableAsync not called"),l()),!!r}t.pairAsync=function(){return navigator.usb.requestDevice({filters:t.filters}).then((e=>!!e)).catch((e=>{if("NotFoundError"!=e.name)throw e}))},t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),i||(i=new o),i.enable(),Promise.resolve(i)},t.isEnabled=!1,t.setEnabled=function(e){c()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.isAvailable=c}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function r(e){let t={},i=0,r=new n.PromiseQueue,s=new Promise(((e,n)=>{t.ready=e}));r.enqueue("main",(()=>s));return{opAsync:function(n,s){return r.enqueue("main",(()=>new Promise(((r,o)=>{let a=""+i++;t[a]=e=>{e?e.errorMessage?o(new Error(e.errorMessage)):r(e):o(new Error("no response"))},e({id:a,op:n,arg:s})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function s(t){let n=new Worker(t),i=r((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),i.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},i}t.getWorker=function(e){let t=i[e];return t||(t=i[e]=s(e)),t},t.wrap=r,t.makeWebWorker=s,t.makeWebSocket=function(t,n=null){let i=new WebSocket(t),s=[],o=r((e=>{let t=JSON.stringify(e);s?s.push(t):i.send(t)}));return i.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):o.recvHandler(t)},i.onopen=t=>{e.debug("socket opened");for(let e of s)i.send(e);s=null},i.onclose=t=>{e.debug("socket closed")},i.onerror=t=>{e.debug("socket errored")},o}}(e.worker||(e.worker={}))}(pxt||(pxt={})),function(e){!function(t){function n(){t.apiKey||e.U.userError("YouTube API key missing")}function i(e){if(!e)return"";const t=e.medium||e.high||e.standard||e.default;return(null==t?void 0:t.url)||""}t.apiKey=void 0,t.playlistItemToCodeCard=function(e){return{name:e.snippet.title.replace(/[^-]*-/,"").trim(),description:(t=e.snippet.description,t.split(/\n\s+/,1)[0].trim()),youTubeId:e.snippet.resourceId.videoId,youTubePlaylistId:e.snippet.playlistId,imageUrl:i(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(i){n();const r=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${i}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(r).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(i){n();let r,s=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${i}&key=${t.apiKey}`;r&&(n+=`&pageToken=${r}`);const o=await e.Util.httpGetJsonAsync(n);s=s.concat(o.items),r=o.nextPageToken}while(r);return e.options.debug&&e.debug(JSON.stringify(s,null,2)),s},t.watchUrl=function(e,t){let n;return e?(n=`https://www.youtube.com/watch?v=${e}`,t&&(n+=`&list=${t}`)):t&&(n=`https://www.youtube.com/playlist?list=${t}`),n}}(e.youtube||(e.youtube={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){function n(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>t[+n]))}t.debug=!1,t.lf=n;let i=l("opcode name doesn't match","<name>");class r{constructor(t,n,i,r,s){this.opcode=i,this.mask=r,this.is32bit=s,this.canBeShared=!1,e.assert((i&r)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,(e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e));let o=a(n);this.name=o[0],this.args=o.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return i;let r=this.opcode,s=1,o=0,a=[],c=null,u=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[s++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return l("expecting register name",p);this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return l("expecting number",p);this.ei.isAddSP(this.opcode)?o=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(o=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return l("expecting {",p);for(f=0;"}"!=n[s];){if(p=n[s++],!p)return l("expecting }",n[s-2]);let e=this.ei.registerNo(p);if(null==e)return l("expecting register name",p);if(f&1<<e)return l("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--,","==n[s]&&s++}p=n[s++]}else if(i.isLabel){if(p=p.replace(/^#/,""),/^[+-]?\d+$/.test(p))f=parseInt(p,10),c="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),c="abs"+f;else if(c=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return l("unknown label",p);f=8}if(this.ei.is32bit(this)){u=f,d=p;continue}}else e.oops();if(null==f)return l("didn't understand it",p);if(a.push(f),f=i.encode(f),null==f)return l("argument out of range or mis-aligned",p);e.assert(0==(r&f)),r|=f}else if(h!=p)return l("expecting "+h,p)}return n[s]?l("trailing tokens",n[s]):this.ei.is32bit(this)?this.ei.emit32(r,u,t.bin.normalizeExternalLabel(d)):{stack:o,opcode:r,numArgs:a,labelName:t.bin.normalizeExternalLabel(c)}}toString(){return this.friendlyFmt}}t.Instruction=r;class s{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=a(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=s;class o{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.currLine=new s(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let r=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;r*=n,t=e[2]}}if("-"==t[0]?(r*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return r*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let s=/(.*)>>(\d+)$/.exec(t);if(s){let e=this.parseOneInt(s[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(s[2])}let o=null;if("0"==t[0])if("x"==t[1]||"X"==t[1]){let e=/^0x([a-f0-9]+)$/i.exec(t);e&&(o=parseInt(e[1],16))}else if("b"==t[1]||"B"==t[1]){let e=/^0b([01]+)$/i.exec(t);e&&(o=parseInt(e[1],2))}if(t.indexOf("@")>=0){let i=/^(\w+)@(-?\d+)$/.exec(t);i&&(1!=r&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(i[1])?o=this.ei.wordSize()*this.ei.computeStackOffset(i[1],this.stack-this.stackpointers[i[1]]+parseInt(i[2])):this.directiveError(n("saved stack not found"))),i=/^(.*)@(hi|lo|fn)$/.exec(t),i&&this.looksLikeLabel(i[1])&&(o=this.lookupLabel(i[1],!0),null!=o&&("fn"==i[2]?o=this.ei.toFnPtr(o,this.baseOffset,i[1]):(o>>=1,0<=o&&o<=65535?"hi"==i[2]?o=o>>8&255:"lo"==i[2]?o&=255:e.oops():(this.directiveError(n("@hi/lo out of range")),o=null))))}return null==o&&this.looksLikeLabel(t)&&(o=this.lookupLabel(t,!0),null!=o&&1==this.ei.postProcessRelAddress(this,1)&&(o+=this.baseOffset)),null==o||isNaN(o)?null:o*r}looksLikeLabel(e){return!/^(r\d|pc|sp|lr)$/i.test(e)&&/^[\.a-zA-Z_][\.:\w+]*$/.test(e)}scopedName(e){return"."==e[0]&&this.scope?this.scope+"$"+e:e}lookupLabel(e,t=!1){let i=null,r=this.scopedName(e);return this.labels.hasOwnProperty(r)?(i=this.labels[r],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(r)&&(i=this.equs[r]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let r,s=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(s&&null!=(r=function(e){e=e.replace(/\\\\/g,"\\B").replace(/\\(['\?])/g,((e,t)=>t)).replace(/\\[z0]/g,"\0").replace(/\\x([0-9a-f][0-9a-f])/gi,((e,t)=>"\\u00"+t)).replace(/\\B/g,"\\\\");try{return JSON.parse(e)}catch(e){return null}}(s[2])))if(this.align(2),t)for(let e=0;e<r.length;e++)this.emitShort(r.charCodeAt(e));else for(let e=0;e<r.length+1;e+=2)this.emitShort(i(r,e+1)<<8|i(r,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],r=t[e+1];0<=i&&r<=255&&0<=r&&i<=255?this.emitShort(255&i|(255&r)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach((e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")}))}handleDirective(e){let t,i=e.words,r=()=>{2!=i.length&&this.directiveError(n("expecting one argument"))};switch(i[0]){case".ascii":case".asciz":case".string":this.emitString(e.text);break;case".utf16":this.emitString(e.text,!0);break;case".align":if(r(),t=this.parseOneInt(i[1]),null!=t){if(0==t)return;t<=4?this.align(1<<t):this.directiveError(n("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))}else this.directiveError(n("expecting number"));break;case".balign":if(r(),t=this.parseOneInt(i[1]),null!=t){if(1==t)return;2==t||4==t||8==t||16==t?this.align(t):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":r(),t=this.parseOneInt(i[1]),null!=t?this.align(1<<t):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(i);break;case".hex":this.emitHex(i);break;case".hword":case".short":case".2bytes":this.parseNumbers(i).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(i).forEach((e=>{-2147483648<=e&&e<=4294967295?(this.emitShort(65535&e),this.emitShort(e>>16&65535)):this.directiveError(n("expecting int32"))}));break;case".skip":case".space":this.emitSpace(i);break;case".set":case".equ":/^\w+$/.test(i[1])||this.directiveError(n("expecting name"));const s=this.parseNumbers(i.slice(","==i[2]||"="==i[2]?2:1));1!=s.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[i[1]]&&this.equs[i[1]]!=s[0]&&this.directiveError(n("redefinition of {0}",i[1])),this.equs[i[1]]=s[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),r(),this.baseOffset=this.parseOneInt(i[1]);break;case"@stackmark":r(),this.stackpointers[i[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[i[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[i[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=i[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":r(),this.stack+=this.parseOneInt(i[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{i=i.filter((e=>","!=e)),i.shift();let e=this.parseOneInt(i[1]),t=0;if(t=i[2]?this.parseOneInt(i[2]):4,null==this.lookupLabel(i[0])){for(this.commPtr||(this.commPtr=this.lookupExternalLabel("_pxt_comm_base")||0,this.commPtr||this.directiveError(n("PXT_COMM_BASE not defined")));this.commPtr&t-1;)this.commPtr++;this.labels[this.scopedName(i[0])]=this.commPtr-this.baseOffset,this.commPtr+=e}break}case".file":case".text":case".cpu":case".fpu":case".eabi_attribute":case".code":case".thumb_func":case".type":case".fnstart":case".save":case".size":case".fnend":case".pad":case".globl":case".local":case"@":break;default:/^\.cfi_/.test(i[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),r="",s=t(i).concat(t(i+"s"));s.length>0&&s.forEach((t=>{let i=t.emit(e);r+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)})),this.pushError(n("assembly error"),r)}buildLine(e,t){let n=e=>{let n=new s(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),r=a(i.text)||[];i.words=r;let o=r[0]||"";if(":"==o.charAt(o.length-1)){let t=/^([\.\w]+):$/.exec(r[0]);if(t){if(i.type="label",i.text=t[1]+":",i.words=[t[1]],!(r.length>1))return;r.shift(),i=n(e.replace(/^[^:]*:/,"")),i.words=r,o=r[0]||""}}let l=o.charAt(0);"."==l||"@"==l?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach((e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))}))}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach((t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}))}getSourceMap(){const e={};let t="",n=0,i=0,r=0;function s(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,r-i)),i=0,r=0}return this.lines.forEach(((e,o)=>{const a=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);a&&(s(),t=a[1],n=parseInt(a[2])),"instruction"==e.type&&(i||(i=e.location),r=e.location)})),s(),e}getSource(i,r=1,s=0){let o=0,a=e=>{let t=this.labels[e]||o,n=t-o;return o=t,n},l=this.buf?this.location():0,c=a("_code_end"),u=a("_helpers_end"),d=a("_vtables_end"),h=a("_literals_end"),p=o,f=l+this.baseOffset&16777215;s&&f>s&&e.U.userError(n("program too big by {0} bytes!",f-s));let m=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",f,(100*f/(s=s||131072)).toFixed(1),(s/1024).toFixed(1),s-f),g=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",p,c,u,d,h,l-p)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*c/r)/100,r)+m+"\n"+this.stats+"\n\n",b=!1;return this.lines.forEach(((e,n)=>{if("_stored_program"==e.words[0])return g+='_stored_program: .string "..."\n',void(b=!0);if(b)return void(b=!1);let r=e.text;if(i){if("@stackempty"==e.words[0]&&this.lines[n-1].text==e.text)return;if(r=r.replace(/; WAS: .*/,""),!r.trim())return}t.debug&&("label"!=e.type&&"instruction"!=e.type||(r+=` \t; 0x${(e.location+this.baseOffset).toString(16)}`)),g+=r+"\n"})),g}peepHole(){let e=this.lines.filter((e=>"empty"!=e.type));for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let r=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,r)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,((e,t)=>t+this.baseOffset))),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=o;t.VMFile=class extends o{constructor(e){super(e)}};function a(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function l(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function c(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let s=new r(this,e,t,n,i);return this.instructions.hasOwnProperty(s.name)||(this.instructions[s.name]=[]),this.instructions[s.name].push(s),s},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=l,t.expectError=function(t,n){let i=new o(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=c,t.expect=function(t,n){let i=[],r=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),""))),s=new o(t);s.throwOnError=!0,s.disablePeepHole=!0,s.emit(r),s.errors.length>0&&(console.debug(s.errors[0].message),e.oops("ASMTEST: not expecting errors")),s.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)s.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+c(i[t])+", got: "+c(s.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i=!0;function r(t){let i=new Error(n.lf("Cannot access {0} while offline",t));return i.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(i)))}function s(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function a(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const i=new Date,r=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+r,e.webConfig.cdnUrl+"/api/"+n}function l(e){return o()?(e.url=a(e.url),n.requestAsync(e).catch((t=>c(e,t)))):u(e)}function c(e,n){return 0==n.statusCode?(i&&(i=!1,t.onOffline()),r(e.url)):Promise.reject(n)}function u(i){var s;return i.url=(null===(s=e.webConfig)||void 0===s?void 0:s.isStatic)&&!i.forceLiveEndpoint?e.webConfig.relprefix+i.url:t.apiRoot+i.url,i.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(i.headers||(i.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(i.headers.Authorization=t.localToken):t.accessToken&&(i.headers["x-td-access-token"]=t.accessToken),n.requestAsync(i).catch((e=>c(i,e)))):r(i.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=s,t.useCdnApi=o,t.cdnApiUrl=a,t.apiRequestWithCdnAsync=l,t.privateRequestAsync=u,t.privateGetTextAsync=function(e,t){return u({url:e,headers:t}).then((e=>e.text))},t.privateGetAsync=function(e,t=!1){return u({url:e,forceLiveEndpoint:t}).then((e=>e.json))},t.downloadTargetConfigAsync=function(){if(!t.isOnline())return Promise.resolve(void 0);const n=e.appTarget.versions&&e.appTarget.versions.target,i=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?s(i).then((e=>e?e.json:void 0)):l({url:i}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text",forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.markdownAsync=async function(t,n){const i=e.BrowserUtils.isLocalHostDev()?0:36e5,r=24*i*7;n=n||e.Util.userLanguage();const a=await e.BrowserUtils.translationDbAsync(),c=await a.getAsync(n,t,""),d=async()=>{try{const i=await function(t,n,i){var r;const a=null===(r=e.webConfig)||void 0===r?void 0:r.isStatic,c=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(a){d=t;const e=/\/?docs\//.test(d),n=/\.\w+$/.test(d);if(!e){const e="/"===d[0];d=`docs${e?"":"/"}${d}`}n||(d=`${d}.md`)}else d=`md/${e.appTarget.id}/${t.replace(/^\//,"")}?targetVersion=${encodeURIComponent(c)}`;"en"!=n&&(d+=`${a?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return s(d).then((e=>404==e.statusCode?u({url:d,method:"GET"}).then((e=>({md:e.text,etag:e.headers.etag}))):{md:e.text,etag:void 0}));{const e=i&&!o()?{"If-None-Match":i}:void 0;return l({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==c?void 0:c.etag);return!c||i.md&&c.md!==i.md?(await a.setAsync(n,t,"",i.etag,void 0,i.md),i.md):c.md}catch(e){return""}};if(c){const t=Date.now()-c.time,n=t>i;if(t>r)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),d()),c.md)return c.md}return d()},t.privateDeleteAsync=function(e){return u({url:e,method:"DELETE"}).then((e=>e.json))},t.privatePostAsync=function(e,t,n=!1){return u({url:e,data:t||{},forceLiveEndpoint:n}).then((e=>e.json))},t.isLoggedIn=function(){return!!t.accessToken},t.isNavigatorOnline=d,t.isOnline=function(){return"undefined"!=typeof navigator&&d()&&(i=!0),i},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){const i=e.appTarget;if(!(t&&i.appTheme&&i.cloud&&i.cloud.sharing))return;let r=["makecode.com"];i.appTheme.embedUrl&&r.push(i.appTheme.embedUrl),i.appTheme.shareUrl&&r.push(i.appTheme.shareUrl),r=n.unique(r,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const s=`^((https://)?(?:${r.join("|")})/)?(?:v[0-9]+/)?(api/oembed?url=.*%2F([^&]*)&.*?|([a-z0-9-_]+))$`,o=new RegExp(s,"i").exec(t.trim()),a=o&&(!o[1]||r.indexOf(n.escapeForRegex(o[1].replace(/https:\/\//,"").replace(/\/$/,"")).toLowerCase())>=0)&&(o[3]||o[4])?o[3]?o[3]:o[4]:null;return a&&("_"==a[0]&&13==a.length||23==a.length&&/^[0-9\-]+$/.test(a))?a:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,i){let r=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(c).join(""),s=4,o=0,a=0,l=e=>{o|=e<<a,a==8-n?(r+=c(o),s++,o=0,a=0):a+=n};for(let r=0;r<e;++r){for(let e=0;e<t;++e)l(i(r,e));for(;0!=a;)l(0);if(n>1)for(;3&s;)l(0)}return r;function c(e){return("0"+e.toString(16)).slice(-2)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){function t(e){let t="";switch(e){case 0:t="C5";break;case 1:t="B";break;case 2:t="A";break;case 3:t="G";break;case 4:t="F";break;case 5:t="E";break;case 6:t="D";break;case 7:t="C"}return t}function n(e){let t=-1;switch(e){case"C5":t=0;break;case"B":t=1;break;case"A":t=2;break;case"G":t=3;break;case"F":t=4;break;case"E":t=5;break;case"D":t=6;break;case"C":t=7}return t}e.MelodyArray=class{constructor(e){this.numCols=8,this.numRows=8,this.polyphonic=!1,e&&(this.tempo=e),this.resetMelody()}setTempo(e){this.tempo=e}getArray(){return this.melody}setArray(e){this.melody=e}getColor(e){return 0}getValue(e,t){return this.melody[e][t]}getWidth(){return this.numCols}getHeight(){return this.numRows}updateMelody(e,t){const n=!this.melody[e][t];if(n&&!this.polyphonic)for(let e=0;e<this.numRows;e++)this.melody[e][t]=!1;this.melody[e][t]=n}getStringRepresentation(){let e="",n=new Array(this.numCols),i=0;for(let e=0;e<this.numRows;e++){let r=0;n[e]=[];for(let i=0;i<this.numCols;i++)this.melody[i][e]&&(n[e].push(t(i)),r++);r>i&&(i=r)}if(0==i)return"- - - - - - - - ";for(let t=0;t<i;t++)for(let t=0;t<this.numCols;t++)n[t]&&n[t].length>0?e+=n[t].shift()+" ":e+="- ";return e}parseNotes(e){let t=(e=e.trim()).split(" ");for(let e=0;e<t.length;e++){for(let t=0;t<this.numRows;t++)this.melody[t][e]=!1;"-"!=t[e]&&(this.melody[n(t[e])][e]=!0)}}setPolyphonic(e){this.polyphonic=e}isPolyphonic(){return this.polyphonic}resetMelody(){this.melody=new Array(this.numCols);for(let e=0;e<this.numCols;e++)this.melody[e]=new Array(this.numRows).fill(!1)}},e.rowToNote=t,e.noteToRow=n,e.getColorClass=function(e){let t="melody-default";switch(e){case 0:t="melody-red";break;case 1:t="melody-orange";break;case 2:t="melody-yellow";break;case 3:t="melody-green";break;case 4:t="melody-teal";break;case 5:t="melody-blue";break;case 6:t="melody-purple";break;case 7:t="melody-violet"}return t}}(pxtmelody||(pxtmelody={})),function(e){function t(e,t,n){return function(e,t,n){if(t)for(const n of Object.keys(t))"className"===n?e.setAttribute("class",t[n]+""):e.setAttribute(n,t[n]+"");n&&e.addEventListener("click",n);return e}(document.createElement(e),t,n)}e.MelodyGallery=class{constructor(){this.value=null,this.visible=!1,this.timeouts=[],this.numSamples=e.SampleMelodies.length,this.containerDiv=document.createElement("div"),this.containerDiv.setAttribute("id","melody-editor-gallery-outer"),this.contentDiv=document.createElement("div"),this.contentDiv.setAttribute("id","melody-editor-gallery"),this.itemBackgroundColor="#DCDCDC",this.itemBorderColor="white",this.initStyles(),this.containerDiv.appendChild(this.contentDiv),this.containerDiv.style.display="none",this.contentDiv.addEventListener("animationend",(()=>{this.visible||(this.containerDiv.style.display="none")})),this.contentDiv.addEventListener("wheel",(e=>{e.stopPropagation()}),!0)}getElement(){return this.containerDiv}getValue(){return this.value}show(e){this.pending=e,this.containerDiv.style.display="block",this.buildDom(),this.visible=!0,pxt.BrowserUtils.removeClass(this.contentDiv,"hidden-above"),pxt.BrowserUtils.addClass(this.contentDiv,"shown")}hide(){this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody()}clearDomReferences(){this.contentDiv=null,this.containerDiv=null}layout(e,t,n){this.containerDiv.style.left=e+"px",this.containerDiv.style.top=t+"px",this.containerDiv.style.height=n+"px"}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.buttons=[];for(let e=0;e<t.length;e++)this.mkButton(t[e],e,"255px","45px")}initStyles(){const e=document.createElement("style");e.textContent="\n #melody-editor-gallery {\n margin-top: -100%;\n }\n\n #melody-editor-gallery.hidden-above {\n margin-top: -100%;\n animation: slide-up 0.2s 0s ease;\n }\n\n #melody-editor-gallery.shown {\n margin-top: 0px;\n animation: slide-down 0.2s 0s ease;\n }\n\n @keyframes slide-down {\n 0% {\n margin-top: -100%;\n }\n 100% {\n margin-top: 0px;\n }\n }\n\n @keyframes slide-up {\n 0% {\n margin-top: 0px;\n }\n 100% {\n margin-top: -100%;\n }\n }\n ",this.containerDiv.appendChild(e)}mkButton(e,n,i,r){const s=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),o=t("i",{className:"music icon melody-icon"}),a=t("div",{className:"melody-editor-text"});a.innerText=e.name;const l=this.createColorBlock(e),c=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));c.appendChild(o),c.appendChild(a),c.appendChild(l),s.appendChild(c);const u=t("div",{className:"melody-editor-button right-button",role:"button",title:lf("Preview {0}",e.name)},(()=>this.togglePlay(e,n))),d=t("i",{className:"play icon"});this.buttons[n]=d,u.appendChild(d),s.appendChild(u),this.contentDiv.appendChild(s)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let i=0;switch(e){case"C5":i=523;break;case"B":i=494;break;case"A":i=440;break;case"G":i=392;break;case"F":i=349;break;case"E":i=330;break;case"D":i=294;break;case"C":i=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(i)}),t*this.getDuration(n))),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration(n)))}getDuration(e){return 6e4/e}previewMelody(e){this.stopMelody();let t=e.notes.split(" ");for(let n=0;n<t.length;n++)this.playNote(t[n],n,e.tempo)}togglePlay(e,t){let n=this.buttons[t];pxt.BrowserUtils.containsClass(n,"play icon")?(this.resetPlayIcons(),pxt.BrowserUtils.removeClass(n,"play icon"),pxt.BrowserUtils.addClass(n,"stop icon"),this.previewMelody(e),this.timeouts.push(setTimeout((()=>{pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon")}),e.notes.split(" ").length*this.getDuration(e.tempo)))):(pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon"),this.stopMelody())}stopMelody(){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop()}resetPlayIcons(){for(let e=0;e<this.numSamples;e++){let t=this.buttons[e];if(pxt.BrowserUtils.containsClass(t,"stop icon")){pxt.BrowserUtils.removeClass(t,"stop icon"),pxt.BrowserUtils.addClass(t,"play icon");break}}}createColorBlock(t){let n=document.createElement("div");pxt.BrowserUtils.addClass(n,"melody-color-block");let i=t.notes.split(" ");for(let t=0;t<i.length;t++){let r=e.getColorClass(e.noteToRow(i[t])),s=document.createElement("div");0==t?pxt.BrowserUtils.addClass(s,"left-edge sliver "+r):t==i.length-1?pxt.BrowserUtils.addClass(s,"right-edge sliver "+r):pxt.BrowserUtils.addClass(s,"sliver "+r),n.appendChild(s)}return n}}}(pxtmelody||(pxtmelody={})),function(e){class t{constructor(e,t,n){this.name=e,this.notes=t,this.tempo=n}}e.MelodyInfo=t,e.SampleMelodies=[new t(lf("Scale"),"C5 B A G F E D C",120),new t(lf("Reverse"),"C D E F G A B C5",120),new t(lf("Mystery"),"E B C5 A B G A F",120),new t(lf("Gilroy"),"A F E F D G E F",120),new t(lf("Falling"),"C5 A B G A F G E",120),new t(lf("Hopeful"),"G B A G C5 B A B",120),new t(lf("Tokyo"),"B A G A G F A C5",120),new t(lf("Paris"),"G F G A - F E D",120),new t(lf("Rising"),"E D G F B A C5 B",120),new t(lf("Sitka"),"C5 G B A F A C5 B",120)]}(pxtmelody||(pxtmelody={})),function(e){!function(t){t.browserDownloadAsync=function(t,n,i){let r;return e.winrt.promisify(Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(n,Windows.Storage.CreationCollisionOption.replaceExisting).then((e=>Windows.Storage.FileIO.writeTextAsync(r=e,t))).then((()=>Windows.System.Launcher.launchFileAsync(r))).then((e=>{})))},t.saveOnlyAsync=function(t){const n=e.appTarget.compile.useUF2,i=n?[".uf2"]:[".hex"],r=new Windows.Storage.Pickers.FileSavePicker;return r.suggestedStartLocation=Windows.Storage.Pickers.PickerLocationId.documentsLibrary,r.fileTypeChoices.insert("MakeCode binary file",i),r.suggestedFileName=t.downloadFileBaseName,e.winrt.promisify(r.pickSaveFileAsync().then((i=>{if(i){let r=n?t.outfiles[pxtc.BINARY_UF2]:t.outfiles[pxtc.BINARY_HEX];e.isOutputText()||(r=atob(r));const s=[];return e.Util.stringToUint8Array(r).forEach((e=>s.push(e))),Windows.Storage.FileIO.writeBytesAsync(i,s).then((()=>!0))}return Promise.resolve(!1)})))}}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.onDeviceConnectionChanged=e=>{},this.onConnectionChanged=()=>{},this.onData=e=>{},this.onEvent=e=>{},this.onError=e=>{},this.connecting=!1,this.handleInputReport=this.handleInputReport.bind(this)}disposeAsync(){return Promise.resolve()}error(t){throw new Error(e.U.lf("USB/HID error ({0})",t))}setConnecting(e){this.connecting=e,this.onConnectionChanged&&this.onConnectionChanged()}isConnecting(){return this.connecting}isConnected(){return!!this.dev}reconnectAsync(){return this.disconnectAsync().then((()=>this.initAsync()))}isSwitchingToBootloader(){o=!0,this.dev&&(a=!0)}disconnectAsync(){if(this.dev){const e=this.dev;delete this.dev;try{e.close()}catch(e){}this.onConnectionChanged&&this.onConnectionChanged()}return Promise.resolve()}sendPacketAsync(t){if(!this.dev)return Promise.resolve();const n=[0];for(let e=0;e<Math.max(t.length,64);++e)n.push(t[e]||0);const i=new Windows.Storage.Streams.DataWriter;i.writeBytes(n);const r=i.detachBuffer(),s=this.dev.createOutputReport(0);return s.data=r,e.winrt.promisify(this.dev.sendOutputReportAsync(s).then((e=>{})))}handleInputReport(e){const t=Windows.Storage.Streams.DataReader.fromBuffer(e.report.data),n=[];for(;t.unconsumedBufferLength;)n.push(t.readByte());65==n.length&&0===n[0]&&n.shift(),this.onData(new Uint8Array(n))}initAsync(n=!1){e.Util.assert(!this.dev,"HID interface not properly reseted");const r=Windows.Devices,s=r.HumanInterfaceDevice.HidDevice,o=()=>{const t=new Error(e.U.lf("Device not found"));return t.type="devicenotfound",Promise.reject(t)},a=i.reduce(((e,t)=>e.then((e=>e&&e.length?Promise.resolve(e):r.Enumeration.DeviceInformation.findAllAsync(t,null)))),Promise.resolve(null));let l;return this.setConnecting(!0),a.then((t=>{if(!t||!t[0])return e.debug("no hid device found"),Promise.reject(new Error("no hid device found"));e.debug(`hid enumerate ${t.length} devices`);const n=t[0];return e.debug(`hid connect to ${n.name} (${n.id})`),l=n.id,s.fromIdAsync(n.id,Windows.Storage.FileAccessMode.readWrite)})).then((t=>{if(this.dev=t,!this.dev){e.debug("can't connect to hid device");let t=Windows.Devices.Enumeration.DeviceAccessInformation.createFromId(l).currentStatus;return e.reportError("winrt_device",`could not connect to HID device; device status: ${t}`),Promise.reject(new Error("can't connect to hid device"))}return e.debug(`hid device version ${this.dev.version}`),this.dev.addEventListener("inputreportreceived",this.handleInputReport),Promise.resolve()})).finally((()=>{this.setConnecting(!1)})).catch((e=>n?o():t.bootloaderViaBaud(this).then((()=>this.initAsync(!0))).catch((()=>o()))))}}t.WinRTPacketIO=n,t.packetIO=void 0,t.mkWinRTPacketIOAsync=function(){return e.debug("packetio: mk winrt packetio"),t.packetIO=new n,t.packetIO.initAsync().catch((e=>(t.packetIO=void 0,Promise.reject(e)))).then((()=>t.packetIO))};const i=[],r=[];let s=0,o=!1,a=!1;t.initWinrtHid=function(n,l){const c=Windows.Devices,u=Windows.Devices.Enumeration.DeviceInformation,d=c.HumanInterfaceDevice.HidDevice;e.appTarget&&e.appTarget.compile&&e.appTarget.compile.hidSelectors&&e.appTarget.compile.hidSelectors.forEach((e=>{const t=d.getDeviceSelector(parseInt(e.usagePage),parseInt(e.usageId),parseInt(e.vid),parseInt(e.pid));i.indexOf(t)<0&&i.push(t)})),i.forEach((i=>{const c=u.createWatcher(i,null);c.addEventListener("added",(t=>{e.debug(`new hid device detected: ${t.id}`),o?o=!1:(++s,1===s&&n&&n())})),c.addEventListener("removed",(i=>{e.debug(`hid device closed: ${i.id}`),a?a=!1:(--s,s>0&&n?n():0===s&&l&&(l(),t.packetIO=void 0))})),c.addEventListener("updated",(e=>{})),r.push(c)})),r.filter((e=>!e.status)).forEach((e=>e.start()))}}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){let n,i,r={};function s(t){if(!t)return Promise.resolve([]);const n=Windows.Devices,i=n.SerialCommunication.SerialDevice,r=n.Enumeration.DeviceInformation,s=[];t.forEach((e=>{const t=i.getDeviceSelectorFromUsbVidPid(parseInt(e.vid),parseInt(e.pid));s.push(t)}));return s.reduce(((e,t)=>{let n;return e.then((e=>(n=e,r.findAllAsync(t,null)))).then((e=>{if(n)for(let t=0;t<e.length;++t)n.push(e[t]);else n=e;return Promise.resolve(n)}))}),Promise.resolve(null)).then((t=>t?e.U.promiseMapAll(t,(t=>e.winrt.promisify(i.fromIdAsync(t.id)))):Promise.resolve([])))}function o(t){i&&!i.test(t.name)||(e.debug(`serial port added ${t.name} - ${t.id}`),r[t.id]={info:t},Windows.Devices.SerialCommunication.SerialDevice.fromIdAsync(t.id).then((e=>{r[t.id].device=e,c(t.id)})))}function a(e){delete r[e.id]}function l(e){const t=r[e.id];t&&t.info.update(e)}t.initSerial=function(){const t=!!(e.appTarget.serial&&(e.appTarget.serial.nameFilter||e.appTarget.serial.vendorId&&e.appTarget.serial.productId));if(!(!!e.appTarget.serial&&e.appTarget.serial.log)||!t)return;const r=Windows.Devices.SerialCommunication.SerialDevice;let s;e.appTarget.serial.vendorId&&e.appTarget.serial.productId?s=r.getDeviceSelectorFromUsbVidPid(parseInt(e.appTarget.serial.vendorId),parseInt(e.appTarget.serial.productId)):(i=new RegExp(e.appTarget.serial.nameFilter),s=r.getDeviceSelector()),n=Windows.Devices.Enumeration.DeviceInformation.createWatcher(s,null),n.addEventListener("added",o),n.addEventListener("removed",a),n.addEventListener("updated",l),n.start()},t.suspendSerialAsync=function(){n&&(n.stop(),n.removeEventListener("added",o),n.removeEventListener("removed",a),n.removeEventListener("updated",l),n=void 0);let t=Promise.resolve();return Object.keys(r).forEach((n=>{const i=r[n],s=i.readingOperation;if(s){const n=e.Util.defer();i.cancellingDeferred=n,t=t.then((()=>e.U.promiseTimeout(500,n.promise).catch((t=>{e.reportError("winrt_device",`could not cancel reading operation for a device: ${t.message}`)})))),s.cancel()}})),t.then((()=>{Object.keys(r).forEach((e=>{const t=r[e];if(t.device){t.device.close()}})),r={}}))},t.bootloaderViaBaud=function(t){if(!(e.appTarget&&e.appTarget.compile&&e.appTarget.compile.useUF2&&e.appTarget.simulator&&e.appTarget.simulator.boardDefinition&&e.appTarget.simulator.boardDefinition.bootloaderBaudSwitchInfo))return Promise.reject(new Error("device does not support switching to bootloader via baudrate"));let n;const i=e.appTarget.simulator.boardDefinition.bootloaderBaudSwitchInfo;return s([{vid:i.vid,pid:i.pid,usageId:void 0,usagePage:void 0}]).then((i=>i&&0!==i.length?(n=i,n.length&&t.isSwitchingToBootloader(),n.forEach((e=>{e.baudRate=1200,e.close()})),e.U.delay(1500)):Promise.reject(new Error("no serial devices to switch into bootloader"))))},t.connectSerialDevicesAsync=s;function c(t){let n=r[t];if(!n)return;if(!n.device){let n=Windows.Devices.Enumeration.DeviceAccessInformation.createFromId(t).currentStatus;return void e.reportError("winrt_device",`could not connect to serial device; device status: ${n}`)}const i=Windows.Storage.Streams;n.device.baudRate=115200;let s=n.device.inputStream,o=new i.DataReader(s);o.inputStreamOptions=i.InputStreamOptions.partial;let a={},l=()=>{r[t]&&!n.cancellingDeferred&&(n.readingOperation=o.loadAsync(32),n.readingOperation.then((n=>{let i=o.readString(4*Math.floor(o.unconsumedBufferLength/4));e.Util.bufferSerial(a,i,t),setTimeout((()=>l()),1)}),(e=>{n.readingOperation.operation.status===Windows.Foundation.AsyncStatus.canceled?(o.detachStream(),o.close(),n.cancellingDeferred&&setTimeout((()=>n.cancellingDeferred.resolve()),25)):setTimeout((()=>c(t)),1e3)})))};setTimeout((()=>l()),100)}}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof Windows}function i(){return n()?(l.resolve(null),l.promise.then((e=>Promise.resolve(e&&e.kind===Windows.ApplicationModel.Activation.ActivationKind.file)))):Promise.resolve(!1)}function r(){return n()?Promise.resolve().then((()=>t.packetIO?(e.log("disconnecting packetIO"),t.packetIO.disconnectAsync()):Promise.resolve())).catch((t=>{t.message=`error disconnecting packetIO: ${t.message}`,e.reportException(t)})).then((()=>(e.log("suspending serial"),t.suspendSerialAsync()))).catch((t=>{t.message=`error suspending serial: ${t.message}`,e.reportException(t)})):Promise.resolve()}function s(e){Windows.UI.WebUI.WebUIApplication.removeEventListener("activated",s),l.resolve(e)}function o(t){e.log("suspending");const n=t.suspendingOperation.getDeferral();return r().then((()=>n.complete()),(e=>n.complete())).then()}function a(n){e.log("resuming"),t.packetIO&&(e.log("reconnet pack io"),t.packetIO.reconnectAsync()),t.initSerial()}let l,c;function u(t,n=!1){if(t.kind===Windows.ApplicationModel.Activation.ActivationKind.file){let i=t.files.getAt(0);if(i&&i.isOfType(Windows.Storage.StorageItemTypes.file)){let t=i;Windows.Storage.FileIO.readBufferAsync(t).then((t=>{let n=[],i=Windows.Storage.Streams.DataReader.fromBuffer(t);for(;i.unconsumedBufferLength;)n.push(i.readByte());return i.close(),e.cpp.unpackSourceFromHexAsync(new Uint8Array(n))})).then((e=>c(e,{openHomeIfFailed:n})))}}}e.BrowserUtils.isWinRT=n,t.promisify=function(e){return new Promise(((t,n)=>{e.then((e=>t(e)),(e=>n(e)))}))},t.toArray=function(e){let t=[],n=e.length;for(let i=0;i<n;++i)t.push(e[i]);return t},t.isWindows=function(){return!!navigator&&/Win32/i.test(navigator.platform)},t.isWinRT=n,t.initAsync=function(r){if(!n()||e.BrowserUtils.isIFrame())return Promise.resolve();const l=Windows.UI.Core,d=l.SystemNavigationManager.getForCurrentView(),h=Windows.UI.WebUI.WebUIApplication;return h.addEventListener("suspending",o),h.addEventListener("resuming",a),d.onbackrequested=t=>{e.log("BACK NAVIGATION"),d.appViewBackButtonVisibility=l.AppViewBackButtonVisibility.collapsed,t.handled=!0},t.initSerial(),i().then((()=>{r&&(c=r,h.removeEventListener("activated",s),h.addEventListener("activated",u))}))},t.captureInitialActivation=function(){if(!n())return;l=e.Util.defer(),Windows.UI.WebUI.WebUIApplication.addEventListener("activated",s)},t.loadActivationProject=function(){return l.promise.then((e=>u(e,!0)))},t.hasActivationProjectAsync=i,t.releaseAllDevicesAsync=r}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){var i=e.Util;let r;function s(...e){return e.join("\\")}function o(n){const i=s(r.path,n);return e.debug(`winrt: reading ${i}`),t.promisify(Windows.Storage.StorageFile.getFileFromPathAsync(i).then((e=>Windows.Storage.FileIO.readTextAsync(e))))}function a(n,i,o){const a=s(r.path,n);return e.debug(`winrt: writing ${s(a,i)}`),t.promisify(Windows.Storage.StorageFolder.getFolderFromPathAsync(a)).then((e=>e.createFileAsync(i,Windows.Storage.CreationCollisionOption.replaceExisting))).then((e=>Windows.Storage.FileIO.writeTextAsync(e,o))).then((()=>{}))}function l(e,t=null){let n=new Error(t||"Error "+e);throw n.statusCode=e,n}n.fileApiAsync=function(n,h){if(i.startsWith(n,"pkg/")){let d=n.slice(4);return h?function(n,d){return e.debug(`winrt: writing package at ${n}`),t.promisify(r.createFolderAsync(n,Windows.Storage.CreationCollisionOption.openIfExists)).then((()=>i.promiseMapAll(d.files,(t=>o(s(n,t.name)).then((n=>{if(t.name!=e.SIMSTATE_JSON&&t.name!=e.ASSETS_FILE){if(t.name==e.CONFIG_NAME)try{JSON.parse(t.content).name||(e.log("Trying to save invalid JSON config"),l(410))}catch(t){e.log("Trying to save invalid format JSON config"),l(410)}n!==t.prevContent&&(e.log(`merge error for ${t.name}: previous content changed...`),l(409))}}),(e=>{})))))).then((()=>i.promiseMapAll(d.files,(e=>a(n,e.name,e.content))))).then((()=>a(n,c,JSON.stringify(d.header,null,4)))).then((()=>u(n,!1)))}(d,h):u(d,!0)}if("list"==n)return function(){if(r)return Promise.resolve();const n=Windows.Storage.ApplicationData.current.localFolder;return e.debug("winrt: initializing workspace"),t.promisify(n.createFolderAsync(e.appTarget.id,Windows.Storage.CreationCollisionOption.openIfExists)).then((t=>{r=t,e.debug(`winrt: initialized workspace at ${r.path}`)})).then((()=>{}))}().then(d);throw l(404)};const c=".header.json";function u(n,a){return e.debug(`winrt: reading package under ${n}`),o(s(n,e.CONFIG_NAME)).then((l=>{const u=JSON.parse(l);return i.promiseMapAll(e.allPkgFiles(u),(i=>function(n){const i=s(r.path,n);return e.debug(`winrt: ${i}`),t.promisify(Windows.Storage.StorageFile.getFileFromPathAsync(i).then((e=>e.getBasicPropertiesAsync().then((e=>({name:n,mtime:e.dateModified.getTime()}))))))}(s(n,i)).then((e=>{const t={name:i,mtime:e?e.mtime:null};return null!=e&&a?o(s(n,i)).then((e=>(t.content=e,t))):t})))).then((e=>{const t={path:n,header:null,config:u,files:e};return o(s(n,c)).then((e=>{e&&(t.header=JSON.parse(e))}),(e=>{})).then((()=>t))}))}))}function d(){return t.promisify(r.getFoldersAsync()).then((e=>i.promiseMapAll(e,(e=>u(e.name,!1))))).then((e=>Promise.resolve({pkgs:e})))}function h(){return t.promisify(r.deleteAsync(Windows.Storage.StorageDeleteOption.default).then((()=>{r=void 0})))}n.getProvider=function(e){return{listAsync:e.listAsync,getAsync:e.getAsync,setAsync:e.setAsync,resetAsync:h}}}(t.workspace||(t.workspace={}))}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){let n,i,r,s;!function(e){e[e.Stopped=0]="Stopped",e[e.Pending=1]="Pending",e[e.Starting=2]="Starting",e[e.Running=3]="Running"}(n=t.SimState||(t.SimState={})),t.isBlocks=function(t){return e.U.endsWith(t.name,".blocks")},function(e){e.HeaderOnly="errorListHeader",e.Expanded="errorListExpanded"}(i=t.ErrorListState||(t.ErrorListState={})),function(e){e[e.Hidden=0]="Hidden",e[e.Visible=1]="Visible",e[e.Disabled=2]="Disabled"}(r=t.FilterState||(t.FilterState={})),t.initExtensionsAsync=e=>Promise.resolve({}),t.initFieldExtensionsAsync=e=>Promise.resolve({}),t.HELP_IMAGE_URI="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYiIGhlaWdodD0iMjYiIHZpZXdCb3g9IjAgMCAyNiAyNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTMiIGN5PSIxMyIgcj0iMTMiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNy45NTIgOS4xODQwMkMxNy45NTIgMTAuMjU2IDE3LjgxNiAxMS4wNzIgMTcuNTQ0IDExLjYzMkMxNy4yODggMTIuMTkyIDE2Ljc1MiAxMi43OTIgMTUuOTM2IDEzLjQzMkMxNS4xMiAxNC4wNzIgMTQuNTc2IDE0LjU4NCAxNC4zMDQgMTQuOTY4QzE0LjA0OCAxNS4zMzYgMTMuOTIgMTUuNzM2IDEzLjkyIDE2LjE2OFYxNi45NkgxMS44MDhDMTEuNDI0IDE2LjQ2NCAxMS4yMzIgMTUuODQgMTEuMjMyIDE1LjA4OEMxMS4yMzIgMTQuNjg4IDExLjM4NCAxNC4yODggMTEuNjg4IDEzLjg4OEMxMS45OTIgMTMuNDg4IDEyLjUzNiAxMi45NjggMTMuMzIgMTIuMzI4QzE0LjEwNCAxMS42NzIgMTQuNjI0IDExLjE2OCAxNC44OCAxMC44MTZDMTUuMTM2IDEwLjQ0OCAxNS4yNjQgOS45NjgwMiAxNS4yNjQgOS4zNzYwMkMxNS4yNjQgOC4yMDgwMiAxNC40MTYgNy42MjQwMiAxMi43MiA3LjYyNDAyQzExLjc2IDcuNjI0MDIgMTAuNzUyIDcuNzM2MDIgOS42OTYgNy45NjAwMkw5LjE0NCA4LjA4MDAyTDkgNi4wODgwMkMxMC40ODggNS41NjAwMiAxMS44NCA1LjI5NjAyIDEzLjA1NiA1LjI5NjAyQzE0LjczNiA1LjI5NjAyIDE1Ljk2OCA1LjYwODAyIDE2Ljc1MiA2LjIzMjAyQzE3LjU1MiA2Ljg0MDAyIDE3Ljk1MiA3LjgyNDAyIDE3Ljk1MiA5LjE4NDAyWk0xMS40IDIyVjE4LjY0SDE0LjE4NFYyMkgxMS40WiIgZmlsbD0iIzU5NUU3NCIvPgo8L3N2Zz4K",t.initEditorExtensionsAsync=function(){if(!s&&(s=Promise.resolve(),e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.extendFieldEditors)){const t={};s=s.then((()=>e.BrowserUtils.loadBlocklyAsync())).then((()=>e.BrowserUtils.loadScriptAsync("fieldeditors.js"))).then((()=>e.editor.initFieldExtensionsAsync(t))).then((t=>{t.fieldEditors&&t.fieldEditors.forEach((t=>{e.blocks.registerFieldEditor(t.selector,t.editor,t.validator)}))}))}return s}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n={};function i(e,t,n,i){e.response&&window.parent.postMessage({type:e.type,id:e.id,resp:t,success:n,error:i},"*")}function r(t){return new Promise(((i,r)=>{const s=e.Util.clone(t);s.id=ts.pxtc.Util.guidGen(),t.response&&(n[s.id]={resolve:i,reject:r}),window.parent.postMessage(s,"*"),t.response||i(void 0)}))}t.bindEditorMessages=function(t){const r=(e.appTarget.appTheme.allowParentController||e.shell.isControllerMode())&&e.BrowserUtils.isIFrame(),s=e.appTarget.appTheme.allowPackageExtensions,o=e.appTarget.appTheme.allowSimulatorTelemetry;(r||s||o)&&window.addEventListener("message",(a=>{const l=a.data;if(!l||!/^pxt(host|editor|pkgext|sim)$/.test(l.type))return!1;if("pxtpkgext"===l.type&&s)t().then((e=>{e.handleExtensionRequest(l)}));else if("pxtsim"===l.type&&o){const t=l;"event"===t.action&&(t.category||t.message?e.reportError(t.category,t.message,t.data):e.tickEvent(t.tick,t.data))}else if(r){let r,s=Promise.resolve();if("pxthost"==l.type){const t=n[l.id];t?s=s.then((()=>t.resolve(l))):e.debug(`pxthost: unknown request ${l.id}`)}else"pxteditor"==l.type&&(s=s.then((()=>t().then((t=>{const n=l;switch(e.debug(`pxteditor: ${n.action}`),n.action.toLowerCase()){case"switchjavascript":return Promise.resolve().then((()=>t.openJavaScript()));case"switchpython":return Promise.resolve().then((()=>t.openPython()));case"switchblocks":return Promise.resolve().then((()=>t.openBlocks()));case"startsimulator":return Promise.resolve().then((()=>t.startSimulator()));case"restartsimulator":return Promise.resolve().then((()=>t.restartSimulator()));case"hidesimulator":return Promise.resolve().then((()=>t.collapseSimulator()));case"showsimulator":return Promise.resolve().then((()=>t.expandSimulator()));case"closeflyout":return Promise.resolve().then((()=>t.closeFlyout()));case"unloadproject":return Promise.resolve().then((()=>t.unloadProjectAsync()));case"saveproject":return t.saveProjectAsync();case"redo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasRedo()&&e.redo()}));case"undo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasUndo()&&e.undo()}));case"setscale":{const e=l;return Promise.resolve().then((()=>t.editor.setScale(e.scale)))}case"stopsimulator":{const e=l;return Promise.resolve().then((()=>t.stopSimulator(e.unload)))}case"newproject":{const e=l;return Promise.resolve().then((()=>t.newProject(e.options)))}case"importproject":{const e=l;return Promise.resolve().then((()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar})))}case"openheader":{const e=l;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const n=l;let i,r=n.path;return/^([jt]s|py|blocks?):/i.test(r)&&(i=/^py:/i.test(r)?e.PYTHON_PROJECT_NAME:/^[jt]s:/i.test(r)?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME,r=r.substr(r.indexOf(":")+1)),Promise.resolve().then((()=>t.startActivity({activity:n.activityType,path:r,title:n.title,editor:i,previousProjectHeaderId:n.previousProjectHeaderId,carryoverPreviousCode:n.carryoverPreviousCode})))}case"importtutorial":{const e=l;return Promise.resolve().then((()=>t.importTutorialAsync(e.markdown)))}case"proxytosim":{const e=l;return Promise.resolve().then((()=>t.proxySimulatorMessage(e.content)))}case"renderblocks":{const e=l;return Promise.resolve().then((()=>t.renderBlocksAsync(e))).then((e=>e.xml.then((e=>{r=e.xml}))))}case"renderpython":{const e=l;return Promise.resolve().then((()=>t.renderPythonAsync(e))).then((e=>{r=e.python}))}case"toggletrace":{const e=l;return Promise.resolve().then((()=>t.toggleTrace(e.intervalSpeed)))}case"settracestate":{const e=l;return Promise.resolve().then((()=>t.setTrace(e.enabled,e.intervalSpeed)))}case"setsimulatorfullscreen":{const e=l;return Promise.resolve().then((()=>t.setSimulatorFullScreen(e.enabled)))}case"togglehighcontrast":return Promise.resolve().then((()=>t.toggleHighContrast()));case"togglegreenscreen":return Promise.resolve().then((()=>t.toggleGreenScreen()));case"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync();case"info":return Promise.resolve().then((()=>{r={versions:e.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:e.appTarget.appTheme.availableLocales}}));case"shareproject":{const e=l;return t.anonymousPublishHeaderByIdAsync(e.headerId).then((e=>{r=e}))}case"savelocalprojectstocloud":{const e=l;return t.saveLocalProjectsToCloudAsync(e.headerIds).then((e=>{r={headerIdMap:e}}))}case"requestprojectcloudstatus":{const e=l;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=l;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=l;if("no-blocks"===e.restriction)throw console.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}}return Promise.resolve()})))));s.then((()=>i(l,r,!0,void 0)),(e=>i(l,r,!1,e)))}return!0}),!1)},t.enableControllerAnalytics=function(){if(!e.appTarget.appTheme.allowParentController||!e.BrowserUtils.isIFrame())return;const t=e.tickEvent;e.tickEvent=function(e,n){t&&t(e,n),r({type:"pxthost",action:"event",tick:e,response:!1,data:n})};const n=e.reportException;e.reportException=function(e,t){n&&n(e,t);try{r({type:"pxthost",action:"event",tick:"error",message:e.message,response:!1,data:t})}catch(e){}};const i=e.reportError;e.reportError=function(e,t,n){i&&i(e,t,n),r({type:"pxthost",action:"event",tick:"error",category:e,message:t,data:n})}},t.shouldPostHostMessages=function(){return e.appTarget.appTheme.allowParentController&&e.BrowserUtils.isIFrame()},t.postHostMessageAsync=r}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e){return`experiments-${"object"==typeof e?e.id:e}`}function i(){const t=e.savedAppTheme(),n={},i=r();return i.forEach((e=>{const i=s(e);t[e.id]=!!i,i&&(n[e.id]=i?1:0)})),i.length&&Object.keys(n).length&&(e.tickEvent("experiments.loaded",n),e.reloadAppTargetVariant()),e.appTarget.appTheme}function r(){const t=e.appTarget.appTheme.experiments;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"snippetBuilder",name:lf("Snippet Builder"),description:lf("Try out the new snippet dialogs.")},{id:"experimentalHw",name:lf("Experimental Hardware"),description:lf("Enable support for hardware marked 'experimental' in the hardware seletion dialog")},{id:"checkForHwVariantWebUSB",name:lf("Detect Hardware with WebUSB"),description:lf("When compiling, use WebUSB to detect hardware configuration.")},{id:"githubEditor",name:lf("GitHub editor"),description:lf("Review, commit and push to GitHub."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6419",enableOnline:!0},{id:"githubCompiledJs",name:lf("GitHub Pages JavaScript"),description:lf("Commit compiled javascript when creating a release"),enableOnline:!0},{id:"blocksCollapsing",name:lf("Collapse blocks"),description:lf("Collapse and expand functions or event blocks")},{id:"tutorialBlocksDiff",name:lf("Tutorial Block Diffs"),description:lf("Automatially render blocks diff in tutorials")},{id:"openProjectNewTab",name:lf("Open in New Tab"),description:lf("Open an editor in a new tab.")},{id:"openProjectNewDependentTab",name:lf("Open in New Connected Tab"),description:lf("Open connected editors in different browser tabs.")},{id:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")}].filter((n=>t.indexOf(n.id)>-1&&!(e.BrowserUtils.isPxtElectron()&&n.enableOnline))):[]}function s(t){return!!e.storage.getLocal(n(t))}function o(t,r){r!=s(t)&&(r?e.storage.setLocal(n(t),"1"):e.storage.removeLocal(n(t)),i())}t.syncTheme=i,t.all=r,t.clear=function(){r().forEach((t=>e.storage.removeLocal(n(t)))),i()},t.someEnabled=function(){return r().some((e=>s(e)))},t.isEnabled=s,t.toggle=function(e){o(e,!s(e))},t.state=function(){const e={};return r().forEach((t=>e[t.id]=s(t))),JSON.stringify(e)},t.setState=o}(t.experiments||(t.experiments={}))}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){function n(t){const n=e.appTarget.appTheme.invertedMonaco,i=!(!e.appTarget.appTheme.monacoFieldEditors||!e.appTarget.appTheme.monacoFieldEditors.length),r=e.BrowserUtils.isAndroid();let s=monaco.editor.create(t,{model:null,ariaLabel:e.Util.lf("JavaScript editor"),fontFamily:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:i,glyphMargin:i||e.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:n?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!r,comments:!r,strings:!r},acceptSuggestionOnCommitCharacter:!r,acceptSuggestionOnEnter:r?"off":"on",accessibilitySupport:r?"off":"on"});return s.layout(),s}t.syncModels=function(e,t,n,i){if(i)return;let r=monaco.languages.typescript.typescriptDefaults.getExtraLibs(),s={};e.sortedDeps().forEach((e=>{e.getFiles().forEach((i=>{let r=e.id+"/"+i;if(/\.(ts)$/.test(i)&&r!=n){if(!monaco.languages.typescript.typescriptDefaults.getExtraLibs()[r]){let n=e.readFile(i)||"\n";t[r]=monaco.languages.typescript.typescriptDefaults.addExtraLib(n,r)}s[r]="1"}}))})),Object.keys(r).filter((e=>/\.(ts)$/.test(e)&&!s[e])).forEach((e=>{t[e].dispose()}))},t.initMonacoAsync=function(t){return new Promise(((i,r)=>{if("object"==typeof window.monaco)return void i(n(t));let s=window.MonacoPaths,o=()=>{let r=window.require;r.config({paths:s}),r(["vs/editor/editor.main"],(()=>{monaco.languages.register({id:"asm",extensions:[".asm"]}),monaco.languages.setMonarchTokensProvider("asm",{tokenPostfix:"",keywords:["movs","mov","adds","add","adcs","adr","subs","sbcs","sub","rsbs","muls","cmp","cmn","ands","eors","orrs","bics","mvns","tst","lsls","lsrs","asrs","rors","ldr","ldrh","ldrb","ldrsh","ldrsb","ldm","str","strh","strb","stm","push","pop","cbz","cbnz","b","bl","bx","blx","sxth","sxtb","uxth","uxtb","rev","rev16","revsh","svc","cpsid","cpsie","setend","bkpt","nop","sev","wfe","wfi","yield","beq","bne","bcs","bhs","bcc","blo","bmi","bpl","bvs","bvc","bhi","bls","bge","blt","bgt","ble","bal","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc","sp","lr"],typeKeywords:[".startaddr",".hex",".short",".space",".section",".string",".byte"],operators:[],symbols:/[:\*]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/(\.)?[a-z_$\.][\w$]*/,{cases:{"@typeKeywords":"keyword","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/@\s*[a-zA-Z_\$][\w\$]*/,{token:"annotation"}],[/(#|(0[xX]))?[0-9a-fA-F]+/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/'[^\\']'/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],comment:[],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",next:"@pop"}]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/;.*$/,"comment"]]}}),monaco.languages.typescript&&(monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSyntaxValidation:!0,noSemanticValidation:!0}),monaco.languages.typescript.typescriptDefaults.setWorkerOptions({customWorkerPath:e.webConfig.typeScriptWorkerJs}),monaco.languages.typescript.typescriptDefaults.setCompilerOptions({allowUnreachableCode:!0,noImplicitAny:!0,allowJs:!1,allowUnusedLabels:!0,target:monaco.languages.typescript.ScriptTarget.ES5,outDir:"built",rootDir:".",noLib:!0,mouseWheelZoom:!1})),i(n(t))}))};if(window.require)o();else{let e=document.createElement("script");e.type="text/javascript",e.src=s["vs/loader"],e.addEventListener("load",o),document.body.appendChild(e)}}))},t.createEditor=n}(e.vs||(e.vs={}))}(pxt||(pxt={})),function(e){!function(t){t.freshHeader=function(t,n){return{target:e.appTarget.id,targetVersion:e.appTarget.versions.target,name:t,meta:{},editor:e.JAVASCRIPT_PROJECT_NAME,pubId:"",pubCurrent:!1,_rev:null,id:e.U.guidGen(),recentUse:n,modificationTime:n,cloudUserId:null,cloudCurrent:!1,cloudVersion:null,cloudLastSyncTime:0,isDeleted:!1}}}(e.workspace||(e.workspace={}))}(pxt||(pxt={})),function(e){!function(e){const t={};e.registerMonacoFieldEditor=function(e,n){t[e]=n},e.getMonacoFieldEditor=function(e){return t[e]}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){t.MonacoReactFieldEditor=class{getId(){return"image-editor"}showEditorAsync(t,n,i){return this.fileType=t,this.editrange=n,this.host=i,this.initAsync().then((()=>{const t=this.textToValue(i.getText(n));return t?(this.fv=e.react.getFieldEditorView(this.getFieldEditorId(),t,this.getOptions()),this.fv.onHide((()=>{this.onClosed()})),this.fv.show(),new Promise(((e,t)=>{this.resolver=e,this.rejecter=t}))):Promise.resolve(null)}))}onClosed(){this.resolver&&(this.resolver({range:this.editrange,replacement:this.resultToText(this.fv.getResult())}),this.editrange=void 0,this.resolver=void 0,this.rejecter=void 0)}dispose(){this.onClosed()}initAsync(){return Promise.resolve()}textToValue(e){return null}resultToText(e){return e+""}getFieldEditorId(){return""}getOptions(){return null}}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="image-editor";class i extends t.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`");const n=e.parseAssetTSReference(t);if(n){const{type:t,name:i}=n,r=i.trim(),s=e.react.getTilemapProject();this.isAsset=!0;const o=s.lookupAssetByName("image",r);if(o)return o;{const t=s.createNewImage();return r&&!s.isNameTaken("image",r)&&e.validateAssetName(r)&&(t.meta.displayName=r),t}}return{type:"image",id:"",internalID:0,bitmap:e.sprite.imageLiteralToBitmap(t).data(),meta:{},jresData:""}}resultToText(t){var n;if(null===(n=t.meta)||void 0===n?void 0:n.displayName){const n=e.react.getTilemapProject();return t=this.isAsset||n.lookupAsset(t.type,t.id)?n.updateAsset(t):n.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,e.getTSReferenceForAsset(t,this.isPython)}return e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript")}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}t.MonacoSpriteEditor=i,t.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:i},t.registerMonacoFieldEditor(n,t.spriteEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="tilemap-editor";class i extends t.MonacoReactFieldEditor{textToValue(t){const n=this.readTilemap(t),i=e.react.getTilemapProject();return e.sprite.addMissingTilemapTilesAndReferences(i,n),n}readTilemap(t){const n=e.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(e){return{type:"tilemap",id:"",internalID:0,meta:{},data:e}}(e.sprite.decodeTilemap(t,"typescript",n))}catch(e){}return null}this.isTilemapLiteral=!0;const i=/^\s*(tilemap(?:8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),r=(i[2]||i[3]||"").trim();let s,o;if(this.tilemapLiteral=i[1],r){let e=ts.pxtc.escapeIdentifier(r);s=n.getTilemap(e)}if(!s){let e=16;"tilemap8"===this.tilemapLiteral?e=8:"tilemap32"===this.tilemapLiteral&&(e=32);const[t]=n.createNewTilemap(o,e,16,16);s=n.getTilemap(t),o=t}return s}resultToText(t){const n=e.react.getTilemapProject();return n.pushUndo(),e.sprite.updateTilemapReferencesFromResult(n,t),this.isTilemapLiteral?(n.updateAsset(t),e.getTSReferenceForAsset(t,"python"===this.fileType)):e.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const e=this.editrange.getStartPosition();let t,n=this.editrange.getEndPosition(),i=1;for(;;){t=new monaco.Range(n.lineNumber,n.column,n.lineNumber+1,0);const r=this.host.getText(t);for(let t=0;t<r.length;t++)if("("===r.charAt(t))i++;else if(")"===r.charAt(t)&&(i--,0===i)){const i=new monaco.Position(n.lineNumber,n.column+t+2);return monaco.Range.fromPositions(e,i)}if(n=t.getEndPosition(),n.lineNumber>e.lineNumber+20)return null}}}t.MonacoTilemapEditor=i,t.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:i},t.registerMonacoFieldEditor(n,t.tilemapEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",i="orange";const r=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function s(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let i=[];const r=(e,t,i,r)=>{let s=[];for(let t=0;t<e.numberOfPins;t++){let r,o=e.pinDefinitions[t];if("string"==typeof o.target)r=o.target;else{let e=o.target.pinInstantiationIdx;if(!i||void 0===i[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=i[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,c=Math.round(l/e.visual.pinDistance),u=l-c*e.visual.pinDistance,d=n.xOffset+a.x,h=Math.round(d/e.visual.pinDistance),p={partRelativeRowIdx:c,partRelativeColIdx:h,xOffset:d-h*e.visual.pinDistance,yOffset:u};s.push({def:o,loc:a,target:r,bbFit:p})}return{name:t,def:e,pins:s,partParams:r||{},bbFit:n}},s=e.instantiations||[];return e.instantiation&&s.push(e.instantiation),s.forEach((n=>{if("singleton"===n.kind)i.push(r(e,t));else if("function"===n.kind){let s=n,a=s.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let c=Object.keys(l);if(!c||!c.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);c.forEach((n=>{const l=n.split(",");if(l.length!=s.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let c=[],u={};l.forEach(((e,t)=>{let n=s.argumentRoles[t];if(void 0!==n.partParameter&&(u[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,i=o(e);c[t]=i}})),i.push(r(e,t,c,u))}))}})),i.filter((e=>!!e))}computePartDimensions(t,n){let i=t.visual.pinLocations,r=t.pinDefinitions,o=t.numberOfPins;e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(r.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,c,u,d=i.map(((e,t)=>{return n={idx:t},i=e,o=r[t],s(s(n,i),o);var n,i,o})).filter((e=>"-Z"===e.orientation)),h=d.length>0,p=t.visual.pinDistance;if(h){let e=d[0],n=Math.ceil(e.x/p),i=Math.ceil(e.y/p);a=n*p-e.x,l=i*p-e.y,c=Math.ceil((a+t.visual.width)/p)+1,u=Math.ceil((l+t.visual.height)/p)+1}else c=Math.ceil(t.visual.width/p),u=Math.ceil(t.visual.height/p),a=c*p-t.visual.width,l=u*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:u,colCount:c}}allocColumns(t){let n=t.length;let i=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);i<=0&&console.log("Not enough breadboard space!");let r=Math.floor(i/(n-1+2)),s=i-r*(n-1),o=Math.floor(s/2),a=(Math.ceil(s/2),1+o);return t.map((e=>{let t=a;return a+=e.colCount+r,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let i=this.allocColumns(t.map((e=>e.bbFit))),r=t.map((e=>{let t=n-e.bbFit.rowCount,i=Math.floor(t/2);return i>4&&(i=4),i<1&&(i=1),i}));return t.map(((e,t)=>{let n=r[t];return s({startColumnIdx:i[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(r){let o=[],l=r.pins.map(((s,l)=>{let c,u,d=s.target,h=r.startColumnIdx+s.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(h),f=r.startRowIdx+s.bbFit.partRelativeRowIdx;if(f>=7&&(f-=2),a(s.def)){c={type:"breadboard",row:f<5?"j":"a",col:p,style:s.def.style}}else{c={type:"breadboard",row:e.visuals.getRowName(f),col:p,xOffset:s.bbFit.xOffset/r.def.visual.pinDistance,yOffset:s.bbFit.yOffset/r.def.visual.pinDistance,style:s.def.style}}return u="ground"===d?t:"threeVolt"===d?n:"fiveVolt"===d?i:"number"==typeof s.def.colorGroup?o[s.def.colorGroup]?o[s.def.colorGroup]:o[s.def.colorGroup]=this.nextColor():this.nextColor(),{start:c,end:d,color:u,pinIdx:l}}));return s(r,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let i=this.opts.getBBCoord(n.referenceBBPin),r=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));r[0]&&r[1]||console.debug(`No more available "${t}" locations!`);let s,o=0==e.visuals.findClosestCoordIdx(i,r);o?"ground"===t?s=this.availablePowerPins.top.ground:"threeVolt"===t?s=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(s=this.availablePowerPins.top.fiveVolt):"ground"===t?s=this.availablePowerPins.bottom.ground:"threeVolt"===t?s=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(s=this.availablePowerPins.bottom.fiveVolt);let a=s.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(i,a),c=s[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),c}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,i=this.opts.boardDef.gpioPinMap[n]||n;return i?{type:"dalboard",pin:i}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let r=this.getBoardGroundPin(),s=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},c={type:"breadboard",row:"-",col:"50"},u={type:"breadboard",row:"-",col:"25"};let d,h;this.opts.boardDef.attachPowerOnRight?(d=c,h=u):(d=a,h=l);let p=[],f=[],m=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:this.allocLocation("ground",{referenceBBPin:h}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:t}),e.bottomThreeVolt&&e.bottomGround?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:this.allocLocation("threeVolt",{referenceBBPin:h}),color:n}):e.bottomFiveVolt&&e.bottomGround&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:this.allocLocation("fiveVolt",{referenceBBPin:h}),color:i}),e.topThreeVolt?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:s},color:n}):e.bottomThreeVolt&&f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:s},color:i}),e.topFiveVolt&&!e.topThreeVolt?m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:i});let g=[];p.length>0&&g.push({wireIndices:p.map(((e,t)=>t))});let b=p.length;return f.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b))}),m.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b+f.length))}),{wires:p.concat(f).concat(m),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let i=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(i=i.map(((e,n)=>{if(e)return e;const r=i[1-n];return this.allocLocation(t[n],{referenceBBPin:r})})),i[0]&&i[1])return{start:i[0],end:i[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let i=t.startRowIdx+n.bbFit.partRelativeRowIdx;i>=7&&(i-=2);let r=e.visuals.getRowName(i),s=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:r,col:e.visuals.getColumnName(s)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,i)=>{let r=t[i],s=this.allocPartIRs(e.def,e.name,r);n=n.concat(s)}));const i=this.placeParts(n).map((e=>this.allocWireIRs(e))),s=i.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),i=t.map((e=>"threeVolt"===e)),s=t.map((e=>"fiveVolt"===e)),o=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=r(n),l=r(i),c=r(s),u=r(o);return{topGround:a&&!u,topThreeVolt:l&&!u,topFiveVolt:c&&!u,bottomGround:a&&u,bottomThreeVolt:l&&u,bottomFiveVolt:c&&u,singleGround:a,singleThreeVolt:l,singleFiveVolt:c}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(s);const o=this.allocPowerWires(this.powerUsage),a=i.map(((e,t)=>{const n=this.allocPart(e),i=e.wires.map((e=>this.allocWire(e)));if(i.some((e=>!e)))return;const r=[];e.wires.forEach(((e,t)=>{r[e.pinIdx]=t}));return{part:n,wires:i,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>r[e]))})))}})).filter((e=>!!e)),l=[o].concat(a).filter((e=>e.assembly&&e.assembly.length)),c=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:c}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,i,r){this.name=e,this.path=t,this.sourceReference=n,i&&(this.origin=i),r&&(this.adapterData=r)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,i=0,r=0){this.id=e,this.source=n,this.line=i,this.column=r,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,i,r){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof r&&(this.namedVariables=r),"number"==typeof i&&(this.indexedVariables=i)}};e.Breakpoint=class{constructor(e,t,n,i){this.verified=e;const r=this;"number"==typeof t&&(r.line=t),"number"==typeof n&&(r.column=n),i&&(r.source=i)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,i,r){const s={command:t};if(n&&Object.keys(n).length>0&&(s.arguments=n),this.send("request",s),r){this._pendingRequests[s.seq]=r;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[s.seq];n&&(delete this._pendingRequests[s.seq],n(new e.Response(s,"timeout")))}),i)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=i;class r extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,i){let s;"number"==typeof t?(s={id:t,format:n},i&&(s.variables=i),s.showUser=!0):s=t,e.success=!1,r.formatPII(s.format,!0,s.variables),e.body||(e.body={}),e.body.error=s,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,(function(e,i){return t&&i.length>0&&"_"!==i[0]?e:n[i]&&n.hasOwnProperty(i)?n[i]:e}))}}r._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,i=arguments[1],r=i>>0,s=r<0?Math.max(n+r,0):Math.min(r,n),o=arguments[2],a=void 0===o?n:o>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;s<l;)t[s]=e,s++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const i=arguments[1];let r=0;for(;r<n;){const n=t[r];if(e.call(i,n,r,t))return n;r++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const i=t(e),r=t(n);let s=0;for(;i[s]===r[s]&&(s++,s!==i.length&&s!==r.length););const o=i.slice(s),a=r.slice(s);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},i=e.runtime.currFrame;for(;null!=i;)n.breakpointIds.push(i.lastBrkId),i=i.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let i=e.RefObject.toDebugString(t),r=i.startsWith("[")?"array":i;return{id:t.id,preview:i,hasFields:null!==t.fields||i.startsWith("["),type:r}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(e,n,r,s){return function(e,r){const o={};for(let i of Object.keys(e))/^__/.test(i)||!/___\d+$/.test(i)||s&&-1===s.indexOf(i)||(o[i]=t(e[i],n));if(e.fields&&r)for(let s of r)s=s.substring(s.lastIndexOf(".")+1),o[s]=t(i(e.vtable.iface[s],e),n);if(e.fields)for(let i of Object.keys(e.fields).filter((e=>!e.startsWith("_"))))o[i]=t(e.fields[i],n);else Array.isArray(e.data)&&e.data.forEach(((e,i)=>{o[i]=t(e,n)}));return o}(e,r)}function i(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function r(e,i){let r=e.fn?e.fn.info:null;if(r){let s={thisParam:t(e.argL,i),params:[]};if(r.argumentNames){const n=r.argumentNames;s.params=n.map(((n,r)=>({name:n,value:t(e["arg"+r],i)})))}return{locals:n(e,i),funcInfo:r,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:s}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let i;if(n)for(const[e,r]of n)r.line<=t.line&&r.endLine>=t.line&&(i=[e,r]);return i?(i[1].verified=!0,i):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,i){const r=e.runtime.environmentGlobals;if(!Object.keys(r).length)return;const s=n.environmentGlobals={};Object.keys(r).forEach((n=>s[n]=t(e.runtime.environmentGlobals[n],i)))},e.getBreakpointMsg=function(t,i,s){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:i,globals:n(e.runtime.globals,o,void 0,s),stackframes:[]};for(;null!=t;){let e=r(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class s extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,i,r,s){this.breakpoints=r,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:i,boardDefinition:s})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const i=[];n.breakpoints.forEach((r=>{if(this.breakpoints){const[s,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),r);t.body.breakpoints.push(o),o.verified&&i.push(s)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(i),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:s.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",s.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",s.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(s.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(s.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}s.THREAD_ID=1,e.SimDebugSession=s;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const i=this.nextId();this._vars[i]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:i,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const i=t[n];let r,s=0;null===i?r="null":void 0===i?r="undefined":"object"==typeof i?(r="(object)",s=this.nextId(),this._vars[s]=this.getVariableValues(i)):r=i.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:r,variablesReference:s})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){function t(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}let n;function i(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function s(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}e.print=t,function(n){function r(n){n.origin;let r=n.data||{},s=r.type;if(s)switch(s){case"run":l(r);break;case"instructions":e.instructions.renderInstructions(r);break;case"stop":a();break;case"mute":c(r.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":t();break;case"recorder":!function(e){if(!o)return;switch(e.action){case"start":o.startRecording(e.width);break;case"stop":o.stopRecording()}}(r);break;case"screenshot":e.Runtime.postScreenshotAsync(r);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(r);break;case"pxteditor":break;case"debugger":o&&o.handleDebuggerMsg(r);break;case"simulator":let n=r;switch(n.command){case"focus":i("simulator.focus",{timestamp:n.timestamp});break;case"blur":i("simulator.blur",{timestamp:n.timestamp})}default:!function(e){if(!o||o.dead)return;o.board.receiveMessage(e)}(r)}}let o;function a(){o&&(o.kill(),o.board&&o.board.kill())}function l(t){a(),t.mute&&c(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);o=n,n.board.initAsync(t).then((()=>{n===o&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function c(t){e.AudioContextManager.mute(t)}n.start=function(){window.addEventListener("message",r,!1),n.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&s()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:n.frameid})},n.stop=a,n.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=i,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=s}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,i=.95,[r,s]=[816*i,1056*i],o=r-86.4,a=s-86.4,[l,c]=[1,1],u=24,d=o/c-48*c,h=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+u}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function p(t,n){let i=document.createElementNS("http://www.w3.org/2000/svg","svg"),r={l:0,t:0,w:0,h:0},s=document.createElementNS("http://www.w3.org/2000/svg","svg");i.appendChild(s),s.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};r.w=t.w,r.h=t.h;let a=e=>{r.h*=e,r.w*=e,o.width=r.w,o.height=r.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<r.w?a(n.cmpWidth/r.w):n.cmpHeight&&n.cmpHeight<r.h&&a(n.cmpHeight/r.h),e.svg.hydrate(s,o);let l=r.l,c=r.t,u=r.w,d=r.h,h=e=>{if(e<r.l){let t=r.l-e;r.l=e,r.w+=t}},p=e=>{let t=r.l+r.w;if(t<e){let n=e-t;r.w+=n}},f=e=>{if(e<r.t){let t=r.t-e;r.t=e,r.h+=t}},m=e=>{let t=r.t+r.h;if(t<e){let n=e-t;r.h+=n}},[g,b]=[-.3,.3];const y=[1.4,1];if(n&&n.top){let t=n.topSize,r=t/y[0],s=t/y[1],[o,a]=[l+u/2,c-3-s/2],d=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(d,"cmp-lbl"),i.appendChild(d);let m=r*n.top.length;f(a-s/2),h(o-m/2),p(o+m/2)}if(n&&n.bot){let t=n.botSize,r=t/y[0],s=t/y[1],[o,a]=[l+u/2,c+d+3+s/2],f=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(f,"cmp-lbl"),i.appendChild(f);let v=r*n.bot.length;m(a+s/2),h(o-v/2),p(o+v/2)}if(n&&n.right){let t=n.rightSize,r=t/y[1],s=t/y[0]*n.right.length,[o,a]=[l+u+5+s/2,c+d/2],h=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(h,"cmp-lbl"),i.appendChild(h),f(a-r/2),p(o+s/2),m(a+r/2)}if(n&&n.left){let t=n.leftSize,r=t/y[1],s=t/y[0]*n.left.length,[o,a]=[l-5-s/2,c+d/2],u=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(u,"cmp-lbl"),i.appendChild(u),f(a-r/2),h(o-s/2),m(a+r/2)}let v={viewBox:`${r.l} ${r.t} ${r.w} ${r.h}`,width:1.7*r.w,height:1.7*r.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(i,v);let w=document.createElement("div");return w.appendChild(i),w}function f(t,n){let i,r=e.runtime.board;if("wire"==t)i=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){i=(0,r.builtinPartVisuals[n.builtIn])([0,0])}else i=e.visuals.mkGenericPartSVG(n)}return p(i,n)}function m(t,n,i=!1){const r={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:i,partsList:[]};let s=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:r.boardDef.visual,boardDef:r.boardDef,wireframe:r.wireframe}),r),o=s.getView();return e.U.addClass(o,"board-svg"),s}function g(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function b(t){let i=g();var r;let s=p((r=t.boardDef,e.visuals.mkBoardView({visual:r.visual,boardDef:r}).getView()),{left:n(1),leftSize:30,cmpScale:.17});i.appendChild(s);let o=p(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return i.appendChild(o),t.allCmps.forEach((t=>{let r=1;"buttonpair"===t.visual.builtIn&&(r=2);let s=f(t.visual,{left:n(r),leftSize:30,cmpScale:.3});e.U.addClass(s,"partslist-cmp"),i.appendChild(s)})),t.allWireColors.forEach((r=>{let s=t.colorToWires[r].length,o=t.boardDef.pinStyles[r]||"female",a=f("wire",{left:n(s),leftSize:20,wireClr:r,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),i.appendChild(a)})),i}function y(t,n){let i=g(),r=m(n,465,!0);!function(t,n,i){let r=t.getView();n>0&&e.U.addClass(r,"grayed");for(let r=0;r<=n;r++){let s=i.stepToCmps[r];s&&s.forEach((i=>{let s=t.addPart(i);r===n&&(i.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(s.element,"notgrayed"))}));let o=i.stepToWires[r];o&&o.forEach((e=>{let i=t.addWire(e);i&&r===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(i))}))}}(r,t,n),i.appendChild(r.getView());let s=document.createElement("div");e.U.addClass(s,"panel-num-outer"),e.U.addClass(s,"noselect"),i.appendChild(s);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",s.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),i.appendChild(a);let l=n.stepToWires[t]||[],c=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let i=!1;"dalboard"==t.end.type&&(i="croc"==n.boardDef.pinStyles[t.end.pin]);let r=f("wire",{top:c(t.end),topSize:10,bot:c(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:i});e.U.addClass(r,"cmp-div"),a.appendChild(r)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,i)=>{let r;if(n){let{row:e,col:t}=n;r=`(${e},${t})`}else r="";let s=1.5;"buttonpair"===t.visual.builtIn&&(s*=.5);let o=f(t.visual,{top:r,topSize:10,cmpHeight:50,cmpScale:s});e.U.addClass(o,"cmp-div"),a.appendChild(o)}))})),i}function v(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const i={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(i),e.runtime.board=null,e.initCurrentRuntime(i);let r=document.createElement("style");r.textContent+=h,document.head.appendChild(r);const s=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),i=[],r=[],s=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,o)=>{e.part&&t&&(r[s+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(i[s+o]=e.wireIndices.map((e=>n[e])))})),s+=e.assembly.length}));let o=s-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),c={},u=[];return l.forEach((e=>{c[e.color]||(c[e.color]=[],u.push(e.color)),c[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:i,stepToCmps:r,allWires:l,allCmps:a,lastStep:o,colorToWires:c,allWireColors:u}}({boardDef:n.boardDef,partDefs:s,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=m(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=b(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=v,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",v(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,i,r,s,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class c{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=c;class u{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=u;class d extends c{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=d;class h extends c{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=h,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new h;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let i=e.getResume();i(t instanceof h?new u(t.func,t.fields,n):new u(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const i=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},r=e=>i(""+Math.round(e),6),s=(e,n)=>{i(Math.round(n)+"",8),t+=" /",r(e),t+=" =",r(n/e)};for(let i of e.split(/\n/)){if(!i)continue;if(!/^\d/.test(i))continue;const e=i.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),o=e[2],a=25,t+=o.length>=a?o:(o+" ").slice(0,a);const c=parseInt(e[0]),u=parseInt(e[1]);s(c,u),t+=" |",s(c-l.stops,u-l.us),t+=" ~";const d=parseInt(e[3]);r(d),l.meds.length>10&&l.meds.shift(),l.meds.push(d);const h=l.meds.slice();h.sort(((e,t)=>e-t));const p=h[h.length>>1];t+=" ~~",r(p),l.stops=c,l.us=u,t+="\n"}var o,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends c{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class f extends c{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=c.toAny(t.val)})),e}}function m(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=f,e.dumpLivePointers=m,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(i=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(r=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){m()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let i=e.getConfig(t);return null==i?n:i},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function i(e,t){if(t+="",e instanceof d){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function r(e,t,n){if(t+="",e instanceof d){return void(e.fields[t]=n)}let i=e.findIdx(t);i<0?e.data.push({key:t,val:n}):e.data[i].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,i){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=i,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new f},n.mapGet=function(e,t){return i(e,n.mapKeyNames[t])},n.mapSet=function(e,t,i){return r(e,n.mapKeyNames[t],i)},n.mapGetByString=i,n.mapDeleteByString=function(e,t){e instanceof f||n.panic(923);let i=e.findIdx(t);return i>=0&&e.data.splice(i,1),!0},n.mapSetGeneric=r,n.mapGetGeneric=i,n.mapSetByString=r,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof f)for(let e of t.data)n.push(e.key);return n}}(s=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new d;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=s.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){s.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let i=e.RefObject.toDebugString(this.data[n]);if(t.length+i.length>100){0==n&&(t+=i.substr(0,100)),t+="...";break}t+=i}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,i,r,s,o,a,l,c;e.RefCollection=t,function(n){function i(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function r(t,n,i){return e.pxtrt.nullCheck(t),t.indexOf(n,i)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=i,n.insertAt=function(t,n,i){e.pxtrt.nullCheck(t),t.insertAt(n,i)},n.setAt=function(t,n,i){e.pxtrt.nullCheck(t),t.setAt(n,i)},n.indexOf=r,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let s=r(t,n,0);return s>=0?(i(t,s),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const i=Math.pow(10,t++);n=Math.round(e*i+Number.EPSILON)/i}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(i=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(r=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return i.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(s=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(i.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,i){return e.pxtrt.nullCheck(t),t.slice(n,n+i)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,i)},t.lastIndexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,i)},t.includes=function(t,n,i){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,i)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class u extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return c.toHex(this)}}e.RefBuffer=u,function(t){let n;function i(t){let i=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),r=!1;i<0&&(r=!0,i=-i);let s=!1;return i>=10&&(s=!0,i/=10),{size:i,signed:r,swap:s,isFloat:t>=n.Float32LE}}function r(e){return new u(new Uint8Array(e))}function s(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function o(e,t){return s(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){s(e,t)&&(a(e),e.data[t]=n)}function c(e,t,n=0,i=-1){n<0||n>e.data.length||(i<0&&(i=e.data.length),i=Math.min(i,e.data.length-n),a(e),e.data.fill(t,n,n+i))}function d(e,t,n,i,r){if(n.buffer===e.buffer)d(e,t,n.slice(i,i+r),0,r);else for(let s=0;s<r;++s)e[t+s]=n[i+s]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let r=i(t);if(r.isFloat){let t=e.data.buffer.slice(n,n+r.size);if(r.swap){new Uint8Array(t).reverse()}return 4==r.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let s=0;for(let t=0;t<r.size;++t){s<<=8;let i=r.swap?n+t:n+r.size-t-1;s|=e.data[i]}if(r.signed){let e=32-8*r.size;s=s<<e>>e}else s>>>=0;return s},t.setNumber=function(e,t,n,r){let s=i(t);if(s.isFloat){let t=new Uint8Array(s.size);4==s.size?new Float32Array(t.buffer)[0]=r:new Float64Array(t.buffer)[0]=r,s.swap&&t.reverse();for(let i=0;i<s.size;++i)e.data[n+i]=t[i]}else for(let t=0;t<s.size;++t){let i=s.swap?n+s.size-t-1:n+t;e.data[i]=255&r,r>>=8}},t.createBuffer=r,t.createBufferFromHex=function(e){let t=r(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=c,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new u(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.data.length;++i)n+=t[e.data[i]>>4],n+=t[15&e.data[i]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const h=-2147483648;t.shift=function(e,t,n,i){i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h||0!=i&&0!=t&&t!=h&&(t<=-i||t>=i?c(e,0):(a(e),t<0?(t=-t,d(e.data,n+t,e.data,n,i-t),e.data.fill(0,n,n+t)):(i-=t,d(e.data,n,e.data,n+t,i),e.data.fill(0,n+i,n+i+t))))},t.rotate=function(e,t,n,i){if(i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h)return;a(e),t<0&&(t+=i<<8),(t%=i)<0&&(t+=i);let r=e.data,s=t,o=0,l=s,c=i;for(;o!=l;){let e=r[o+n];r[o+++n]=r[l+n],r[l+++n]=e,l==c?l=s:o==s&&(s=l)}},t.write=function(e,t,n,i=0,r=-1){r<0&&(r=n.data.length),i<0||t<0||t>e.data.length||(r=Math.min(n.data.length-i,e.data.length-t))<0||(a(e),d(e.data,t,n.data,i,r))}}(c=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,s){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(s);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",i=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;a=i}else a=":x"==s?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==s?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==s?a=1==o?"":"s":":q"==s?a=i(a):":jq"==s?a=r(a):":uri"==s?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==s?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==s&&(a=(100*o).toFixed(1).toString()+"%"),a}))}function i(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function r(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...i){let r=t[e]||e;return r=r.replace(/^\{(id|loc):[^\}]+\}/g,""),n(r,i)},e.fmt_va=n,e.htmlEscape=i,e.jsStringQuote=r}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,U,pxtcore;!function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let i;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return i||(i="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*i()};const r=Promise.resolve();async function s(e,t,n){let i=0;const r=[],s=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,r=t[e];s[e]=await n(r)}})();r.push(e)}try{await Promise.all(r)}catch(e){throw i=t.length,e}return s}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function c(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){r.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return s(1,e,t)},e.promisePoolAsync=s,e.promiseTimeout=async function(e,t,n){let i,r;const s=new Promise(((t,s)=>{r=t,i=setTimeout((()=>{r=void 0,clearTimeout(i),s(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,s]).then((e=>(r&&(clearTimeout(i),r()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let r=e.charCodeAt(i);if(r<=127)n+=e.charAt(i);else if(r<=2047)n+=String.fromCharCode(192|r>>6,128|63&r);else{if(!t&&55296<=r&&r<=56319){let t=e.charCodeAt(++i);isNaN(t)||(r=65536+(r-55296<<10)+(t-56320))}n+=r<=65535?String.fromCharCode(224|r>>12,128|r>>6&63,128|63&r):String.fromCharCode(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let r=t(e);i.hasOwnProperty(r)||(i[r]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}poke(){this.lock=!0;let e=this.events;return this.events=[],U.promiseMapAllSeries(e,(e=>U.promiseMapAllSeries(this.handlers,(t=>this.runtime.runFiberAsync(t,...this.valueToArgs?this.valueToArgs(e):[e]))))).then((()=>this.events.length>0?this.poke():(this.lock=!1,this._addRemoveLog.forEach((e=>{e.log===LogType.BackAdd?this.addHandler(e.act):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act)})),this._addRemoveLog=[],Promise.resolve())))}get handlers(){return this._handlers}setHandler(e){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet}):this._handlers=[e]}addHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackAdd});else{-1==this._handlers.indexOf(e)&&this._handlers.push(e)}}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove});else{let t=this._handlers.indexOf(e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let i=0;for(;e.hasOwnProperty("arg"+i);)i++;const r=e;for(let e=i;e>0;e--)r["arg"+e]=r["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,i){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=i}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let i=Date.now();return i-lastYield>=20&&(lastYield=i,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),5),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,i){let r={};__this.loopLock=r,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=i;const{msg:s,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(s,o),Runtime.postMessage(s),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==r),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,i){if(setupResume(t,n),"<main>"===i.functionName||"main.ts"===i.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let i;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(i=pxsim.dumpHeap(e,dbgHeap,n.fields))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:i})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:i}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,i),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let i=1;for(;e.hasOwnProperty("arg"+i);)n["arg"+(i-1)]=e["arg"+i],i++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let i=r=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>i(r)));pxsim.runtime=__this;let s=Date.now();if(s-n>3&&(lastYield=s),U.assert(e.pc==t),r instanceof pxsim.FnWrapper){let t=r,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},i={};return __this.loopLock=i,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===i),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=r,loop(e)};return i}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,i){return new Promise(((r,s)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(r),pxtcore.runAction(e,[t,n,i])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function i(t,n,r=null){if(!(n instanceof pxsim.RefObject))return;const s=n;if(s.gcIsStatic())return;const o=e[s.id];if(o)return void(r&&o.pointers.push([r,t]));const a={obj:s,path:null,pointers:[[r,t]]};e[s.id]=a,s.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&i(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))i(e.replace(/___\d+$/,""),this.globals[e]);const r=this.otherFrames.slice();this.currFrame&&r.indexOf(this.currFrame)<0&&r.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const r=n[t];r instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),i(e+"."+t,r))}if(n.caps)for(let t of n.caps)i(e+".cap",t)}}const s=Object.keys(e).map((t=>e[t]));s.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,i]of e.pointers){if(null==n)return void(e.path=i);o(n);const r=n.path+"."+i;(!t||t.length>r.length)&&(t=r)}e.path=t};s.forEach(o);const a=[t];for(const e of s){const i=e.obj.gcSize(),r=e.obj.gcKey();n.hasOwnProperty(r)||a.push(n[r]={count:0,size:0,name:r});const s=n[r];s.size+=i,s.count++,t.size+=i,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const c=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=c(4*e.size)+c(e.count)+" "+e.name+"\n";const u=e=>c(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,d=s.slice(0,20).map(u).join("\n");let h="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,i=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);h=s.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!i(e.obj))).map(u).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+d+"\n\nNew Objects:\n"+h}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;return(t?t.screenshotAsync().catch((e=>{console.debug("screenshot failed")})):Promise.resolve(void 0)).then((t=>Runtime.postMessage({type:"screenshot",data:t,delay:e&&e.delay})))}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{if(this.recordingLastImageData&&t&&this.recordingLastImageData.data.byteLength==t.data.byteLength){const e=this.recordingLastImageData.data,n=t.data,i=e.byteLength;let r=0;for(r=0;r<i&&e[r]==n[r];++r);if(r==i)return}this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e})}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let i=t.lastFewPtr++;i>=t.lastFew.length&&(i=0,t.lastFewPtr=1),t.lastFew[i]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),i=new TimeoutScheduled(-1,e,t,n);return i.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(i);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(i),i.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}}pxsim.Runtime=Runtime;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const i="pxtdriver";e.SimulatorDriver=class{constructor(n,i={}){this.container=n,this.options=i,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),i.parentOrigin&&this._allowedOrigins.push(i.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const r=null==i?void 0:i.messageSimulators;r&&Object.keys(r).map((e=>r[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:i,width:e})}stopRecording(){this.postMessage({type:"recorder",source:i,action:"stop"})}setFrameState(n){const i=n.nextElementSibling,r=i.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:i.style.display="",i.className="",r.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?i.style.display="none":(i.style.display="",i.className="videoplay xicon icon"),r.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),i.style.display="none",r.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const i=this.loanedIFrame();return i&&!t&&n.unshift(i),n}getSimUrl(){const e=this.options.simUrl||(window.pxtConfig||{}).simUrl||`${location.origin}/sim/simulator.html`;try{return new URL(e)}catch(t){return new URL(e,location.origin)}}postMessage(t,n,i){var r;if(this.hwdbg)return void this.hwdbg.postMessage(t);const s=this.dependentEditors();let o=this.simFrames();i&&(o=o.filter((e=>e.id===i)));const a=t;if(n&&(null==a?void 0:a.broadcast)){const i=!!(null===(r=this._currentRuntime)||void 0===r?void 0:r.single),a=window.parent&&window.parent!==window.window?window.parent:window.opener;if(this.options.nestedEditorSim&&a){if(n!==a){const e=this.options.parentOrigin||window.location.origin;a.postMessage(t,e)}}else if(s)s.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!i){const n="messagepacket"===t.type&&t.channel,i=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(i){let t=o.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const r=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&i.localHostUrl||i.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||""));let s=this.createFrame(r);this.container.appendChild(s),t=s.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(s,"simmsg"),e.U.addClass(s,"simmsg"+n),i.permanent&&(t.dataset.permanent="true"),this.startFrame(t),o=this.simFrames()}}else{const e=o.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),o=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<o.length;++e){const i=o[e];if((!n||i.contentWindow!=n)&&(i.contentWindow&&(this.postMessageCore(i,t),"recorder"==t.type&&"start"==t.action)))break}}postMessageCore(t,n){var i,r,s,o;if(t.contentWindow.postMessage(n,t.dataset.origin),e.U.isLocalHostDev()&&(null===(r=null===(i=pxt)||void 0===i?void 0:i.appTarget)||void 0===r?void 0:r.id))try{t.contentWindow.postMessage(n,`https://trg-${null===(o=null===(s=pxt)||void 0===s?void 0:s.appTarget)||void 0===o?void 0:o.id}.userpxt.io/---simulator`)}catch(e){}}createFrame(n){const i=document.createElement("div");i.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";const s=(n||this.getSimUrl())+"#"+r.id;r.src=s,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(s).origin||"*",i.appendChild(r);const o=document.createElement("i");o.className="videoplay xicon icon",o.style.display="none",o.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),i.appendChild(o);const a=document.createElement("div");return a.className="ui active loader",o.style.display="none",i.appendChild(a),this._runOptions&&this.applyAspectRatioToFrame(r),i}preload(e){this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.clearDebugger(),this.postMessage({type:"stop",source:i}),this.setState(n?t.Starting:t.Stopped),e&&this.unload()}suspend(){this.postMessage({type:"stop",source:i}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:i,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:i})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,i,r,s;let o=t;if(void 0===o){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(o=t)}if(void 0===o){const t=e.dataset.messagechannel;if(t){const e=null===(r=null===(i=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===i?void 0:i[t])||void 0===r?void 0:r.aspectRatio;e&&(o=e)}}void 0===o&&(o=(null===(s=this._runOptions)||void 0===s?void 0:s.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/o+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}run(e,t={}){this._runOptions=t,this.runId=this.nextId(),this._currentRuntime={type:"run",source:i,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies},this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){if(!this._currentRuntime||!e.contentWindow)return!1;const t=JSON.parse(JSON.stringify(this._currentRuntime));return t.frameCounter=++this.frameCounter,t.options={theme:this.themes[this.nextFrameId++%this.themes.length]},t.id=`${t.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=t.id,e.id!==this.debuggingFrame&&(t.traceDisabled=!0,t.breakOnStart=!1),this.postMessageCore(e,t),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleMessage(e,n){switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&(this.startFrame(n),this.options.revealElement&&this.options.revealElement(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,i=document.getElementById(n);if(i){const n=e;if(n.runtimeid==i.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,i=document.getElementById(n);i&&(i.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(i));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let r;switch(e){case n.Resume:r="resume",this.setState(t.Running);break;case n.StepInto:r="stepinto",this.setState(t.Running);break;case n.StepOut:r="stepout",this.setState(t.Running);break;case n.StepOver:r="stepover",this.setState(t.Running);break;case n.Pause:r="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:r,source:i})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const i=e;if(this.state==t.Running){if(i.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(i);let e=i.exceptionMessage+"\n";for(let t of i.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}i.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const i=e.req_seq;if(i){const{resolve:t}=this.debuggerResolvers[i];t&&(delete this.debuggerResolvers[i],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((i,r)=>{const s=this.debuggerSeq++;this.debuggerResolvers[s.toString()]={resolve:i,reject:r},this.postDebuggerMessage(e,t,s,n)}))}postDebuggerMessage(e,t={},n,r){const s=JSON.parse(JSON.stringify(t));s.type="debugger",s.subtype=e,s.source=i,n&&(s.seq=n),this.postMessage(s,void 0,r)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,i,r=!1){let s=(i?"back":"fore")+":"+t+":"+n;return!this.queues[s]&&r&&(this.queues[s]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[s]}listen(e,t,n){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let i=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?i.addHandler(n):i.setHandler(n),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let i=[this.start(0,0,n)];return 0==e&&0==t||(t&&i.push(this.start(0,t,n)),e&&i.push(this.start(e,0,n)),e&&t&&i.push(this.start(e,t,n))),i}queue(t,n,i=null){if(e.runtime.pausedOnBreakpoint)return;const r=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;r&&(t=this.notifyID);let s=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(s,(e=>e?e.push(i,r):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function i(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,i,r,s,o=0,a=!1;function l(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),n}function c(){T(0),o=0,s&&s.pause()}function u(){c(),x()}function d(e,t){e.gain.value&&e.gain.setTargetAtTime(0,l().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.mute=function(e){a=e,u();const t=l();!e&&t&&"suspended"===t.state&&t.resume()},t.stopAll=u,t.stop=function(){c(),function(){if(r){try{d(r,i)}catch(e){}r=void 0,i=void 0}}()},t.frequency=function(){return o};const h=[null,"triangle","sawtooth","sine"];let p,f,m=[],g=[];function b(e,t){let n,i=h[e];if(i){let e=l().createOscillator();return e.type=i,e.frequency.value=t,e}if(4==e)n=function(){if(!f){const e=131072;f=l().createBuffer(1,e,l().sampleRate);const t=f.getChannelData(0);let n=251771520;for(let i=0;i<e;i+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[i]=1,t[i+1]=1,t[i+2]=-1,t[i+3]=-1):(t[i]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0)}return f}();else if(5==e)n=function(){if(!p){const e=1e5;p=l().createBuffer(1,e,l().sampleRate);const t=p.getChannelData(0);let n=251771520;for(let i=0;i<e;i++)n^=n<<13,n^=n>>17,n^=n<<5,t[i]=(1023&n)/512-1}return p}();else if(11<=e&&e<=15)n=function(e){if(!g[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),i=n.getChannelData(0);for(let n=0;n<t;n++)i[n]=n<e/100*t?1:-1;g[e]=n}return g[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!m[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),i=n.getChannelData(0),r=[770763591,3356908179],s=[15,31,63];for(let n=0;n<t;n+=4){let t,o=n/4;o&=s[e-4],t=0!=(r[o>>5]&1<<(31&o)),t?(i[n]=1,i[n+1]=1,i[n+2]=-1,i[n+3]=-1):(i[n]=0,i[n+1]=0,i[n+2]=0,i[n+3]=0)}m[e]=n}return m[e]}(e-16+4)}let r=l().createBufferSource();r.buffer=n,r.loop=!0;return 4==e||16<=e&&e<=18?r.playbackRate.value=t/(l().sampleRate/4):5!=e&&(r.playbackRate.value=t/(l().sampleRate/1024)),r}const y=[];class v{mute(){this.gain?d(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=y.indexOf(this);e>=0&&y.splice(e,1),this.mute()}}let w=1;function x(){for(w++;y.length;)y[0].remove()}function k(t){const i=w;let r=l(),s=0,o=new v,c=-1,u=-1,d=0;y.length>5&&y[0].remove(),y.push(o);const h=(e,t)=>e/1024/4*(t?.5:1),p=()=>{o.mute(),d=0,c=-1,u=-1},f=()=>{if(s>=t.data.length||!t.data[s])return e.U.delay(d).then(p);const m=t.data[s],g=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+2),y=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+4),v=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+6),x=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+8),k=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+10),A=11<=m&&m<=15,T=4==m||16<=m&&m<=18,E=h(v,A),C=h(x,A);if(!r||i!=w)return e.U.delay(y);if(c!=m||u!=g||g!=k){if(o.generator)return e.U.delay(d).then((()=>(p(),f())));if(o.generator=a?null:b(m,g),!o.generator)return e.U.delay(y);if(c=m,u=g,o.gain=r.createGain(),o.gain.gain.value=0,o.gain.gain.setTargetAtTime(E,n.currentTime,.015),k!=g)if(null!=o.generator.frequency){o.generator.frequency.linearRampToValueAtTime(k,r.currentTime+(d+y)/1e3)}else if(null!=o.generator.playbackRate){const e=T?4:1024;o.generator.playbackRate.linearRampToValueAtTime(k/(l().sampleRate/e),r.currentTime+(d+y)/1e3)}o.generator.connect(o.gain),o.gain.connect(r.destination),o.generator.start()}s+=12,o.gain.gain.setValueAtTime(E,r.currentTime+d/1e3),d+=y;const S=0!==C&&y>50?(d-50)/1e3:(d-10)/1e3;return o.gain.gain.linearRampToValueAtTime(C,r.currentTime+S),f()};return f().then((()=>o.remove()))}function A(e,t){if(e<0)return;o=e;let n=l();if(n){t=Math.max(0,Math.min(1,t));try{i||(i=n.createOscillator(),r=n.createGain(),r.gain.value=0,i.type="triangle",i.connect(r),r.connect(n.destination),i.start(0)),T(t)}catch(e){return i=void 0,void(r=void 0)}i.frequency.value=e,T(t)}}function T(e){(null==r?void 0:r.gain)&&r.gain.setTargetAtTime(a?0:e,n.currentTime,.015)}t.muteAllChannels=x,t.queuePlayInstructions=function(t,n){const i=w;e.U.delay(t).then((()=>i!=w?Promise.resolve():k(n)))},t.playInstructionsAsync=k,t.tone=A,t.setCurrentToneGain=T,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const i="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n}(e.data));s=new Audio(i),a&&(s.volume=0),s.onended=()=>n(),s.onpause=()=>n(),s.onerror=()=>n(),s.play()})):Promise.resolve()};t.playPCMBufferStreamAsync=function(e,t,n=.3,i){return new Promise((r=>{let s=[],o=l().currentTime,c=!1;function u(){const t=i&&i();for(;!c&&s.length<3&&!t;){const t=e();if(!t||!t.length){c=!0;break}d(t)}c&&0===s.length&&(h.remove(),r&&r(),r=void 0)}function d(e){const n=l().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const i=l().createBufferSource();s.push(i),i.connect(h.gain),i.buffer=n,i.addEventListener("ended",(()=>{s.shift().disconnect(),u()})),i.start(o),o+=n.duration}const h=new v;h.gain=l().createGain(),h.gain.gain.value=0,a||h.gain.gain.setValueAtTime(n,l().currentTime),h.gain.connect(l().destination),y.length>5&&y[0].remove(),y.push(h),u()}))},t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,i=15&t[0],r=t[1]||0,s=(o=r,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?c():9==n&&(A(s,1),9==i&&setTimeout((()=>c()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=i,e.pointerEvents=i()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function i(e,t){let n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,i]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==i.x&&0==i.y,"el1 and el2 x,y offsets not supported");let r=(t,n,i)=>e.svg.hydrate(t,{x:n,y:i}),s=(t,n,i)=>e.svg.hydrate(t,{width:`${n}px`,height:`${i}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,c=n.h*a;s(n.el,l,c);let u=1*i.w,d=1*i.h;s(i.el,u,d);let[h,p,f,m]=t.margin,g=t.middleMargin,b=Math.max(l,u),y=p+(b-l)/2,v=h;r(n.el,y,v);let w=p+(b-u)/2,x=v+c+g;r(i.el,w,x);let k=[v,v+c,x,x+d],A=p+b+m,T=h+c+g+d+f,E=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${A} ${T}`,class:"sim-bb"});((t,n,i)=>{n&&e.svg.hydrate(t,{width:n}),i&&e.svg.hydrate(t,{height:i})})(E,t.maxWidth,t.maxHeight),r(E,0,0);let C=e.svg.child(E,"g");return E.appendChild(n.el),E.appendChild(i.el),{under:C,over:e.svg.child(E,"g"),host:E,edges:k,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+y,n*a+v]},toHostCoord2:e=>{let[t,n]=e;return[1*t+w,1*n+x]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let i=n(t.imageUnitDist,t.targetUnitDist),r=i(t.width),s=i(t.height),o=e.svg.elt("image",{width:r,height:s});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:r,h:s,x:0,y:0}},t.findDistSqrd=i,t.findClosestCoordIdx=function(e,t){return t.map((t=>i(e,t))).reduce(((e,t,n,i)=>t<i[e]?n:e),0)},t.mkTxt=function(t,n,i,r,s,o,a){let l=e.svg.elt("text");a=a||.3;const c=(o=o||-.33333)*i*s.length,u=a*i;return e.svg.hydrate(l,{style:`font-size:${i}px;`,transform:`translate(${t} ${n}) rotate(${r}) translate(${c} ${u})`}),e.U.addClass(l,"noselect"),l.textContent=s,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,i,[r,s,o]=e,[a,l,c]=[r/255,s/255,o/255],u=Math.min(a,l,c),d=Math.max(a,l,c),h=d-u,p=d+u;return i=p/2*100,0===h?n=t=0:(d===a?t=(l-c)/h%6*60:d===l?t=60*((c-a)/h+2):d===c&&(t=60*((a-l)/h+4)),n=i>50?h/(2-p)*100:h/p*100),[Math.floor(t),Math.floor(n),Math.floor(i)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function i(e,n,i){let r={class:e,d:n};i&&(r.title=i);let s=t.elt("path");return t.hydrate(s,r),s}function r(e,n=!1){let i=t.elt("linearGradient");t.hydrate(i,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(i,"stop",{offset:"0%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"});return i}function s(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,i){e.setAttribute("transform",`translate(${t},${n}) rotate(${i+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let i in n)"title"==i?t.title(e,n[i]):e.setAttributeNS(null,i,n[i])},n.elt=function(e,n){let i=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(i,n),i},n.child=function(e,n,i){let r=t.elt(n,i);return e.appendChild(r),r},n.mkPath=i,n.path=function(e,t,n,r){let s=i(t,n,r);return e.appendChild(s),s},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let i=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(i=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!i||(i=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,i,r,s){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,i&&i(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!o||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{o=!1,r&&r(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{o=!1,r&&r(e)}),!1),t.addEventListener("keydown",(e=>{o=!1,s&&s(e)}))},n.mkLinearGradient=r,n.linearGradient=function(e,t,n=!1){let i=r(t,n);return e.appendChild(i),i},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let i=t.parentElement;i&&(i.removeChild(t),i.appendChild(t))},n.mkTitle=s,n.title=function(e,t){let n=s(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,i){this.parts=[],this.boardView=n,this.opts=i,i.boardDef.pinStyles||(i.boardDef.pinStyles={}),this.state=i.state;let r=i.partsList,s=0<r.length||i.forceBreadboardLayout;if(s){this.breadboard=new t.Breadboard({wireframe:i.wireframe});const n=i.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:i.maxWidth,maxHeight:i.maxHeight}),a=o.under,l=o.over;this.view=o.host;const c=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,c,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const u=e.allocateDefinitions({boardDef:i.boardDef,partDefs:i.partDefs,fnArgs:i.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:r});u.partsAndWires.length||i.forceBreadboardLayout?(this.addAll(u),u.requiresBreadboard||i.forceBreadboardRender?u.hideBreadboard&&this.breadboard&&this.breadboard.hide():s=!1):s=!1}if(!s){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),i.maxWidth&&e.svg.hydrate(this.view,{width:i.maxWidth}),i.maxHeight&&e.svg.hydrate(this.view,{height:i.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.cloneNode(!0);t.setAttribute("width",this.view.width.baseVal.value+""),t.setAttribute("height",this.view.height.baseVal.value+"");const n=(new XMLSerializer).serializeToString(t),i="data:image/svg+xml,"+encodeURIComponent(n.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const r=document.createElement("img");r.onload=()=>{const n=document.createElement("canvas");n.width=r.width,n.height=r.height,e>0?(n.width=e,n.height=r.height*e/r.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const i=n.getContext("2d");i.drawImage(r,0,0,n.width,n.height),t(i.getImageData(0,0,n.width,n.height))},r.onerror=e=>{console.log(e),t(void 0)},r.src=i}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let i=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],r=this.state.builtinParts[e];i=t(),i.init(this.state.bus,r,this.view,n.params)}else{let e=n.visual;i=new t.GenericPart(e)}this.parts.push(i),this.partGroup.appendChild(i.element),i.overElement&&this.partOverGroup.appendChild(i.overElement),i.defs&&i.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=i.style||"";let r=n.startColumnIdx,s=n.startRowIdx,o={type:"breadboard",row:t.getRowName(s),col:t.getColumnName(r),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);i.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(i.element,l),e.U.addClass(i.element,"sim-cmp"),i.updateTheme(),i.updateState(),i}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,i=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));i&&n.forEach((t=>e.wires.push(this.addWire(t))));let r=t.part;!r||n&&!i||e.parts.push(this.addPart(r))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,i="#DD4BA0",r=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${i};\n stroke:${i};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${i};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const s=[4,4],o=t.BREADBOARD_MID_ROWS+s.length,a=25,l=[4,9,14,19],c=a+l.length,u=n*(t.BREADBOARD_MID_COLS+3),d=n*(o+4+5.5),h=2/3,p=d*h,f=.16666666666666669*d,m=(t.BREADBOARD_MID_COLS-1)*n,g=(u-m)/2,b=f+(p-(o-1)*n)/2,y=(c-1)*n,v=(u-y)/2,w=(f-15)/2,x=v,k=w+f+p,A=25.5,T=12,E=1.05,C=-90,S="abcdefghij".split("").reverse();function I(e){return`${e+1}`}function P(e){return S[e]}function U(t){let n=t.xOffset||0,i=t.yOffset||0,r=[],s=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],c=(e,t)=>{let n,i=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),i+=1;return i},u=0,d=l(t.rowIdxsWithGap);for(let h=0;h<t.rowCount;h++){let p=0,f=l(t.colIdxsWithGap),m=i+h*t.pinDist+u*t.pinDist,g=h+a;for(let i=0;i<t.colCount;i++){let a=n+i*t.pinDist+p*t.pinDist,l=i+o;const u=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:m}:{x:a-.5*t.w,y:m-.5*t.h}),s.appendChild(t.el),t.el);let d=u(t.mkPin()),h=u(t.mkHoverPin()),b=t.getRowName(g),y=t.getColName(l),v=t.getGroupName?t.getGroupName(g,l):null,w={el:d,hoverEl:h,cx:a,cy:m,row:b,col:y,group:v};r.push(w),p+=c(f,l)}u+=c(d,g)}return{g:s,allPins:r}}function _(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function N(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function O(n,i,r,s,o,a,l){let c=t.mkTxt(n,i,r,s,o);e.U.addClass(c,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(c,t)));let u=t.mkTxt(n,i,1.3*r,s,o);return e.U.addClass(u,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(u,t))),{el:c,hoverEl:u,txt:o,group:a}}t.getColumnName=I,t.getRowName=P,t.mkGrid=U;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let i=n[t];return i||null}getCoord(e){let{row:t,col:i,xOffset:r,yOffset:s}=e,o=this.getPin(t,i);if(!o)return null;let a=(r||0)*n,l=(s||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${u} ${d}`,class:"sim-bb",width:u+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=r,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:u,height:d,rx:4.5,ry:4.5});let i="sim-bb-channel-grad",o=e.svg.elt("linearGradient");e.svg.hydrate(o,{id:i,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(o);e.svg.child(o,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(o,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"100%",style:"stop-color: #AAA;"});const c=(t,n,r)=>{let s=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${r||""}`,y:t-n/2,width:u,height:n});return s.setAttribute("fill",`url(#${i})`),s};c(f+p/2,15,"sim-bb-mid-channel"),c(f,.75,"sim-bb-sml-channel"),c(f+p,.75,"sim-bb-sml-channel");const h=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${I(n)}`,m=e=>0===e?"-":"+",S=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${m(e)}${n}`};let D=U({xOffset:g,yOffset:b,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:_,mkHoverPin:N,getRowName:P,getColName:I,getGroupName:h,rowIdxsWithGap:s});D.g;this.allPins=this.allPins.concat(D.allPins);let R=U({xOffset:x,yOffset:k,rowCount:2,colCount:a,pinDist:n,mkPin:_,mkHoverPin:N,getRowName:m,getColName:I,getGroupName:S,colIdxsWithGap:l});R.g;this.allPins=this.allPins.concat(R.allPins);let M=U({xOffset:v,yOffset:w,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:_,mkHoverPin:N,getRowName:m,getColName:I,getGroupName:S,colIdxsWithGap:l.map((e=>e+a))});M.g;this.allPins=this.allPins.concat(M.allPins),this.allPins.forEach((t=>{let{el:n,row:i,col:r,hoverEl:s}=t,o=`(${i},${r})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(s,{title:o})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const L=(e,t,n,i,r,s)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return O(a+n,l+i,10.5,-90,r,s)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=I(e),i=0,r=L(P(i),n,0,-15,n,h(i,e));this.allLabels.push(r);let s=t.BREADBOARD_MID_ROWS-1,o=L(P(s),n,0,15,n,h(s,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=P(e),i=L(n,I(0),-15,0,n);this.allLabels.push(i);let r=L(n,I(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(r)}let B=[O(13.05,f+p+T,30,C,"-",S(0,0),["sim-bb-blue"]),O(12,f+p+f-T,A,C,"+",S(1,0),["sim-bb-red"]),O(u-T+E,f+p+T,30,C,"-",S(0,24),["sim-bb-blue"]),O(u-T,f+p+f-T,A,C,"+",S(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(B);let F=[O(13.05,12,30,C,"-",S(0,a),["sim-bb-blue"]),O(12,f-T,A,C,"+",S(1,a),["sim-bb-red"]),O(u-T+E,12,30,C,"-",S(0,49),["sim-bb-blue"]),O(u-T,f-T,A,C,"+",S(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(F);let $={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;($[n]=$[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:i}=e,r=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),s=r[n]||(r[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?B.filter((t=>t.group==e.group)).forEach((e=>s.push(e))):F.filter((t=>t.group==e.group)).forEach((e=>s.push(e)))}else{$[t].forEach((e=>s.push(e))),$[n].forEach((e=>s.push(e)))}}));const j=y+22.5,H=(j-y)/2,V=(t,n,i,r)=>{let s=e.svg.elt("rect");return e.svg.hydrate(s,{class:`sim-bb-bar ${r}`,x:t,y:n-1.5,width:j,height:3}),{el:s,group:i}};let G=[V(x-H,k-9,S(0,49),"sim-bb-blue"),V(x-H,k+n+9,S(1,49),"sim-bb-red"),V(v-H,w-9,S(0,0),"sim-bb-blue"),V(v-H,w+n+9,S(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(G),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let z=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),W=z.map((t=>e.svg.elt("g")));W.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),W.forEach(((t,n)=>e.U.addClass(t,`group-${z[n]}`)));let q={};z.forEach(((e,t)=>q[e]=W[t]));let J={};this.allPins.forEach(((e,t)=>{let n=e.group;(J[n]||(J[n]=[])).push(e)})),z.forEach((t=>{let n=J[t],[i,r]=[n.map((e=>e.cx)),n.map((e=>e.cy))],s=e=>e.reduce(((e,t)=>e<t?e:t)),o=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,c,u]=[s(i),o(i),s(r),o(r)],d=e.svg.elt("rect"),h=Math.max(l-a,1e-4),p=Math.max(u-c,1e-4);e.svg.hydrate(d,{x:a,y:c,width:h,height:p}),e.U.addClass(d,"sim-bb-group-wire"),q[t].appendChild(d)})),this.allPins.forEach((e=>{let t=q[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let Y=e.svg.elt("g");e.svg.hydrate(Y,{class:"sim-bb-group-misc"}),W.push(Y),this.allLabels.forEach((e=>{if(e.group){let t=q[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Y.appendChild(e.el),Y.appendChild(e.hoverEl)})),W.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:u,h:d}}highlightLoc(t){let{row:n,col:i}=t,r=this.rowColToPin[n][i],{cx:s,cy:o}=r;this.rowColToLbls[n][i].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,i=1.5*n,r=.66666*t.PIN_DIST,s=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,c=a.wireframe&&l.outlineImage?l.outlineImage:l.image,u=t.mkImageSVG({image:c,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),d=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=u.w,this.height=u.h;let h=u.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(h),this.background=h,e.svg.hydrate(h,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("circle"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map(((n,i)=>{let r=d(n.x)+t.PIN_DIST/2,s=d(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:r,yOffset:s,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:m,mkHoverPin:l.useCrocClips?f:g,getRowName:()=>`${i+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),y=[];b.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),y.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const v=(e,n,i,r,s)=>{let o,a;if("below"===s){a=e,o=n+12+.25*i*r.length}else{a=e,o=n-11-.32*i*r.length}return t.mkTxt(a,o,i,-90,r)};this.allLabels=this.allPins.map(((t,r)=>{let s=y[r];return((t,r,s,o)=>{let a=v(t,r,n,s,o);e.U.addClass(a,"sim-board-pin-lbl");let l=v(t,r,i,s,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:s}})(t.cx,t.cy,t.col,s.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,i,r){let s=e.svg.elt("rect");return e.svg.hydrate(s,{x:t,y:n,width:i,height:r,class:"gray-cover"}),s}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),i=this.findPin(t);n&&i&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(i.el,"highlight"),e.U.addClass(i.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let i=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(i)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,i=.7;function r(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let s;function o(t,n,i,r){const s=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,c]=n,u=c-a,d=[o,a+u*i],h=[l,c-u*i],p=e.svg.mkPath("sim-bb-wire",`M${s(t)} C${s(d)} ${s(h)} ${s(n)}`);return e.U.addClass(p,`wire-stroke-${r}`),p}function a(t,n,i){const r=e=>`${e[0]}, ${e[1]}`;let s=e.svg.mkPath("sim-bb-wire",`M${r(t)} L${r(n)}`);return e.U.addClass(s,`wire-stroke-${i}`),s}function l(i,r){const s=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=i[0],l=i[1],c=n/2+s/2;return e.svg.hydrate(o,{cx:a,cy:l,r:c,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${r}`),o.style["stroke-width"]=`${s}px`,o}function c(n,i,r){let s=.24*t.PIN_DIST,o=10*s,a=2*s,l=6*s,c=s;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),x=l,k=c,A=d-k/2,T=h+p*(g/2+x/2)-x/2;return e.svg.hydrate(w,{x:A,y:T,width:k,height:x,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,T),w:b+2*u,h:g+x}}function u(n,i,r){let s=.24*t.PIN_DIST;const o=4*s,a=10*s,l=3.5*s,c=3.5*s,u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("polygon"),g=a,b=o,y=d-b/2,v=h-g/2;const w=i?.15:.3,x=i?.7:1-.7,k=i?.3:.15;e.svg.hydrate(m,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([y+b*w,v],[y+b*(1-w),v],[y+b,v+g*x],[y+b*(1-k),v+g],[y+b*k,v+g],[y,v+g*x])}),e.svg.hydrate(m,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let A=e.svg.elt("rect"),T=l,E=c,C=d-E/2,S=h+p*(g/2+T/2)-T/2;return e.svg.hydrate(A,{x:C,y:S,width:E,height:T,class:"sim-bb-wire-bare-end"}),f.appendChild(A),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,S),w:b+2*u,h:g+T}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(s=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,i,r=!1){let s,o=e.svg.elt("g"),[a,l]=n,d=[a-15,l-50],h=[a+15,l+50];i=t.mapWireColor(i),s=r?u(d,!0,i):c(d,!0,i);let p=function(t,n,i){const r=e=>`${e[0]}, ${e[1]}`;let[s,o]=t,[a,l]=n,c=l-o,u=[s,o+.8*c],d=[a,l-.8*c],h=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(u)} ${r(d)} ${r(n)}`);return h.style.stroke=i,{el:h,x:Math.min(s,a),y:Math.min(o,l),w:Math.abs(s-a),h:Math.abs(o-l)}}(d,h,i),f=c(h,!1,i);o.appendChild(p.el),o.appendChild(s.el),o.appendChild(f.el);let m=Math.min(s.x,f.x),g=Math.max(s.x+s.w,f.x+f.w),b=Math.min(s.y,f.y);return{el:o,x:m,y:b,w:g-m,h:Math.max(s.y+s.h,f.y+f.h)-b}};t.WireFactory=class{constructor(e,n,i,r,s,o){this.nextWireId=0,this.styleEl=r,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=i,this.getLocCoord=s,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]<n&&(n=e[i],t=i);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,s,c){let u=[],d=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const h=e=>{const n=t.PIN_DIST/2;let i,r=this.closestEdge(e);return i=r-e[1]<0?r-n:r+n,[e[0],i]};let p=this.nextWireId++,f=r(c),m=l(n,f),g=l(s,f),b=e.svg.child(d,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(m),b.appendChild(g);let y=this.closestEdgeIdx(n),v=this.closestEdgeIdx(s);if(y==v){let e=a(n,s,f);d.appendChild(e),u.push(e)}else{let t,r,l=h(n),c=h(s),m=a(n,l,f),g=a(s,c,f);!(1!=y&&2!=y||1!=v&&2!=v)?(t=o(l,c,i,f),r=o(l,c,i,f)):(t=a(l,c,f),r=a(l,c,f)),e.U.addClass(r,"sim-bb-wire-hover"),d.appendChild(m),u.push(m),d.appendChild(g),u.push(g),this.underboard.appendChild(t),u.push(t),d.appendChild(r),u.push(r);let w=`sim-bb-wire-id-${p}`;const x=t=>e.U.addClass(t,w);x(b),x(r),this.styleEl.textContent+=`\n .${w}:hover ~ .${w}.sim-bb-wire-hover {\n visibility: visible;\n }`}let w=`\n .wire-stroke-${f} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${f} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=w,{endG:b,end1:m,end2:g,wires:u}}drawWireWithCrocs(n,s,c,d=!1){let h=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const f=e=>{const n=t.PIN_DIST/2;let i,r=this.closestEdge(e);return i=r-e[1]<0?r-n:r+n,[e[0],i]};let m=this.nextWireId++,g=r(c),b=l(n,g),y=s,[v,w]=s;s=[v,w+40],[v,w]=s;let x,k=[v,w+-17];x=d?function(n,i,r){let s=.24*t.PIN_DIST,o=4*s,a=1.2*s,l=10*s,c=s;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h+10-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),x=l,k=c,A=d-k/2,T=h+10+p*(g/2+x/2)-x/2;return e.svg.hydrate(w,{x:A,y:T,width:k,height:x,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,T),w:b+2*u,h:g+x}}(k,!0):u(k,!0);let A=x.el,T=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});T.appendChild(b);let E=this.closestEdgeIdx(n),C=this.closestEdgeIdx(y);if(E==C){let e=a(n,s,g);p.appendChild(e),h.push(e)}else{let t,r,l=f(n),c=a(n,l,g);!(1!=E&&2!=E||1!=C&&2!=C)?(t=o(l,s,i,g),r=o(l,s,i,g)):(t=a(l,s,g),r=a(l,s,g)),e.U.addClass(r,"sim-bb-wire-hover"),p.appendChild(c),h.push(c),this.underboard.appendChild(t),h.push(t);let u=`sim-bb-wire-id-${m}`;const d=t=>e.U.addClass(t,u);d(T),d(r),this.styleEl.textContent+=`\n .${u}:hover ~ .${u}.sim-bb-wire-hover {\n visibility: visible;\n }`}T.appendChild(A);let S=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=S,{endG:T,end1:b,end2:A,wires:h}}checkWire(e,t){let n=this.getLocCoord(e),i=this.getLocCoord(t);return!!n&&!!i}addWire(e,t,n){let i=this.getLocCoord(e),r=this.getLocCoord(t);if(!i||!r)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let s,o=this.getPinStyle(t);return s="dalboard"==t.type&&"croc"==o?this.drawWireWithCrocs(i,r,n):this.drawWire(i,r,n),s}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));
|
|
1
|
+
var e=function(){"use strict";function t(e,t){postMessage({action:$e,cbn:t,result:e})}function n(e){var t=[];return t[e-1]=void 0,t}function i(e,t){return o(e[0]+t[0],e[1]+t[1])}function r(e,t){return function(e,t){var n;return n=t,0>t&&(n+=He),[n,e*He]}(~~Math.max(Math.min(e[1]/He,2147483647),-2147483648)&~~Math.max(Math.min(t[1]/He,2147483647),-2147483648),c(e)&c(t))}function s(e,t){var n,i;return e[0]==t[0]&&e[1]==t[1]?0:(n=0>e[1],i=0>t[1],n&&!i?-1:!n&&i?1:p(e,t)[1]<0?-1:1)}function o(e,t){var n,i;for(e%=0x10000000000000000,t=(t%=0x10000000000000000)-(n=t%He)+(i=Math.floor(e/He)*He),e=e-i+n;0>e;)e+=He,t-=He;for(;e>4294967295;)e-=He,t+=He;for(t%=0x10000000000000000;t>0x7fffffff00000000;)t-=0x10000000000000000;for(;-0x8000000000000000>t;)t+=0x10000000000000000;return[e,t]}function a(e,t){return e[0]==t[0]&&e[1]==t[1]}function l(e){return e>=0?[e,0]:[e+He,-He]}function c(e){return e[0]>=2147483648?~~Math.max(Math.min(e[0]-He,2147483647),-2147483648):~~Math.max(Math.min(e[0],2147483647),-2147483648)}function u(e){return 30>=e?1<<e:u(30)*u(e-30)}function d(e,t){var n,i,r,s;if(t&=63,a(e,Ge))return t?ze:e;if(0>e[1])throw Error("Neg");return s=u(t),i=e[1]*s%0x10000000000000000,(i+=n=(r=e[0]*s)-r%He)>=0x8000000000000000&&(i-=0x10000000000000000),[r-=n,i]}function h(e,t){var n;return n=u(t&=63),o(Math.floor(e[0]/n),e[1]/n)}function p(e,t){return o(e[0]-t[0],e[1]-t[1])}function f(e,t){return e.Mc=t,e.Lc=0,e.Yb=t.length,e}function m(e){return e.Lc>=e.Yb?-1:255&e.Mc[e.Lc++]}function g(e,t,n,i){return e.Lc>=e.Yb?-1:(i=Math.min(i,e.Yb-e.Lc),x(e.Mc,e.Lc,t,n,i),e.Lc+=i,i)}function b(e){return e.Mc=n(32),e.Yb=0,e}function y(e){var t=e.Mc;return t.length=e.Yb,t}function v(e,t){e.Mc[e.Yb++]=t<<24>>24}function w(e,t,n,i){x(t,n,e.Mc,e.Yb,i),e.Yb+=i}function x(e,t,n,i,r){for(var s=0;r>s;++s)n[i+s]=e[t+s]}function k(t,n,i,r,o){var a,l;if(s(r,Ve)<0)throw Error("invalid length "+r);for(t.Tb=r,function(e,t){(function(e,t){e.ab=t;for(var n=0;t>1<<n;++n);e.$b=2*n})(t,1<<e.s),t.n=e.f,function(e,t){var n=e.X;e.X=t,e.b&&n!=e.X&&(e.wb=-1,e.b=null)}(t,e.m),t.eb=0,t.fb=3,t.Y=2,t.y=3}(o,a=Y({})),a.Gc=void 0===e.disableEndMark,function(e,t){e.fc[0]=9*(5*e.Y+e.eb)+e.fb<<24>>24;for(var n=0;4>n;++n)e.fc[1+n]=e.ab>>8*n<<24>>24;w(t,e.fc,0,5)}(a,i),l=0;64>l;l+=8)v(i,255&c(h(r,l)));t.yb=(a.W=0,a.oc=n,a.pc=0,function(e){var t,n;e.b||(t={},n=4,e.X||(n=2),function(e,t){e.qb=t>2,e.qb?(e.w=0,e.xb=4,e.R=66560):(e.w=2,e.xb=3,e.R=0)}(t,n),e.b=t),he(e.A,e.eb,e.fb),(e.ab!=e.wb||e.Hb!=e.n)&&(_(e.b,e.ab,4096,e.n,274),e.wb=e.ab,e.Hb=e.n)}(a),a.d.Ab=i,function(e){(function(e){e.l=0,e.J=0;for(var t=0;4>t;++t)e.v[t]=0})(e),function(e){e.mc=ze,e.xc=ze,e.E=-1,e.Jb=1,e.Oc=0}(e.d),Pe(e.C),Pe(e._),Pe(e.bb),Pe(e.hb),Pe(e.Ub),Pe(e.vc),Pe(e.Sb),function(e){var t,n=1<<e.u+e.I;for(t=0;n>t;++t)Pe(e.V[t].tb)}(e.A);for(var t=0;4>t;++t)Pe(e.K[t].G);oe(e.$,1<<e.Y),oe(e.i,1<<e.Y),Pe(e.S.G),e.N=0,e.jb=0,e.q=0,e.s=0}(a),X(a),K(a),a.$.rb=a.n+1-2,de(a.$,1<<a.Y),a.i.rb=a.n+1-2,de(a.i,1<<a.Y),a.g=ze,function(e,t){return e.cb=t,e.Z=null,e.zc=1,e}({},a))}function A(e,t,n){return e.Nb=b({}),k(e,f({},t),e.Nb,l(t.length),n),e}function T(e,t,n){var i,r,s,o,a="",c=[];for(r=0;5>r;++r){if(-1==(s=m(t)))throw Error("truncated input");c[r]=s<<24>>24}if(!function(e,t){var n,i,r,s,o,a,l;if(5>t.length)return 0;for(l=255&t[0],r=l%9,s=(a=~~(l/9))%5,o=~~(a/5),n=0,i=0;4>i;++i)n+=(255&t[1+i])<<8*i;return n>99999999||!function(e,t,n,i){if(t>8||n>4||i>4)return 0;W(e.gb,n,t);var r=1<<i;return H(e.Rb,r),H(e.sb,r),e.Dc=r-1,1}(e,r,s,o)?0:function(e,t){return 0>t?0:(e.Ob!=t&&(e.Ob=t,e.nb=Math.max(e.Ob,1),D(e.B,Math.max(e.nb,4096))),1)}(e,n)}(i=j({}),c))throw Error("corrupted input");for(r=0;64>r;r+=8){if(-1==(s=m(t)))throw Error("truncated input");1==(s=s.toString(16)).length&&(s="0"+s),a=s+""+a}/^0+$|^f+$/i.test(a)?e.Tb=Ve:(o=parseInt(a,16),e.Tb=o>4294967295?Ve:l(o)),e.yb=function(e,t,n,i){return e.e.Ab=t,L(e.B),e.B.cc=n,function(e){e.B.h=0,e.B.o=0,Pe(e.Gb),Pe(e.pb),Pe(e.Zb),Pe(e.Cb),Pe(e.Db),Pe(e.Eb),Pe(e.kc),function(e){var t,n;for(n=1<<e.u+e.I,t=0;n>t;++t)Pe(e.V[t].Ib)}(e.gb);for(var t=0;4>t;++t)Pe(e.kb[t].G);z(e.Rb),z(e.sb),Pe(e.Fb.G),function(e){e.Bb=0,e.E=-1;for(var t=0;5>t;++t)e.Bb=e.Bb<<8|m(e.Ab)}(e.e)}(e),e.U=0,e.ib=0,e.Jc=0,e.Ic=0,e.Qc=0,e.Nc=i,e.g=ze,e.jc=0,function(e,t){return e.Z=t,e.cb=null,e.zc=1,e}({},e)}(i,t,n,e.Tb)}function E(e,t){return e.Nb=b({}),T(e,f({},t),e.Nb),e}function C(e,t){return e.c[e.f+e.o+t]}function S(e,t,n,i){var r,s;for(e.T&&e.o+t+i>e.h&&(i=e.h-(e.o+t)),++n,s=e.f+e.o+t,r=0;i>r&&e.c[s+r]==e.c[s+r-n];++r);return r}function I(e){return e.h-e.o}function P(e){var t,n;if(!e.T)for(;;){if(!(n=-e.f+e.Kb-e.h))return;if(-1==(t=g(e.cc,e.c,e.f+e.h,n)))return e.zb=e.h,e.f+e.zb>e.H&&(e.zb=e.H-e.f),void(e.T=1);e.h+=t,e.h>=e.o+e._b&&(e.zb=e.h-e._b)}}function U(e,t){e.f+=t,e.zb-=t,e.o-=t,e.h-=t}function _(e,t,i,r,s){var o,a;1073741567>t&&(e.Fc=16+(r>>1),function(e,t,i,r){var s;e.Bc=t,e._b=i,s=t+i+r,(null==e.c||e.Kb!=s)&&(e.c=null,e.Kb=s,e.c=n(e.Kb)),e.H=e.Kb-i}(e,t+i,r+s,256+~~((t+i+r+s)/2)),e.ob=r,o=t+1,e.p!=o&&(e.L=n(2*(e.p=o))),a=65536,e.qb&&(a=t-1,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a>>=1,(a|=65535)>16777216&&(a>>=1),e.Ec=a,++a,a+=e.R),a!=e.rc&&(e.ub=n(e.rc=a)))}function N(e){var t;++e.k>=e.p&&(e.k=0),function(e){++e.o,e.o>e.zb&&(e.f+e.o>e.H&&function(e){var t,n,i;for((i=e.f+e.o-e.Bc)>0&&--i,n=e.f+e.h-i,t=0;n>t;++t)e.c[t]=e.c[i+t];e.f-=i}(e),P(e))}(e),1073741823==e.o&&(t=e.o-e.p,O(e.L,2*e.p,t),O(e.ub,e.rc,t),U(e,t))}function O(e,t,n){var i,r;for(i=0;t>i;++i)n>=(r=e[i]||0)?r=0:r-=n,e[i]=r}function D(e,t){(null==e.Lb||e.M!=t)&&(e.Lb=n(t)),e.M=t,e.o=0,e.h=0}function R(e){var t=e.o-e.h;t&&(w(e.cc,e.Lb,e.h,t),e.o>=e.M&&(e.o=0),e.h=e.o)}function M(e,t){var n=e.o-t-1;return 0>n&&(n+=e.M),e.Lb[n]}function L(e){R(e),e.cc=null}function B(e){return 4>(e-=2)?e:3}function F(e){return 4>e?0:10>e?e-3:e-6}function $(e){if(!e.zc)throw Error("bad state");return e.cb?function(e){(function(e,t,n,r){var o,u,d,h,f,m,g,b,y,v,w,x,k,A,T;if(t[0]=ze,n[0]=ze,r[0]=1,e.oc&&(e.b.cc=e.oc,function(e){e.f=0,e.o=0,e.h=0,e.T=0,P(e),e.k=0,U(e,-1)}(e.b),e.W=1,e.oc=null),!e.pc){if(e.pc=1,A=e.g,a(e.g,ze)){if(!I(e.b))return void Q(e,c(e.g));ie(e),k=c(e.g)&e.y,Ue(e.d,e.C,(e.l<<4)+k,0),e.l=F(e.l),d=C(e.b,-e.s),fe(pe(e.A,c(e.g),e.J),e.d,d),e.J=d,--e.s,e.g=i(e.g,We)}if(!I(e.b))return void Q(e,c(e.g));for(;;){if(g=Z(e,c(e.g)),v=e.mb,k=c(e.g)&e.y,u=(e.l<<4)+k,1==g&&-1==v)Ue(e.d,e.C,u,0),d=C(e.b,-e.s),T=pe(e.A,c(e.g),e.J),7>e.l?fe(T,e.d,d):(y=C(e.b,-e.v[0]-1-e.s),me(T,e.d,y,d)),e.J=d,e.l=F(e.l);else{if(Ue(e.d,e.C,u,1),4>v){if(Ue(e.d,e.bb,e.l,1),v?(Ue(e.d,e.hb,e.l,1),1==v?Ue(e.d,e.Ub,e.l,0):(Ue(e.d,e.Ub,e.l,1),Ue(e.d,e.vc,e.l,v-2))):(Ue(e.d,e.hb,e.l,0),Ue(e.d,e._,u,1==g?0:1)),1==g?e.l=7>e.l?9:11:(le(e.i,e.d,g-2,k),e.l=7>e.l?8:11),h=e.v[v],0!=v){for(m=v;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h}}else{for(Ue(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,g-2,k),x=se(v-=4),b=B(g),ke(e.K[b],e.d,x),x>=4&&(w=v-(o=(2|1&x)<<(f=(x>>1)-1)),14>x?Ce(e.Sb,o-x-1,e.d,f,w):(_e(e.d,w>>4,f-4),Te(e.S,e.d,15&w),++e.Qb)),h=v,m=3;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h,++e.Mb}e.J=C(e.b,g-1-e.s)}if(e.s-=g,e.g=i(e.g,l(g)),!e.s){if(e.Mb>=128&&X(e),e.Qb>=16&&K(e),t[0]=e.g,n[0]=Ne(e.d),!I(e.b))return void Q(e,c(e.g));if(s(p(e.g,A),[4096,0])>=0)return e.pc=0,void(r[0]=0)}}}})(e.cb,e.cb.Xb,e.cb.uc,e.cb.Kc),e.Pb=e.cb.Xb[0],e.cb.Kc[0]&&(function(e){re(e),e.d.Ab=null}(e.cb),e.zc=0)}(e):function(e){var t=function(e){var t,n,r,o,a,u;if(u=c(e.g)&e.Dc,Ie(e.e,e.Gb,(e.U<<4)+u)){if(Ie(e.e,e.Zb,e.U))r=0,Ie(e.e,e.Cb,e.U)?(Ie(e.e,e.Db,e.U)?(Ie(e.e,e.Eb,e.U)?(n=e.Qc,e.Qc=e.Ic):n=e.Ic,e.Ic=e.Jc):n=e.Jc,e.Jc=e.ib,e.ib=n):Ie(e.e,e.pb,(e.U<<4)+u)||(e.U=7>e.U?9:11,r=1),r||(r=V(e.sb,e.e,u)+2,e.U=7>e.U?8:11);else if(e.Qc=e.Ic,e.Ic=e.Jc,e.Jc=e.ib,r=2+V(e.Rb,e.e,u),e.U=7>e.U?7:10,(a=we(e.kb[B(r)],e.e))>=4){if(o=(a>>1)-1,e.ib=(2|1&a)<<o,14>a)e.ib+=function(e,t,n,i){var r,s,o=1,a=0;for(s=0;i>s;++s)r=Ie(n,e,t+o),o<<=1,o+=r,a|=r<<s;return a}(e.kc,e.ib-a-1,e.e,o);else if(e.ib+=function(e,t){var n,i,r=0;for(n=t;0!=n;--n)e.E>>>=1,i=e.Bb-e.E>>>31,e.Bb-=e.E&i-1,r=r<<1|1-i,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8);return r}(e.e,o-4)<<4,e.ib+=function(e,t){var n,i,r=1,s=0;for(i=0;e.F>i;++i)n=Ie(t,e.G,r),r<<=1,r+=n,s|=n<<i;return s}(e.Fb,e.e),0>e.ib)return-1==e.ib?1:-1}else e.ib=a;if(s(l(e.ib),e.g)>=0||e.ib>=e.nb)return-1;(function(e,t,n){var i=e.o-t-1;for(0>i&&(i+=e.M);0!=n;--n)i>=e.M&&(i=0),e.Lb[e.o++]=e.Lb[i++],e.o>=e.M&&R(e)})(e.B,e.ib,r),e.g=i(e.g,l(r)),e.jc=M(e.B,0)}else t=function(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}(e.gb,c(e.g),e.jc),e.jc=7>e.U?function(e,t){var n=1;do{n=n<<1|Ie(t,e.Ib,n)}while(256>n);return n<<24>>24}(t,e.e):function(e,t,n){var i,r,s=1;do{if(r=n>>7&1,n<<=1,i=Ie(t,e.Ib,(1+r<<8)+s),s=s<<1|i,r!=i){for(;256>s;)s=s<<1|Ie(t,e.Ib,s);break}}while(256>s);return s<<24>>24}(t,e.e,M(e.B,e.ib)),function(e,t){e.Lb[e.o++]=t,e.o>=e.M&&R(e)}(e.B,e.jc),e.U=F(e.U),e.g=i(e.g,We);return 0}(e.Z);if(-1==t)throw Error("corrupted input");e.Pb=Ve,e.Pc=e.Z.g,(t||s(e.Z.Nc,ze)>=0&&s(e.Z.g,e.Z.Nc)>=0)&&(R(e.Z.B),L(e.Z.B),e.Z.e.Ab=null,e.zc=0)}(e),e.zc}function j(e){e.B={},e.e={},e.Gb=n(192),e.Zb=n(12),e.Cb=n(12),e.Db=n(12),e.Eb=n(12),e.pb=n(192),e.kb=n(4),e.kc=n(114),e.Fb=ve({},4),e.Rb=G({}),e.sb=G({}),e.gb={};for(var t=0;4>t;++t)e.kb[t]=ve({},6);return e}function H(e,t){for(;t>e.O;++e.O)e.ec[e.O]=ve({},3),e.hc[e.O]=ve({},3)}function V(e,t,n){return Ie(t,e.wc,0)?8+(Ie(t,e.wc,1)?8+we(e.tc,t):we(e.hc[n],t)):we(e.ec[n],t)}function G(e){return e.wc=n(2),e.ec=n(16),e.hc=n(16),e.tc=ve({},8),e.O=0,e}function z(e){Pe(e.wc);for(var t=0;e.O>t;++t)Pe(e.ec[t].G),Pe(e.hc[t].G);Pe(e.tc.G)}function W(e,t,i){var r,s;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,s=1<<e.u+e.I,e.V=n(s),r=0;s>r;++r)e.V[r]=q({})}function q(e){return e.Ib=n(768),e}function J(e,t){var n,i,r,s;e.jb=t,r=e.a[t].r,i=e.a[t].j;do{e.a[t].t&&(ye(e.a[r]),e.a[r].r=r-1,e.a[t].Ac&&(e.a[r-1].t=0,e.a[r-1].r=e.a[t].r2,e.a[r-1].j=e.a[t].j2)),s=r,n=i,i=e.a[s].j,r=e.a[s].r,e.a[s].j=n,e.a[s].r=t,t=s}while(t>0);return e.mb=e.a[0].j,e.q=e.a[0].r}function Y(e){var t;for(e.v=n(4),e.a=[],e.d={},e.C=n(192),e.bb=n(12),e.hb=n(12),e.Ub=n(12),e.vc=n(12),e._=n(192),e.K=[],e.Sb=n(114),e.S=xe({},4),e.$=ce({}),e.i=ce({}),e.A={},e.m=[],e.P=[],e.lb=[],e.nc=n(16),e.x=n(4),e.Q=n(4),e.Xb=[ze],e.uc=[ze],e.Kc=[0],e.fc=n(5),e.yc=n(128),e.vb=0,e.X=1,e.D=0,e.Hb=-1,e.mb=0,t=0;4096>t;++t)e.a[t]={};for(t=0;4>t;++t)e.K[t]=xe({},6);return e}function K(e){for(var t=0;16>t;++t)e.nc[t]=Ee(e.S,t);e.Qb=0}function X(e){var t,n,i,r,s,o,a,l;for(r=4;128>r;++r)t=(2|1&(o=se(r)))<<(i=(o>>1)-1),e.yc[r]=Se(e.Sb,t-o-1,i,r-t);for(s=0;4>s;++s){for(n=e.K[s],a=s<<6,o=0;e.$b>o;++o)e.P[a+o]=Ae(n,o);for(o=14;e.$b>o;++o)e.P[a+o]+=(o>>1)-1-4<<6;for(l=128*s,r=0;4>r;++r)e.lb[l+r]=e.P[a+r];for(;128>r;++r)e.lb[l+r]=e.P[a+se(r)]+e.yc[r]}e.Mb=0}function Q(e,t){re(e),function(e,t){if(e.Gc){Ue(e.d,e.C,(e.l<<4)+t,1),Ue(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,0,t);var n=B(2);ke(e.K[n],e.d,63),_e(e.d,67108863,26),Te(e.S,e.d,15)}}(e,t&e.y);for(var n=0;5>n;++n)Oe(e.d)}function Z(e,t){var n,i,r,s,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,x,k,A,T,E,P,U,_,N,O,D,R,M,L,B,$,j,H,V,G,z,W,q,Y,K;if(e.jb!=e.q)return f=e.a[e.q].r-e.q,e.mb=e.a[e.q].j,e.q=e.a[e.q].r,f;if(e.q=e.jb=0,e.N?(p=e.vb,e.N=0):p=ie(e),U=e.D,2>(E=I(e.b)+1))return e.mb=-1,1;for(E>273&&(E=273),G=0,u=0;4>u;++u)e.x[u]=e.v[u],e.Q[u]=S(e.b,-1,e.x[u],273),e.Q[u]>e.Q[G]&&(G=u);if(e.Q[G]>=e.n)return e.mb=G,ne(e,(f=e.Q[G])-1),f;if(p>=e.n)return e.mb=e.m[U-1]+4,ne(e,p-1),p;if(l=C(e.b,-1),y=C(e.b,-e.v[0]-1-1),2>p&&l!=y&&2>e.Q[G])return e.mb=-1,1;if(e.a[0].Hc=e.l,L=t&e.y,e.a[1].z=Ye[e.C[(e.l<<4)+L]>>>2]+be(pe(e.A,t,e.J),e.l>=7,y,l),ye(e.a[1]),V=(v=Ye[2048-e.C[(e.l<<4)+L]>>>2])+Ye[2048-e.bb[e.l]>>>2],y==l&&(z=V+function(e,t,n){return Ye[e.hb[t]>>>2]+Ye[e._[(t<<4)+n]>>>2]}(e,e.l,L),e.a[1].z>z&&(e.a[1].z=z,function(e){e.j=0,e.t=0}(e.a[1]))),2>(h=p>=e.Q[G]?p:e.Q[G]))return e.mb=e.a[1].j,1;e.a[1].r=0,e.a[0].bc=e.x[0],e.a[0].ac=e.x[1],e.a[0].dc=e.x[2],e.a[0].lc=e.x[3],d=h;do{e.a[d--].z=268435455}while(d>=2);for(u=0;4>u;++u)if(!(2>(H=e.Q[u]))){$=V+te(e,u,e.l,L);do{s=$+ue(e.i,H-2,L),(D=e.a[H]).z>s&&(D.z=s,D.r=0,D.j=u,D.t=0)}while(--H>=2)}if(T=v+Ye[e.bb[e.l]>>>2],p>=(d=e.Q[0]>=2?e.Q[0]+1:2)){for(_=0;d>e.m[_];)_+=2;for(;s=T+ee(e,c=e.m[_+1],d,L),(D=e.a[d]).z>s&&(D.z=s,D.r=0,D.j=c+4,D.t=0),d!=e.m[_]||(_+=2)!=U;++d);}for(n=0;;){if(++n==h)return J(e,n);if(w=ie(e),U=e.D,w>=e.n)return e.vb=w,e.N=1,J(e,n);if(++t,M=e.a[n].r,e.a[n].t?(--M,e.a[n].Ac?(q=e.a[e.a[n].r2].Hc,q=4>e.a[n].j2?7>q?8:11:7>q?7:10):q=e.a[M].Hc,q=F(q)):q=e.a[M].Hc,M==n-1?q=e.a[n].j?F(q):7>q?9:11:(e.a[n].t&&e.a[n].Ac?(M=e.a[n].r2,R=e.a[n].j2,q=7>q?8:11):q=4>(R=e.a[n].j)?7>q?8:11:7>q?7:10,O=e.a[M],4>R?R?1==R?(e.x[0]=O.ac,e.x[1]=O.bc,e.x[2]=O.dc,e.x[3]=O.lc):2==R?(e.x[0]=O.dc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.lc):(e.x[0]=O.lc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc):(e.x[0]=O.bc,e.x[1]=O.ac,e.x[2]=O.dc,e.x[3]=O.lc):(e.x[0]=R-4,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc)),e.a[n].Hc=q,e.a[n].bc=e.x[0],e.a[n].ac=e.x[1],e.a[n].dc=e.x[2],e.a[n].lc=e.x[3],a=e.a[n].z,l=C(e.b,-1),y=C(e.b,-e.x[0]-1-1),L=t&e.y,i=a+Ye[e.C[(q<<4)+L]>>>2]+be(pe(e.A,t,C(e.b,-2)),q>=7,y,l),x=0,(k=e.a[n+1]).z>i&&(k.z=i,k.r=n,k.j=-1,k.t=0,x=1),V=(v=a+Ye[2048-e.C[(q<<4)+L]>>>2])+Ye[2048-e.bb[q]>>>2],y!=l||n>k.r&&!k.j||(z=V+(Ye[e.hb[q]>>>2]+Ye[e._[(q<<4)+L]>>>2]),k.z>=z&&(k.z=z,k.r=n,k.j=0,k.t=0,x=1)),!(2>(E=P=(P=I(e.b)+1)>4095-n?4095-n:P))){if(E>e.n&&(E=e.n),!x&&y!=l&&(K=Math.min(P-1,e.n),(g=S(e.b,0,e.x[0],K))>=2)){for(Y=F(q),B=t+1&e.y,A=i+Ye[2048-e.C[(Y<<4)+B]>>>2]+Ye[2048-e.bb[Y]>>>2],N=n+1+g;N>h;)e.a[++h].z=268435455;s=A+(ue(e.i,g-2,B)+te(e,0,Y,B)),(D=e.a[N]).z>s&&(D.z=s,D.r=n+1,D.j=0,D.t=1,D.Ac=0)}for(W=2,j=0;4>j;++j)if(!(2>(m=S(e.b,-1,e.x[j],E)))){b=m;do{for(;n+m>h;)e.a[++h].z=268435455;s=V+(ue(e.i,m-2,L)+te(e,j,q,L)),(D=e.a[n+m]).z>s&&(D.z=s,D.r=n,D.j=j,D.t=0)}while(--m>=2);if(m=b,j||(W=m+1),P>m&&(K=Math.min(P-1-m,e.n),(g=S(e.b,m,e.x[j],K))>=2)){for(Y=7>q?8:11,B=t+m&e.y,r=V+(ue(e.i,m-2,L)+te(e,j,q,L))+Ye[e.C[(Y<<4)+B]>>>2]+be(pe(e.A,t+m,C(e.b,m-1-1)),1,C(e.b,m-1-(e.x[j]+1)),C(e.b,m-1)),Y=F(Y),B=t+m+1&e.y,A=r+Ye[2048-e.C[(Y<<4)+B]>>>2]+Ye[2048-e.bb[Y]>>>2],N=m+1+g;n+N>h;)e.a[++h].z=268435455;s=A+(ue(e.i,g-2,B)+te(e,0,Y,B)),(D=e.a[n+N]).z>s&&(D.z=s,D.r=n+m+1,D.j=0,D.t=1,D.Ac=1,D.r2=n,D.j2=j)}}if(w>E){for(w=E,U=0;w>e.m[U];U+=2);e.m[U]=w,U+=2}if(w>=W){for(T=v+Ye[e.bb[q]>>>2];n+w>h;)e.a[++h].z=268435455;for(_=0;W>e.m[_];)_+=2;for(m=W;;++m)if(s=T+ee(e,o=e.m[_+1],m,L),(D=e.a[n+m]).z>s&&(D.z=s,D.r=n,D.j=o+4,D.t=0),m==e.m[_]){if(P>m&&(K=Math.min(P-1-m,e.n),(g=S(e.b,m,o,K))>=2)){for(Y=7>q?7:10,B=t+m&e.y,r=s+Ye[e.C[(Y<<4)+B]>>>2]+be(pe(e.A,t+m,C(e.b,m-1-1)),1,C(e.b,m-(o+1)-1),C(e.b,m-1)),Y=F(Y),B=t+m+1&e.y,A=r+Ye[2048-e.C[(Y<<4)+B]>>>2]+Ye[2048-e.bb[Y]>>>2],N=m+1+g;n+N>h;)e.a[++h].z=268435455;s=A+(ue(e.i,g-2,B)+te(e,0,Y,B)),(D=e.a[n+N]).z>s&&(D.z=s,D.r=n+m+1,D.j=0,D.t=1,D.Ac=1,D.r2=n,D.j2=o+4)}if((_+=2)==U)break}}}}}function ee(e,t,n,i){var r=B(n);return(128>t?e.lb[128*r+t]:e.P[(r<<6)+function(e){return 131072>e?Je[e>>6]+12:134217728>e?Je[e>>16]+32:Je[e>>26]+52}(t)]+e.nc[15&t])+ue(e.$,n-2,i)}function te(e,t,n,i){var r;return t?(r=Ye[2048-e.hb[n]>>>2],1==t?r+=Ye[e.Ub[n]>>>2]:(r+=Ye[2048-e.Ub[n]>>>2],r+=De(e.vc[n],t-2))):(r=Ye[e.hb[n]>>>2],r+=Ye[2048-e._[(n<<4)+i]>>>2]),r}function ne(e,t){t>0&&(function(e,t){var n,i,r,s,o,a,l,c,u,d,h,p,f,m,g,b,y;do{if(e.h>=e.o+e.ob)p=e.ob;else if(p=e.h-e.o,e.xb>p){N(e);continue}for(f=e.o>e.p?e.o-e.p:0,i=e.f+e.o,e.qb?(a=1023&(y=qe[255&e.c[i]]^255&e.c[i+1]),e.ub[a]=e.o,l=65535&(y^=(255&e.c[i+2])<<8),e.ub[1024+l]=e.o,c=(y^qe[255&e.c[i+3]]<<5)&e.Ec):c=255&e.c[i]^(255&e.c[i+1])<<8,r=e.ub[e.R+c],e.ub[e.R+c]=e.o,g=1+(e.k<<1),b=e.k<<1,d=h=e.w,n=e.Fc;;){if(f>=r||0==n--){e.L[g]=e.L[b]=0;break}if(o=e.o-r,s=(e.k>=o?e.k-o:e.k-o+e.p)<<1,m=e.f+r,u=h>d?d:h,e.c[m+u]==e.c[i+u]){for(;++u!=p&&e.c[m+u]==e.c[i+u];);if(u==p){e.L[b]=e.L[s],e.L[g]=e.L[s+1];break}}(255&e.c[i+u])>(255&e.c[m+u])?(e.L[b]=r,b=s+1,r=e.L[b],h=u):(e.L[g]=r,g=s,r=e.L[g],d=u)}N(e)}while(0!=--t)}(e.b,t),e.s+=t)}function ie(e){var t=0;return e.D=function(e,t){var n,i,r,s,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,x,k;if(e.h>=e.o+e.ob)m=e.ob;else if(m=e.h-e.o,e.xb>m)return N(e),0;for(y=0,g=e.o>e.p?e.o-e.p:0,i=e.f+e.o,b=1,c=0,u=0,e.qb?(c=1023&(k=qe[255&e.c[i]]^255&e.c[i+1]),u=65535&(k^=(255&e.c[i+2])<<8),d=(k^qe[255&e.c[i+3]]<<5)&e.Ec):d=255&e.c[i]^(255&e.c[i+1])<<8,r=e.ub[e.R+d]||0,e.qb&&(s=e.ub[c]||0,o=e.ub[1024+u]||0,e.ub[c]=e.o,e.ub[1024+u]=e.o,s>g&&e.c[e.f+s]==e.c[i]&&(t[y++]=b=2,t[y++]=e.o-s-1),o>g&&e.c[e.f+o]==e.c[i]&&(o==s&&(y-=2),t[y++]=b=3,t[y++]=e.o-o-1,s=o),0!=y&&s==r&&(y-=2,b=1)),e.ub[e.R+d]=e.o,w=1+(e.k<<1),x=e.k<<1,p=f=e.w,0!=e.w&&r>g&&e.c[e.f+r+e.w]!=e.c[i+e.w]&&(t[y++]=b=e.w,t[y++]=e.o-r-1),n=e.Fc;;){if(g>=r||0==n--){e.L[w]=e.L[x]=0;break}if(l=e.o-r,a=(e.k>=l?e.k-l:e.k-l+e.p)<<1,v=e.f+r,h=f>p?p:f,e.c[v+h]==e.c[i+h]){for(;++h!=m&&e.c[v+h]==e.c[i+h];);if(h>b&&(t[y++]=b=h,t[y++]=l-1,h==m)){e.L[x]=e.L[a],e.L[w]=e.L[a+1];break}}(255&e.c[i+h])>(255&e.c[v+h])?(e.L[x]=r,x=a+1,r=e.L[x],f=h):(e.L[w]=r,w=a,r=e.L[w],p=h)}return N(e),y}(e.b,e.m),e.D>0&&((t=e.m[e.D-2])==e.n&&(t+=S(e.b,t-1,e.m[e.D-1],273-t))),++e.s,t}function re(e){e.b&&e.W&&(e.b.cc=null,e.W=0)}function se(e){return 2048>e?Je[e]:2097152>e?Je[e>>10]+20:Je[e>>20]+40}function oe(e,t){Pe(e.db);for(var n=0;t>n;++n)Pe(e.Vb[n].G),Pe(e.Wb[n].G);Pe(e.ic.G)}function ae(e,t,n,i,r){var s,o,a,l,c;for(s=Ye[e.db[0]>>>2],a=(o=Ye[2048-e.db[0]>>>2])+Ye[e.db[1]>>>2],l=o+Ye[2048-e.db[1]>>>2],c=0,c=0;8>c;++c){if(c>=n)return;i[r+c]=s+Ae(e.Vb[t],c)}for(;16>c;++c){if(c>=n)return;i[r+c]=a+Ae(e.Wb[t],c-8)}for(;n>c;++c)i[r+c]=l+Ae(e.ic,c-8-8)}function le(e,t,n,i){(function(e,t,n,i){8>n?(Ue(t,e.db,0,0),ke(e.Vb[i],t,n)):(n-=8,Ue(t,e.db,0,1),8>n?(Ue(t,e.db,1,0),ke(e.Wb[i],t,n)):(Ue(t,e.db,1,1),ke(e.ic,t,n-8)))})(e,t,n,i),0==--e.sc[i]&&(ae(e,i,e.rb,e.Cc,272*i),e.sc[i]=e.rb)}function ce(e){return function(e){e.db=n(2),e.Vb=n(16),e.Wb=n(16),e.ic=xe({},8);for(var t=0;16>t;++t)e.Vb[t]=xe({},3),e.Wb[t]=xe({},3)}(e),e.Cc=[],e.sc=[],e}function ue(e,t,n){return e.Cc[272*n+t]}function de(e,t){for(var n=0;t>n;++n)ae(e,n,e.rb,e.Cc,272*n),e.sc[n]=e.rb}function he(e,t,i){var r,s;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,s=1<<e.u+e.I,e.V=n(s),r=0;s>r;++r)e.V[r]=ge({})}function pe(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}function fe(e,t,n){var i,r,s=1;for(r=7;r>=0;--r)i=n>>r&1,Ue(t,e.tb,s,i),s=s<<1|i}function me(e,t,n,i){var r,s,o,a,l=1,c=1;for(s=7;s>=0;--s)r=i>>s&1,a=c,l&&(a+=1+(o=n>>s&1)<<8,l=o==r),Ue(t,e.tb,a,r),c=c<<1|r}function ge(e){return e.tb=n(768),e}function be(e,t,n,i){var r,s,o=1,a=7,l=0;if(t)for(;a>=0;--a)if(s=n>>a&1,r=i>>a&1,l+=De(e.tb[(1+s<<8)+o],r),o=o<<1|r,s!=r){--a;break}for(;a>=0;--a)r=i>>a&1,l+=De(e.tb[o],r),o=o<<1|r;return l}function ye(e){e.j=-1,e.t=0}function ve(e,t){return e.F=t,e.G=n(1<<t),e}function we(e,t){var n,i=1;for(n=e.F;0!=n;--n)i=(i<<1)+Ie(t,e.G,i);return i-(1<<e.F)}function xe(e,t){return e.F=t,e.G=n(1<<t),e}function ke(e,t,n){var i,r,s=1;for(r=e.F;0!=r;)i=n>>>--r&1,Ue(t,e.G,s,i),s=s<<1|i}function Ae(e,t){var n,i,r=1,s=0;for(i=e.F;0!=i;)n=t>>>--i&1,s+=De(e.G[r],n),r=(r<<1)+n;return s}function Te(e,t,n){var i,r,s=1;for(r=0;e.F>r;++r)i=1&n,Ue(t,e.G,s,i),s=s<<1|i,n>>=1}function Ee(e,t){var n,i,r=1,s=0;for(i=e.F;0!=i;--i)n=1&t,t>>>=1,s+=De(e.G[r],n),r=r<<1|n;return s}function Ce(e,t,n,i,r){var s,o,a=1;for(o=0;i>o;++o)Ue(n,e,t+a,s=1&r),a=a<<1|s,r>>=1}function Se(e,t,n,i){var r,s,o=1,a=0;for(s=n;0!=s;--s)r=1&i,i>>>=1,a+=Ye[(2047&(e[t+o]-r^-r))>>>2],o=o<<1|r;return a}function Ie(e,t,n){var i,r=t[n];return(-2147483648^(i=(e.E>>>11)*r))>(-2147483648^e.Bb)?(e.E=i,t[n]=r+(2048-r>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),0):(e.E-=i,e.Bb-=i,t[n]=r-(r>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),1)}function Pe(e){for(var t=e.length-1;t>=0;--t)e[t]=1024}function Ue(e,t,n,s){var o,a=t[n];o=(e.E>>>11)*a,s?(e.xc=i(e.xc,r(l(o),[4294967295,0])),e.E-=o,t[n]=a-(a>>>5)<<16>>16):(e.E=o,t[n]=a+(2048-a>>>5)<<16>>16),-16777216&e.E||(e.E<<=8,Oe(e))}function _e(e,t,n){for(var r=n-1;r>=0;--r)e.E>>>=1,1==(t>>>r&1)&&(e.xc=i(e.xc,l(e.E))),-16777216&e.E||(e.E<<=8,Oe(e))}function Ne(e){return i(i(l(e.Jb),e.mc),[4,0])}function Oe(e){var t,n=c(function(e,t){var n;return n=h(e,t&=63),0>e[1]&&(n=i(n,d([2,0],63-t))),n}(e.xc,32));if(0!=n||s(e.xc,[4278190080,0])<0){e.mc=i(e.mc,l(e.Jb)),t=e.Oc;do{v(e.Ab,t+n),t=255}while(0!=--e.Jb);e.Oc=c(e.xc)>>>24}++e.Jb,e.xc=d(r(e.xc,[16777215,0]),8)}function De(e,t){return Ye[(2047&(e-t^-t))>>>2]}function Re(e){for(var t,n,i,r=0,s=0,o=e.length,a=[],l=[];o>r;++r,++s){if(128&(t=255&e[r]))if(192==(224&t)){if(r+1>=o)return e;if(128!=(192&(n=255&e[++r])))return e;l[s]=(31&t)<<6|63&n}else{if(224!=(240&t))return e;if(r+2>=o)return e;if(128!=(192&(n=255&e[++r])))return e;if(128!=(192&(i=255&e[++r])))return e;l[s]=(15&t)<<12|(63&n)<<6|63&i}else{if(!t)return e;l[s]=t}16383==s&&(a.push(String.fromCharCode.apply(String,l)),s=-1)}return s>0&&(l.length=s,a.push(String.fromCharCode.apply(String,l))),a.join("")}function Me(e){var t,n,i,r=[],s=0,o=e.length;if("object"==typeof e)return e;for(function(e,t,n,i,r){var s;for(s=t;n>s;++s)i[r++]=e.charCodeAt(s)}(e,0,o,r,0),i=0;o>i;++i)(t=r[i])>=1&&127>=t?++s:s+=!t||t>=128&&2047>=t?2:3;for(n=[],s=0,i=0;o>i;++i)(t=r[i])>=1&&127>=t?n[s++]=t<<24>>24:!t||t>=128&&2047>=t?(n[s++]=(192|t>>6&31)<<24>>24,n[s++]=(128|63&t)<<24>>24):(n[s++]=(224|t>>12&15)<<24>>24,n[s++]=(128|t>>6&63)<<24>>24,n[s++]=(128|63&t)<<24>>24);return n}function Le(e){return e[1]+e[0]}var Be=1,Fe=2,$e=3,je="function"==typeof setImmediate?setImmediate:setTimeout,He=4294967296,Ve=[4294967295,-He],Ge=[0,-0x8000000000000000],ze=[0,0],We=[1,0],qe=function(){var e,t,n,i=[];for(e=0;256>e;++e){for(n=e,t=0;8>t;++t)0!=(1&n)?n=n>>>1^-306674912:n>>>=1;i[e]=n}return i}(),Je=function(){var e,t,n,i=2,r=[0,1];for(n=2;22>n;++n)for(t=1<<(n>>1)-1,e=0;t>e;++e,++i)r[i]=n<<24>>24;return r}(),Ye=function(){var e,t,n,i=[];for(t=8;t>=0;--t)for(e=1<<9-t,n=1<<9-t-1;e>n;++n)i[n]=(t<<6)+(e-n<<6>>>9-t-1);return i}(),Ke=function(){var e=[{s:16,f:64,m:0},{s:20,f:64,m:0},{s:19,f:64,m:1},{s:20,f:64,m:1},{s:21,f:128,m:1},{s:22,f:128,m:1},{s:23,f:128,m:1},{s:24,f:255,m:1},{s:25,f:255,m:1}];return function(t){return e[t-1]||e[6]}}();return"undefined"==typeof onmessage||"undefined"!=typeof window&&void 0!==window.document||(onmessage=function(t){t&&t.gc&&(t.gc.action==Fe?e.decompress(t.gc.gc,t.gc.cbn):t.gc.action==Be&&e.compress(t.gc.gc,t.gc.Rc,t.gc.cbn))}),{compress:function(e,n,i,r){var s,o,a={},l=void 0===i&&void 0===r;if("function"!=typeof i&&(o=i,i=r=0),r=r||function(e){return void 0!==o?t(e,o):void 0},i=i||function(e,t){return void 0!==o?postMessage({action:Be,cbn:o,result:e,error:t}):void 0},l){for(a.c=A({},Me(e),Ke(n));$(a.c.yb););return y(a.c.Nb)}try{a.c=A({},Me(e),Ke(n)),r(0)}catch(e){return i(null,e)}je((function e(){try{for(var t,n=(new Date).getTime();$(a.c.yb);)if(s=Le(a.c.yb.Pb)/Le(a.c.Tb),(new Date).getTime()-n>200)return r(s),je(e,0),0;r(1),t=y(a.c.Nb),je(i.bind(null,t),0)}catch(e){i(null,e)}}),0)},decompress:function(e,n,i){var r,s,o,a,l={},c=void 0===n&&void 0===i;if("function"!=typeof n&&(s=n,n=i=0),i=i||function(e){return void 0!==s?t(o?e:-1,s):void 0},n=n||function(e,t){return void 0!==s?postMessage({action:Fe,cbn:s,result:e,error:t}):void 0},c){for(l.d=E({},e);$(l.d.yb););return Re(y(l.d.Nb))}try{l.d=E({},e),a=Le(l.d.Tb),o=a>-1,i(0)}catch(e){return n(null,e)}je((function e(){try{for(var t,s=0,c=(new Date).getTime();$(l.d.yb);)if(++s%1e3==0&&(new Date).getTime()-c>200)return o&&(r=Le(l.d.yb.Z.g)/a,i(r)),je(e,0),0;i(1),t=Re(y(l.d.Nb)),je(n.bind(null,t),0)}catch(e){n(null,e)}}),0)}}}(),pxt,pxt,pxt,pxt,pxt,ts;this.LZMA=this.LZMA_WORKER=e,function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.DOMPurify=t()}(this,(function(){"use strict";function e(e){return function(t){for(var n=arguments.length,i=Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return h(e,t,i)}}function t(e){return function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];return p(e,n)}}function n(e,t){o&&o(e,null);for(var n=t.length;n--;){var i=t[n];if("string"==typeof i){var r=w(i);r!==i&&(a(t)||(t[n]=r),i=r)}e[i]=!0}return e}function i(e){var t={},n=void 0;for(n in e)h(s,e,[n])&&(t[n]=e[n]);return t}function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var s=Object.hasOwnProperty,o=Object.setPrototypeOf,a=Object.isFrozen,l=Object.keys,c=Object.freeze,u=Object.seal,d="undefined"!=typeof Reflect&&Reflect,h=d.apply,p=d.construct;h||(h=function(e,t,n){return e.apply(t,n)}),c||(c=function(e){return e}),u||(u=function(e){return e}),p||(p=function(e,t){return new(Function.prototype.bind.apply(e,[null].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(t))))});var f=e(Array.prototype.forEach),m=e(Array.prototype.indexOf),g=e(Array.prototype.join),b=e(Array.prototype.pop),y=e(Array.prototype.push),v=e(Array.prototype.slice),w=e(String.prototype.toLowerCase),x=e(String.prototype.match),k=e(String.prototype.replace),A=e(String.prototype.indexOf),T=e(String.prototype.trim),E=e(RegExp.prototype.test),C=t(RegExp),S=t(TypeError),I=c(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),P=c(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","audio","canvas","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","video","view","vkern"]),U=c(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),_=c(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),N=c(["#text"]),O=c(["accept","action","align","alt","autocomplete","background","bgcolor","border","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","coords","crossorigin","datetime","default","dir","disabled","download","enctype","face","for","headers","height","hidden","high","href","hreflang","id","integrity","ismap","label","lang","list","loop","low","max","maxlength","media","method","min","minlength","multiple","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","type","usemap","valign","value","width","xmlns"]),D=c(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","tabindex","targetx","targety","transform","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),R=c(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),M=c(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),L=u(/\{\{[\s\S]*|[\s\S]*\}\}/gm),B=u(/<%[\s\S]*|[\s\S]*%>/gm),F=u(/^data-[\-\w.\u00B7-\uFFFF]/),$=u(/^aria-[\-\w]+$/),j=u(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),H=u(/^(?:\w+script|data):/i),V=u(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g),G="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},z=function(){return"undefined"==typeof window?null:window},W=function(e,t){if("object"!==(void 0===e?"undefined":G(e))||"function"!=typeof e.createPolicy)return null;var n=null;t.currentScript&&t.currentScript.hasAttribute("data-tt-policy-suffix")&&(n=t.currentScript.getAttribute("data-tt-policy-suffix"));var i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}};return function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:z(),s=function(t){return e(t)};if(s.version="2.0.8",s.removed=[],!t||!t.document||9!==t.document.nodeType)return s.isSupported=!1,s;var o=t.document,a=!1,u=!1,d=t.document,h=t.DocumentFragment,p=t.HTMLTemplateElement,q=t.Node,J=t.NodeFilter,Y=t.NamedNodeMap,K=void 0===Y?t.NamedNodeMap||t.MozNamedAttrMap:Y,X=t.Text,Q=t.Comment,Z=t.DOMParser,ee=t.trustedTypes;if("function"==typeof p){var te=d.createElement("template");te.content&&te.content.ownerDocument&&(d=te.content.ownerDocument)}var ne=W(ee,o),ie=ne?ne.createHTML(""):"",re=d,se=re.implementation,oe=re.createNodeIterator,ae=re.getElementsByTagName,le=re.createDocumentFragment,ce=o.importNode,ue={};s.isSupported=se&&void 0!==se.createHTMLDocument&&9!==d.documentMode;var de=L,he=B,pe=F,fe=$,me=H,ge=V,be=j,ye=null,ve=n({},[].concat(r(I),r(P),r(U),r(_),r(N))),we=null,xe=n({},[].concat(r(O),r(D),r(R),r(M))),ke=null,Ae=null,Te=!0,Ee=!0,Ce=!1,Se=!1,Ie=!1,Pe=!1,Ue=!1,_e=!1,Ne=!1,Oe=!1,De=!1,Re=!1,Me=!0,Le=!0,Be=!1,Fe={},$e=n({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","plaintext","script","style","svg","template","thead","title","video","xmp"]),je=n({},["audio","video","img","source","image"]),He=null,Ve=n({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Ge=null,ze=d.createElement("form"),We=function(e){Ge&&Ge===e||(e&&"object"===(void 0===e?"undefined":G(e))||(e={}),ye="ALLOWED_TAGS"in e?n({},e.ALLOWED_TAGS):ve,we="ALLOWED_ATTR"in e?n({},e.ALLOWED_ATTR):xe,He="ADD_URI_SAFE_ATTR"in e?n(i(Ve),e.ADD_URI_SAFE_ATTR):Ve,ke="FORBID_TAGS"in e?n({},e.FORBID_TAGS):{},Ae="FORBID_ATTR"in e?n({},e.FORBID_ATTR):{},Fe="USE_PROFILES"in e&&e.USE_PROFILES,Te=!1!==e.ALLOW_ARIA_ATTR,Ee=!1!==e.ALLOW_DATA_ATTR,Ce=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Se=e.SAFE_FOR_JQUERY||!1,Ie=e.SAFE_FOR_TEMPLATES||!1,Pe=e.WHOLE_DOCUMENT||!1,Ne=e.RETURN_DOM||!1,Oe=e.RETURN_DOM_FRAGMENT||!1,De=e.RETURN_DOM_IMPORT||!1,Re=e.RETURN_TRUSTED_TYPE||!1,_e=e.FORCE_BODY||!1,Me=!1!==e.SANITIZE_DOM,Le=!1!==e.KEEP_CONTENT,Be=e.IN_PLACE||!1,be=e.ALLOWED_URI_REGEXP||be,Ie&&(Ee=!1),Oe&&(Ne=!0),Fe&&(ye=n({},[].concat(r(N))),we=[],!0===Fe.html&&(n(ye,I),n(we,O)),!0===Fe.svg&&(n(ye,P),n(we,D),n(we,M)),!0===Fe.svgFilters&&(n(ye,U),n(we,D),n(we,M)),!0===Fe.mathMl&&(n(ye,_),n(we,R),n(we,M))),e.ADD_TAGS&&(ye===ve&&(ye=i(ye)),n(ye,e.ADD_TAGS)),e.ADD_ATTR&&(we===xe&&(we=i(we)),n(we,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&n(He,e.ADD_URI_SAFE_ATTR),Le&&(ye["#text"]=!0),Pe&&n(ye,["html","head","body"]),ye.table&&(n(ye,["tbody"]),delete ke.tbody),c&&c(e),Ge=e)},qe=function(e){y(s.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=ie}},Je=function(e,t){try{y(s.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){y(s.removed,{attribute:null,from:t})}t.removeAttribute(e)},Ye=function(e){var t=void 0,i=void 0;if(_e)e="<remove></remove>"+e;else{var r=x(e,/^[\s]+/);i=r&&r[0]}var s=ne?ne.createHTML(e):e;if(a)try{t=(new Z).parseFromString(s,"text/html")}catch(e){}if(u&&n(ke,["title"]),!t||!t.documentElement){var o=(t=se.createHTMLDocument("")).body;o.parentNode.removeChild(o.parentNode.firstElementChild),o.outerHTML=s}return e&&i&&t.body.insertBefore(d.createTextNode(i),t.body.childNodes[0]||null),ae.call(t,Pe?"html":"body")[0]};s.isSupported&&(function(){try{Ye('<svg><p><textarea><img src="</textarea><img src=x abc=1//">').querySelector("svg img")&&(a=!0)}catch(e){}}(),function(){try{var e=Ye("<x/><title></title><img>");E(/<\/title/,e.querySelector("title").innerHTML)&&(u=!0)}catch(e){}}());var Ke=function(e){return oe.call(e.ownerDocument||e,e,J.SHOW_ELEMENT|J.SHOW_COMMENT|J.SHOW_TEXT,(function(){return J.FILTER_ACCEPT}),!1)},Xe=function(e){return!(e instanceof X||e instanceof Q||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof K&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI)},Qe=function(e){return"object"===(void 0===q?"undefined":G(q))?e instanceof q:e&&"object"===(void 0===e?"undefined":G(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},Ze=function(e,t,n){ue[e]&&f(ue[e],(function(e){e.call(s,t,n,Ge)}))},et=function(e){var t=void 0;if(Ze("beforeSanitizeElements",e,null),Xe(e))return qe(e),!0;var n=w(e.nodeName);if(Ze("uponSanitizeElement",e,{tagName:n,allowedTags:ye}),("svg"===n||"math"===n)&&0!==e.querySelectorAll("p, br").length)return qe(e),!0;if(!ye[n]||ke[n]){if(Le&&!$e[n]&&"function"==typeof e.insertAdjacentHTML)try{var i=e.innerHTML;e.insertAdjacentHTML("AfterEnd",ne?ne.createHTML(i):i)}catch(e){}return qe(e),!0}return"noscript"===n&&E(/<\/noscript/i,e.innerHTML)||"noembed"===n&&E(/<\/noembed/i,e.innerHTML)?(qe(e),!0):(!Se||e.firstElementChild||e.content&&e.content.firstElementChild||!E(/</g,e.textContent)||(y(s.removed,{element:e.cloneNode()}),e.innerHTML?e.innerHTML=k(e.innerHTML,/</g,"<"):e.innerHTML=k(e.textContent,/</g,"<")),Ie&&3===e.nodeType&&(t=e.textContent,t=k(t,de," "),t=k(t,he," "),e.textContent!==t&&(y(s.removed,{element:e.cloneNode()}),e.textContent=t)),Ze("afterSanitizeElements",e,null),!1)},tt=function(e,t,n){if(Me&&("id"===t||"name"===t)&&(n in d||n in ze))return!1;if(Ee&&E(pe,t));else if(Te&&E(fe,t));else{if(!we[t]||Ae[t])return!1;if(He[t]);else if(E(be,k(n,ge,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==A(n,"data:")||!je[e])if(Ce&&!E(me,k(n,ge,"")));else if(n)return!1}return!0},nt=function(e){var t=void 0,n=void 0,i=void 0,r=void 0,o=void 0;Ze("beforeSanitizeAttributes",e,null);var a=e.attributes;if(a){var c={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we};for(o=a.length;o--;){var u=t=a[o],d=u.name,h=u.namespaceURI;if(n=T(t.value),i=w(d),c.attrName=i,c.attrValue=n,c.keepAttr=!0,c.forceKeepAttr=void 0,Ze("uponSanitizeAttribute",e,c),n=c.attrValue,!c.forceKeepAttr){if("name"===i&&"IMG"===e.nodeName&&a.id)r=a.id,a=v(a,[]),Je("id",e),Je(d,e),m(a,r)>o&&e.setAttribute("id",r.value);else{if("INPUT"===e.nodeName&&"type"===i&&"file"===n&&c.keepAttr&&(we[i]||!Ae[i]))continue;"id"===d&&e.setAttribute(d,""),Je(d,e)}if(c.keepAttr)if(Se&&E(/\/>/i,n))Je(d,e);else if(E(/svg|math/i,e.namespaceURI)&&E(C("</("+g(l($e),"|")+")","i"),n))Je(d,e);else{Ie&&(n=k(n,de," "),n=k(n,he," "));var p=e.nodeName.toLowerCase();if(tt(p,i,n))try{h?e.setAttributeNS(h,d,n):e.setAttribute(d,n),b(s.removed)}catch(e){}}}}Ze("afterSanitizeAttributes",e,null)}},it=function e(t){var n=void 0,i=Ke(t);for(Ze("beforeSanitizeShadowDOM",t,null);n=i.nextNode();)Ze("uponSanitizeShadowNode",n,null),et(n)||(n.content instanceof h&&e(n.content),nt(n));Ze("afterSanitizeShadowDOM",t,null)};return s.sanitize=function(e,n){var i=void 0,r=void 0,a=void 0,l=void 0,c=void 0;if(e||(e="\x3c!--\x3e"),"string"!=typeof e&&!Qe(e)){if("function"!=typeof e.toString)throw S("toString is not a function");if("string"!=typeof(e=e.toString()))throw S("dirty is not a string, aborting")}if(!s.isSupported){if("object"===G(t.toStaticHTML)||"function"==typeof t.toStaticHTML){if("string"==typeof e)return t.toStaticHTML(e);if(Qe(e))return t.toStaticHTML(e.outerHTML)}return e}if(Ue||We(n),s.removed=[],"string"==typeof e&&(Be=!1),Be);else if(e instanceof q)1===(r=(i=Ye("\x3c!--\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?i=r:i.appendChild(r);else{if(!Ne&&!Ie&&!Pe&&Re&&-1===e.indexOf("<"))return ne?ne.createHTML(e):e;if(!(i=Ye(e)))return Ne?null:ie}i&&_e&&qe(i.firstChild);for(var u=Ke(Be?e:i);a=u.nextNode();)3===a.nodeType&&a===l||et(a)||(a.content instanceof h&&it(a.content),nt(a),l=a);if(l=null,Be)return e;if(Ne){if(Oe)for(c=le.call(i.ownerDocument);i.firstChild;)c.appendChild(i.firstChild);else c=i;return De&&(c=ce.call(o,c,!0)),c}var d=Pe?i.outerHTML:i.innerHTML;return Ie&&(d=k(d,de," "),d=k(d,he," ")),ne&&Re?ne.createHTML(d):d},s.setConfig=function(e){We(e),Ue=!0},s.clearConfig=function(){Ge=null,Ue=!1},s.isValidAttribute=function(e,t,n){Ge||We({});var i=w(e),r=w(t);return tt(i,r,n)},s.addHook=function(e,t){"function"==typeof t&&(ue[e]=ue[e]||[],y(ue[e],t))},s.removeHook=function(e){ue[e]&&b(ue[e])},s.removeHooks=function(e){ue[e]&&(ue[e]=[])},s.removeAllHooks=function(){ue={}},s}()})),pxt||(pxt={}),function(e){!function(t){const n={},i={};let r=!1;t.addDefaultProperties=function(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]}))},t.enable=function(){if(!e.aiTrackException||!e.aiTrackEvent||r)return;r=!0,e.debug("setting up app insights");const t=e.tickEvent;e.tickEvent=function(r,s,o){if(t&&t(r,s,o),(null==o?void 0:o.interactiveConsent)&&e.setInteractiveConsent(!0),s){const t=Object.assign({},n)||{},o=Object.assign({},i)||{};Object.keys(s).forEach((e=>{"string"==typeof s[e]?t[e]=s[e]:"number"==typeof s[e]?o[e]=s[e]:t[e]=JSON.stringify(s[e]||"")})),e.aiTrackEvent(r,t,o)}else e.aiTrackEvent(r)};const s=e.reportException;e.reportException=function(t,n){s&&s(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const o=e.reportError;e.reportError=function(t,n,i){o&&o(t,n,i);try{throw n}catch(r){const s={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(s,i),e.aiTrackException(r,"error",s)}}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,r=0,s=!1;function o(){return t||(t=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),t}function a(){t&&(i.gain.setTargetAtTime(0,t.currentTime,.015),r=0)}e.mute=function(e){t&&(s=e,a(),e&&n&&(n.disconnect(),i.disconnect(),n=void 0,i=void 0))},e.stop=a,e.frequency=function(){return r},e.tone=function(e){if(s)return;if(e<0)return;r=e;let a=o();if(a)try{n||(n=a.createOscillator(),n.type="triangle",i=a.createGain(),i.gain.value=0,i.connect(a.destination),n.connect(i),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),i.gain.setTargetAtTime(.2,t.currentTime,.015)}catch(e){return void(n=void 0)}}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxt||(pxt={})),function(e){!function(t){const n="auth",i="csrf-token",r="login-state",s="user-state";let o,a=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){return o};let l=0,c=0;t.AuthClient=class{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],e.Util.assert(!o),o=this}async initAsync(){try{this.state$=await e.storage.shared.getAsync(n,s)}catch(e){}this.state$||(this.state$={}),this.setUserProfileAsync(this.state$.profile),this.setUserPreferencesAsync(this.state$.preferences)}async loginAsync(t,i,s){var o;if(!h()||!function(e){return d().filter((t=>t.id===e)).length>0}(t))return;s=null!=s?s:u;const a=this.getState();a.profile||await this.authCheckAsync();if((null===(o=a.profile)||void 0===o?void 0:o.idp)===t)return void e.debug(`loginAsync: Already signed into ${t}.`);this.clearState();const l={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:s,callbackPathname:window.location.pathname,idp:t};await e.storage.shared.setAsync(n,r,l);const c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${l.key}`}),p=await this.apiAsync(c);p.success?(e.tickEvent("auth.login.start",{provider:t}),window.location.href=p.resp.loginUrl):await this.onSignInFailed()}async logoutAsync(t){if(!h())return;e.tickEvent("auth.logout"),await this.apiAsync("/api/auth/logout"),await e.storage.shared.delAsync(n,i),this.clearState();const r=t?t.startsWith("#")?t:`#${t}`:"";e.BrowserUtils.hasWindow()&&(window.location.href=`${window.location.origin}${window.location.pathname}${r}`,location.reload())}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const r=null===(t=this.getState().profile)||void 0===t?void 0:t.id,s=await this.apiAsync("/api/user",null,"DELETE");if(s.err)await this.onApiError(s.err);else try{await e.storage.shared.delAsync(n,i);try{await this.onProfileDeleted(r)}catch(t){e.tickEvent("auth.profile.cloudToLocalFailed")}this.clearState()}finally{e.tickEvent("auth.profile.deleted")}}async initialUserPreferencesAsync(){if(await this.loggedInAsync())return this.initialUserPreferences_||(this.initialUserPreferences_=this.fetchUserPreferencesAsync()),this.initialUserPreferences_}async userProfileAsync(){if(!await this.loggedInAsync())return;const e=this.getState();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=this.getState();return Object.assign({},e.preferences)}async authCheckAsync(){var t;if(!h())return;if(!await e.storage.shared.getAsync(n,i))return;const r=this.getState();return(null===(t=r.profile)||void 0===t?void 0:t.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(r.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return await this.authCheckAsync(),this.hasUserId()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=this.getState(),n=await this.apiAsync("/api/user/profile",{id:t.profile.id,username:e.username,avatarUrl:e.avatarUrl});return n.success&&await this.setUserProfileAsync(n.resp),n.success}async patchUserPreferencesAsync(t,n={}){const i=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(t=(t=Array.isArray(t)?t:[t]).filter((e=>!!e))).length)return await i();const r=(t,n,i)=>{const r=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(r,n);let s=ts.pxtc.jsonPatch.diff(t,r);return s.length&&i&&(s=s.filter(i)),s},s=await this.userPreferencesAsync(),o=r(s,t,n.filter);if(!o.length)return await i();if(ts.pxtc.jsonPatch.patchInPlace(s,o),await this.setUserPreferencesAsync(s),!await this.loggedInAsync())return await i();this.patchQueue.push({ops:t,filter:n.filter}),clearTimeout(l);const a=async()=>{if(c=0,!this.patchQueue.length)return await i();const t=await this.apiAsync("/api/user/preferences");if(!t.success)return e.reportError("identity","failed to fetch preferences for patch",t),{success:!1,res:void 0};const n=e.U.deepCopy(t.resp),s=this.patchQueue;this.patchQueue=[],s.forEach((e=>{const t=r(n,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(n,t)}));const o=pxtc.jsonPatch.diff(t.resp,n),a=await this.apiAsync("/api/user/preferences",o,"PATCH");return a.success?this.setUserPreferencesAsync(a.resp):e.reportError("identity","failed to patch preferences",a),{success:a.success,res:a.resp}};return n.immediate?await a():(c||(c=e.U.now()),1e4<e.U.now()-c?await a():(l=setTimeout(a,1e3),{success:!1,res:void 0}))}hasUserId(){var e;if(!h())return!1;return!!(null===(e=this.getState().profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!h())return;const t=this.getState();if(null===(e=t.profile)||void 0===e?void 0:e.id)return t.profile;const n=await this.apiAsync("/api/user/profile");if(n.success){const e=n.resp;return await this.setUserProfileAsync(e),e}}async setUserProfileAsync(e){const t=this.hasUserId();this.transformUserProfile(e);const n=this.hasUserId();this.onUserProfileChanged(),n&&!t?await this.onSignedIn():!n&&t&&await this.onSignedOut()}async setUserPreferencesAsync(e){var n;const i=null!==(n=this.getState().preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),r=ts.pxtc.jsonPatch.diff(i,e);this.transformUserPreferences(Object.assign(Object.assign({},i),e)),await this.onUserPreferencesChanged(r)}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;const e=this.getState(),t=await this.apiAsync("/api/user/preferences");return t.success&&t.resp?(this.setUserPreferencesAsync(t.resp),e.preferences):void 0}transformUserProfile(e){this.state$=Object.assign(Object.assign({},this.state$),{profile:Object.assign({},e)}),this.saveState()}transformUserPreferences(e){this.state$=Object.assign(Object.assign({},this.state$),{preferences:Object.assign({},e)}),this.saveState()}getState(){return this.state$}saveState(){e.storage.shared.setAsync(n,s,this.state$).then((()=>{}))}clearState(){this.state$={},e.storage.shared.delAsync(n,s).then((()=>this.onStateCleared()))}async apiAsync(t,r,s){var o;const a={},l=await e.storage.shared.getAsync(n,i);return l&&(a.authorization=`mkcd ${l}`),a["x-pxt-target"]=null===(o=e.appTarget)||void 0===o?void 0:o.id,t=e.BrowserUtils.isLocalHostDev()?`https://staging.pxt.io${t}`:t,e.Util.requestAsync({url:t,headers:a,data:r,method:s||(r?"POST":"GET"),withCredentials:!0}).then((e=>({statusCode:e.statusCode,resp:e.json,success:2===Math.floor(e.statusCode/100),err:null}))).catch((async e=>(/logout/.test(t)||401!=e.statusCode||await this.logoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1})))}};const u={hash:"",params:{}};function d(){var t,n;return Object.keys((null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.cloud)||void 0===n?void 0:n.cloudProviders)||{}).map((t=>e.appTarget.cloud.cloudProviders[t])).filter((e=>e.identity)).sort(((e,t)=>e.order-t.order))}function h(){return!a&&!e.BrowserUtils.isPxtElectron()&&d().length>0}function p(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let s,o=Object.assign({},u);do{if(s=await e.storage.shared.getAsync(n,r),!s)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,r);const a=t.state;if(!a||s.key!==a)return void e.debug("Failed to get auth state for key");o=Object.assign(Object.assign({},u),s.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:s.idp}),e.log(`Auth failed: ${l}:${n}`),o=Object.assign({},u);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}await e.storage.shared.setAsync(n,i,c),e.tickEvent("auth.login.success",{provider:s.idp})}while(0);const a=o.hash.startsWith("#")?o.hash:`#${o.hash}`,l=e.Util.stringifyQueryString("",o.params),c=`${s.callbackPathname.startsWith("/")?s.callbackPathname:`/${s.callbackPathname}`}${a}${l}`;window.location.href=c},t.identityProviders=d,t.identityProvider=function(e){return d().filter((t=>t.id===e)).shift()},t.hasIdentity=h,t.enableAuth=function(e=!0){a=!e},t.userName=function(e){var t,n,i,r;return null!==(r=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==r?r:"??"},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),r=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(r)}catch(e){}}},t.badgeEquals=p,t.hasBadge=function(e,t){return e.badges.some((e=>p(e,t)))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){!function(e){e.__dummy=42}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));var pxtc=ts.pxtc;!function(e){!function(e){!function(e){function t(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.flatClone=function(e){if(null==e)return null;let t={};return Object.keys(e).forEach((n=>{t[n]=e[n]})),t},e.clone=function(e){return null==e?null:JSON.parse(JSON.stringify(e))},e.htmlEscape=function(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,(e=>String.fromCharCode(Number(e.substr(2,e.length-3))))):e},e.jsStringQuote=t,e.jsStringLiteral=function(e){return'"'+t(e)+'"'},e.initials=function(e){if(/^\w+@/.test(e)){return e.match(/^\w\w/).shift().toUpperCase()}{const t=e.match(/\b\w/g)||[];return((t.shift()||"")+(t.pop()||"")).toUpperCase()}};let n="en",i={},r={},s=!1;function o(){return n}function a(e){const t=/^(\w{2})-(\w{2}$)/i.exec(e);return t&&t[1]&&t[2]?[`${t[1].toLowerCase()}-${t[2].toUpperCase()}`,t[1].toLowerCase(),`${t[1].toLowerCase()}-${t[2].toLowerCase()}`]:[(e||"en").toLowerCase()]}function l(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,i,r){let s=n[parseInt(i)],o="",a=/^:f(\d*)\.(\d+)/.exec(r);if(a){let e=parseInt(a[2]),t=parseInt(a[1])||0,n=/^0/.test(a[1])?"0":" ",i=s.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;o=i}else o=":x"==r?"0x"+s.toString(16):void 0===s?"(undef)":null===s?"(null)":s.toString?s.toString():s+"";return":a"==r?/^\s*[euioah]/.test(o.toLowerCase())?o="an "+o:/^\s*[bcdfgjklmnpqrstvwxz]/.test(o.toLowerCase())&&(o="a "+o):":s"==r?o=1==s?"":"s":":q"==r?o=e.htmlEscape(o):":jq"==r?o=e.jsStringQuote(o):":uri"==r?o=encodeURIComponent(o).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?o=encodeURI(o).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(o=(100*s).toFixed(1).toString()+"%"),o}))}e.enableLiveLocalizationUpdates=function(){s=!0},e.liveLocalizationEnabled=function(){return s},e.localeInfo=function(){return`${s?"live-":""}${o()}`},e.userLanguage=o,e.normalizeLanguageCode=a,e.setUserLanguage=function(e){n=a(e)[0]},e.isUserLanguageRtl=function(){return/^ar|dv|fa|ha|he|ks|ku|ps|ur|yi/i.test(n)},e.TRANSLATION_LOCALE="pxt",e.isTranslationMode=function(){return o()==e.TRANSLATION_LOCALE},e._localize=function(e){return i[e]||e},e.getLocalizedStrings=function(){return i},e.setLocalizedStrings=function(e){i=e},e.translationsCache=function(){return r},e.fmt_va=l,e.fmt=function(e,...t){return l(e,t)};const c={};e.dumpLocStats=function(){const e={};Object.keys(c).sort(((e,t)=>c[t]-c[e])).forEach((t=>e[t]=t)),console.log("prioritized list of strings:"),console.log(JSON.stringify(e,null,2))};function u(t,n){if(!t)return t;c[t]=(c[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),l(i,n)}e.lf_va=u,e.lf=function(e,...t){return u(e,t)},e.rlf=function(e,...t){return u(e,t)},e.lookup=function(e,t){return e.hasOwnProperty(t)?e[t]:null},e.isoTime=function(t){let n=new Date(1e3*t);return e.fmt("{0}-{1:f02.0}-{2:f02.0} {3:f02.0}:{4:f02.0}:{5:f02.0}",n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds())},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.deq=function e(t,n){if(t===n)return null;if(!t||!n)return"Null value";if("object"==typeof t&&"object"==typeof n){if(Array.isArray(t)){if(!Array.isArray(n))return"Expected array";if(t.length!=n.length)return"Expected array of length "+t.length+", got "+n.length;for(let i=0;i<t.length;i++)if(null!=e(t[i],n[i]))return"Expected array value "+t[i]+" got "+n[i];return null}let i=Object.keys(t),r=Object.keys(t);if(i.length!=r.length)return"Expected "+i.length+" keys, got "+r.length;for(let r=0;r<i.length;r++){if(!Object.prototype.hasOwnProperty.call(n,i[r]))return"Missing key "+i[r];if(null!=e(t[i[r]],n[i[r]]))return"Expected value of "+i[r]+" to be "+t[i[r]]+", got "+n[i[r]]}return null}return"Unable to compare "+t+", "+n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,ts,pxt,ts,pxtmelody,pxtmelody,pxtmelody,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(e){e.decodeBase64=function(e){return atob(e)},e.encodeBase64=function(e){return btoa(e)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function i(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function r(e){let t=[];for(let n=0;n<e.length;++n)i(t,e[n]);return t}function s(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function o(e,t,n,i,r){void 0===i&&(i=0),void 0===r&&(r=n.length-i);for(let s=0;s<r;++s)e[t+s]=n[i+s]}function a(e,t){return e==t?0:e<t?-1:1}n.CancellationToken=class{constructor(){this.pending=!1,this.cancelled=!1}startOperation(){this.pending=!0}isRunning(){return this.pending}onProgress(e){this.progressHandler=e}reportProgress(e,t){this.progressHandler&&this.progressHandler(e,t)}cancel(){this.cancelled=!0,this.pending=!1}cancelAsync(){return this.cancelled||!this.pending?(this.cancelled=!0,this.pending=!1,Promise.resolve()):(this.cancelled=!0,this.deferred=new Promise((e=>{this.resolve=e})),this.deferred)}isCancelled(){return this.cancelled}throwIfCancelled(){if(this.isCancelled())throw new Error}resolveCancel(){this.pending=!1,this.deferred&&(this.resolve(),this.deferred=void 0,this.resolve=void 0)}},n.codalHash16=function(e){const t=[251,175,119,215,81,14,79,191,103,49,181,143,186,157,0,232,31,32,55,60,152,58,17,237,174,70,160,144,220,90,57,223,59,3,18,140,111,166,203,196,134,243,124,95,222,179,197,65,180,48,36,15,107,46,233,130,165,30,123,161,209,23,97,16,40,91,219,61,100,10,210,109,250,127,22,138,29,108,244,67,207,9,178,204,74,98,126,249,167,116,34,77,193,200,121,5,20,113,71,35,128,13,182,94,25,226,227,199,75,27,41,245,230,224,43,225,177,26,155,150,212,142,218,115,241,73,88,105,39,114,62,255,192,201,145,214,168,158,221,148,154,122,12,84,82,163,44,139,228,236,205,242,217,11,187,146,159,64,86,239,195,42,106,198,118,112,184,172,87,2,173,117,176,229,247,253,137,185,99,164,102,147,45,66,231,52,141,211,194,206,246,238,56,110,78,248,63,240,189,93,92,51,53,183,19,171,72,50,33,104,101,69,8,252,83,120,76,135,85,54,202,125,188,213,96,235,136,208,162,129,190,132,156,38,47,1,7,254,24,4,216,131,89,21,28,133,37,153,149,80,170,68,6,169,234,151];function n(e){let n=0;for(let i=0;i<e.length;i++){let r=e[i];n=t[n^r]}return n}return e?function(e,t){let i;const r=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);r[t]=255&n}let s=0;for(let e=0;e<t;++e)i=n(r),s|=i<<8*e,r[0]=(r[0]+1)%255;return s}(e,2):0},n.bufferSerial=function(e,t="",n="?",i=255){for(let r=0;r<t.length;++r){const s=t[r];if(e[n]=(e[n]||"")+s,"\n"===s||e[n].length>i){let t=e[n];e[n]="",window.postMessage({type:"serial",id:n,data:t},"*")}}},n.blobReadAsDataURL=function(e){return e?new Promise(((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=e=>n(e),i.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(new Uint8Array(i.result)),i.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(i.result),i.readAsText(e)})):Promise.resolve(null)},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=((e,t)=>e===t)){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach((n=>t(n,e[n])))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach((i=>n[i]=t(i,e[i]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=i,n.concatArrayLike=function(e){return r(e)},n.concat=r,n.memcpy=o,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),i=0;for(let t of e)o(n,i,t),i+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,i){i&&Object.keys(i).forEach((r=>{s(t[r])&&s(i[r])?e(t[r],i[r]):t[r]=n.clone(i[r])}))},n.jsonCopyFrom=function(e,t){let i=n.clone(t);for(let n of Object.keys(t))e[n]=i[n]},n.jsonFlatten=function(e){let t={},i=(e,r)=>{if(null!==r&&"object"==typeof r){n.assert(!Array.isArray(r)),e&&(e+=".");for(let t of Object.keys(r))i(e+t,r[t])}else t[e]=r};return i("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let i=t,r=n.split(".");for(let t=0;t<r.length;++t){let s=r[t];t==r.length-1?i[s]=e[n]:("object"!=typeof i[s]&&(i[s]={}),i=i[s])}}return t},n.strcmp=a,n.stringMapEq=function(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!=i.length)return!1;for(let i of n){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i])return!1}return!0},n.endsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(-t.length)==t)},n.startsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(0,t.length)==t)},n.contains=function(e,t){return!(e.length<t.length)&&(0==t.length||e.indexOf(t)>-1)},n.replaceAll=function(e,t,n){return t?e.split(t).join(n):e},n.snakify=function(e){const t=e.toUpperCase(),n=e.toLowerCase();if(e==t||e==n)return e;if(e.lastIndexOf("_")>0)return e;const i=t=>e[t]!=n[t],r=n=>e[n]!=t[n];let s="",o=0;for(;o<e.length;){let t=i(o),n=o;for(;n<e.length;){if(t&&r(n)){if(n-o>2){n--;break}t=!1}if(!t&&i(n))break;n++}s&&(s+="_"),s+=e.slice(o,n),o=n}return s.toUpperCase()===s?s:s.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(a);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},n.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let r=t(e);i.hasOwnProperty(r)||(i[r]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let i=t(e);n.hasOwnProperty(i)||(n[i]=[]),n[i].push(e)})),n},n.toDictionary=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=e})),n},n.toSet=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=!0})),n},n.deepCopy=function e(t){if("object"!=typeof t||null===t)return t;const n=Array.isArray(t)?[]:{};for(const i in t){const r=t[i];n[i]=e(r)}return n},n.toArray=function(e){if(Array.isArray(e))return e;let t=[];if(!e)return t;for(let n=0;n<e.length;++n)t.push(e[n]);return t},n.indexOfMatching=function(e,t){for(let n=0;n<e.length;++n)if(t(e[n]))return n;return-1};const l=Promise.resolve();async function c(e,t,n){let i=0;const r=[],s=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,r=t[e];s[e]=await n(r)}})();r.push(e)}try{await Promise.all(r)}catch(e){throw i=t.length,e}return s}function u(e,t){const n={};return i=>{const r=e(i);return n.hasOwnProperty(r)?n[r]:n[r]=t(i)}}n.nextTick=function(e){l.then(e)},n.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},n.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},n.promiseMapAllSeries=function(e,t){return c(1,e,t)},n.promisePoolAsync=c,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let i,r;const s=new Promise(((t,s)=>{r=t,i=setTimeout((()=>{r=void 0,clearTimeout(i),s(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,s]).then((e=>(r&&(clearTimeout(i),r()),e)))},n.defer=function(){let e,t,n,i=!1;return{resolve:function(n){i?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),i=!0)},reject:function(t){i?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),i=!0)},promise:new Promise((function(i,r){e?i(e):(t=i,n=r)}))}},n.memoize=u,n.debounce=function(e,t,n){let i;return function(){let r=this,s=arguments,o=function(){i=null,n||e.apply(r,s)},a=n&&!i;return clearTimeout(i),i=setTimeout(o,t),a&&e.apply(r,s),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){return n.httpRequestCoreAsync(e).then((i=>{const r=i.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(r)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",i.statusCode,e.url,(i.text||"").slice(0,500)),r=new Error(t);return r.statusCode=i.statusCode,Promise.reject(r)}return i.text&&/application\/json/.test(i.headers["content-type"])&&(i.json=t.U.jsonTryParse(i.text)),i}))}function p(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let r=e.charCodeAt(i);if(r<=127)n+=e.charAt(i);else if(r<=2047)n+=String.fromCharCode(192|r>>6,128|63&r);else{if(!t&&55296<=r&&r<=56319){let t=e.charCodeAt(++i);isNaN(t)||(r=65536+(r-55296<<10)+(t-56320))}n+=r<=65535?String.fromCharCode(224|r>>12,128|r>>6&63,128|63&r):String.fromCharCode(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,i=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=i,this.lastPoke=0,this.recentGaps=[],this.wrapped=()=>{this.timeout=null,this.func()}}poke(){const e=Date.now();if(this.lastPoke){const t=e-this.lastPoke;if(t<10)return;for(t<4e3&&this.recentGaps.push(t);this.recentGaps.length>10;)this.recentGaps.shift()}this.lastPoke=e}trigger(){let e=this.maxDelay;if(this.lastPoke){const t=this.recentGaps.slice();t.sort();const n=t[t.length>>1]||1;e=Math.min(Math.max(n*this.slowdownFactor|0,this.minDelay),this.maxDelay);e-=Date.now()-this.lastPoke,e<0&&(e=0),this.lastPoke=null}clearTimeout(this.timeout),this.timeout=setTimeout(this.wrapped,e)}},n.throttle=function(e,t,n){let i;return function(){let r=this,s=arguments,o=function(){i=null,n||e.apply(r,s)},a=n&&!i;i||(i=setTimeout(o,t)),a&&e.apply(r,s)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[m()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,(function(e,t){return String.fromCharCode(parseInt(t,16))}))},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return h({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise(((n,i)=>{let r=this.promises[e];r||(r=this.promises[e]=[]),r.push((()=>t().finally((()=>{r.shift(),0==r.length?delete this.promises[e]:r[0]()})).then(n,i))),1==r.length&&r[0]()}))}};function f(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n,i){function r(r){pxt.debug(`downloading translations for ${e} ${t} ${n||""}`);let s=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",o=`${s}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;n&&(o+="&branch="+encodeURIComponent(n));const a={};return i&&!pxt.Cloud.useCdnApi()&&(a["If-None-Match"]=i),(s?h:pxt.Cloud.apiRequestWithCdnAsync)({url:o,headers:a}).then((s=>304==s.statusCode||200==s.statusCode?(i=s.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((o=>o.setAsync(e,t,n,i,s.json||r))).then((()=>s.json||r))):s.json),(e=>{console.log(`failed to load translations from ${o}`)}))}return pxt.BrowserUtils.translationDbAsync().then((i=>i.getAsync(e,t,n))).then((e=>{if(e){i=e.etag;return(Date.now()-e.time)/1e3>300&&r(e.strings),e.strings}return r()}))}function b(e){let[t,i]=n.normalizeLanguageCode(e),r=pxt.appTarget.appTheme;if(r&&r.availableLocales){if(r.availableLocales.indexOf(t)>-1)return!0;if(i&&r.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,r,s,o,a,l){if(l=l||y.Editor,"en-US"===(r=n.normalizeLanguageCode(r)[0])||"en"===r)return Promise.resolve(void 0);let c,u,d=`${r}/${a}/${l}`;if(n.translationsCache()[d])return Promise.resolve(n.translationsCache()[d]);switch(l){case y.Editor:c=[{branch:s,staticName:"strings.json",path:"strings.json"},{branch:o,staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:c=[{branch:o,staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:c=[{branch:o,staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:c=[{branch:o,staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function h(e){e&&(u||(u={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>u[t]=e[t])))}if(a){let a=0;return t.U.promiseMapAllSeries(c,(e=>g(r,e.path,e.branch).then(h,(e=>{console.log(e.message),++a})))).then((()=>(a&&(n.translationsCache()[d]=u),a!==c.length&&u?Promise.resolve(u):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,r,s,o,!1,l)))))}return Promise.all(c.map((e=>n.httpGetJsonAsync(`${i}locales/${r}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(u=t,n.translationsCache()[d]=u)}),(e=>{console.error("failed to load localizations")})).then((()=>u))}function w(e){const t={};for(const n of Object.keys(e))t[n]=x(e[n]);return t}function x(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(k),extendsTypes:e.extendsTypes?[...e.extendsTypes]:void 0,pkgs:e.pkgs?[...e.pkgs]:void 0,combinedProperties:e.combinedProperties?[...e.combinedProperties]:void 0,name:e.name,namespace:e.namespace,fileName:e.fileName,kind:e.kind,retType:e.retType,isInstance:e.isInstance,isContextual:e.isContextual,qName:e.qName,pkg:e.pkg,snippet:e.snippet,snippetName:e.snippetName,snippetWithMarkers:e.snippetWithMarkers,pySnippet:e.pySnippet,pySnippetName:e.pySnippetName,pySnippetWithMarkers:e.pySnippetWithMarkers,blockFields:e.blockFields,isReadOnly:e.isReadOnly,pyName:e.pyName,pyQName:e.pyQName,snippetAddsDefinitions:e.snippetAddsDefinitions}}function k(e){var n,i;return{name:e.name,description:e.description,type:e.type,pyTypeString:e.pyTypeString,initializer:e.initializer,default:e.default,properties:null===(n=e.properties)||void 0===n?void 0:n.map(A),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(A),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function A(e){return{name:e.name,type:e.type}}n.PromiseBuffer=class{constructor(){this.waiting=[],this.available=[]}drain(){for(let e of this.waiting)e(new Error("Promise Buffer Reset"));this.waiting=[],this.available=[]}pushError(e){this.push(e)}push(e){let t=this.waiting.shift();t?t(e):this.available.push(e)}shiftAsync(e=0){if(this.available.length>0){let e=this.available.shift();return e instanceof Error?Promise.reject(e):Promise.resolve(e)}return new Promise(((n,i)=>{let r=e=>{e instanceof Error?i(e):n(e)};this.waiting.push(r),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(r);e>=0&&(this.waiting.splice(e,1),i(new Error("Timeout")))}))}))}},n.now=f,n.nowSeconds=function(){return Math.round(f()/1e3)},n.timeout=function(e){return new Promise((t=>setTimeout((()=>t()),e)))},n.cpuUs=()=>{const e="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now;return n.cpuUs=()=>1e3*e(),n.cpuUs()},n.getMime=function(e){let t=/\.([a-zA-Z0-9]+)$/.exec(e);if(!t)return"application/octet-stream";switch(t[1].toLowerCase()){case"txt":return"text/plain";case"html":case"htm":return"text/html";case"css":return"text/css";case"js":return"application/javascript";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"ico":return"image/x-icon";case"manifest":return"text/cache-manifest";case"webmanifest":return"application/manifest+json";case"json":return"application/json";case"svg":return"image/svg+xml";case"eot":return"application/vnd.ms-fontobject";case"ttf":return"font/ttf";case"woff":return"application/font-woff";case"woff2":return"application/font-woff2";case"md":return"text/markdown";case"xml":return"application/xml";case"m4a":return"audio/m4a";case"mp3":return"audio/mp3";default:return"application/octet-stream"}},n.randomUint32=m,n.guidGen=function(){function e(){return(65536|m()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=g,n.pxtLangCookieId="PXT_LANG",n.langCookieExpirationDays=30,n.allLanguages={af:{englishName:"Afrikaans",localizedName:"Afrikaans"},ar:{englishName:"Arabic",localizedName:"العربية"},az:{englishName:"Azerbaijani",localizedName:"آذربایجان دیلی"},bg:{englishName:"Bulgarian",localizedName:"български"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},da:{englishName:"Danish",localizedName:"Dansk"},de:{englishName:"German",localizedName:"Deutsch"},el:{englishName:"Greek",localizedName:"Ελληνικά"},en:{englishName:"English",localizedName:"English"},"es-ES":{englishName:"Spanish (Spain)",localizedName:"Español (España)"},"es-MX":{englishName:"Spanish (Mexico)",localizedName:"Español (México)"},et:{englishName:"Estonian",localizedName:"Eesti"},eu:{englishName:"Basque",localizedName:"Euskara"},fa:{englishName:"Persian",localizedName:"فارسی"},fi:{englishName:"Finnish",localizedName:"Suomi"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"gu-IN":{englishName:"Gujarati",localizedName:"ગુજરાતી"},he:{englishName:"Hebrew",localizedName:"עברית"},hr:{englishName:"Croatian",localizedName:"Hrvatski"},hu:{englishName:"Hungarian",localizedName:"Magyar"},"hy-AM":{englishName:"Armenian (Armenia)",localizedName:"Հայերէն (Հայաստան)"},id:{englishName:"Indonesian",localizedName:"Bahasa Indonesia"},is:{englishName:"Icelandic",localizedName:"Íslenska"},it:{englishName:"Italian",localizedName:"Italiano"},ja:{englishName:"Japanese",localizedName:"日本語"},kab:{englishName:"Kabyle",localizedName:"شئعم"},ko:{englishName:"Korean",localizedName:"한국어"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},nl:{englishName:"Dutch",localizedName:"Nederlands"},no:{englishName:"Norwegian",localizedName:"Norsk"},nb:{englishName:"Norwegian Bokmal",localizedName:"Norsk bokmål"},"nn-NO":{englishName:"Norwegian Nynorsk",localizedName:"Norsk nynorsk"},"pa-IN":{englishName:"Punjabi",localizedName:"ਪੰਜਾਬੀ"},pl:{englishName:"Polish",localizedName:"Polski"},"pt-BR":{englishName:"Portuguese (Brazil)",localizedName:"Português (Brasil)"},"pt-PT":{englishName:"Portuguese (Portugal)",localizedName:"Português (Portugal)"},ro:{englishName:"Romanian",localizedName:"Română"},ru:{englishName:"Russian",localizedName:"Русский"},"si-LK":{englishName:"Sinhala (Sri Lanka)",localizedName:"සිංහල (ශ්රී ලංකා)"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sr:{englishName:"Serbian",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish (Sweden)",localizedName:"Svenska (Sverige)"},ta:{englishName:"Tamil",localizedName:"தமிழ்"},te:{englishName:"Telugu",localizedName:"తెలుగు"},th:{englishName:"Thai",localizedName:"ภาษาไทย"},tl:{englishName:"Tagalog",localizedName:"ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"},tr:{englishName:"Turkish",localizedName:"Türkçe"},uk:{englishName:"Ukrainian",localizedName:"Українська"},"ur-IN":{englishName:"Urdu (India)",localizedName:"اردو (ہندوستان)"},"ur-PK":{englishName:"Urdu (Pakistan)",localizedName:"اردو (پاکستان)"},vi:{englishName:"Vietnamese",localizedName:"Tiếng việt"},"zh-CN":{englishName:"Chinese (Simplified)",localizedName:"简体中文"},"zh-TW":{englishName:"Chinese (Traditional)",localizedName:"繁體中文"}},n.isLocaleEnabled=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:r,pxtBranch:s,targetBranch:o,force:a}=t;let{code:l}=t;if(l=n.normalizeLanguageCode(l)[0],"en-US"===l&&(l="en"),l===n.userLanguage()||!b(l)&&!a)return pxt.debug(`loc: ${l} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${l}`);const c=pxt.Util.liveLocalizationEnabled();return v(i,r,l,s,o,c,e.pxtc.Util.TranslationsKind.Editor).then((t=>(t&&(n.setUserLanguage(l),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,r,l,s,o,c,e.pxtc.Util.TranslationsKind.Apis).then((t=>{t&&(e.pxtc.apiLocalizationStrings=t)})))))},function(e){e[e.Editor=0]="Editor",e[e.Sim=1]="Sim",e[e.Apis=2]="Apis",e[e.SkillMap=3]="SkillMap"}(y=n.TranslationsKind||(n.TranslationsKind={})),n.downloadTranslationsAsync=v,n.capitalize=function(e){return e?e[0].toLocaleUpperCase()+e.slice(1):e},n.uncapitalize=function(e){return(e||"").split(/(?=[A-Z])/g).join(" ").toLowerCase()},n.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},i=null,r=null){const s="--------------------------0461489f461126c5";let o="";Object.keys(t).forEach((e=>function(e,t){o+=s+"\r\n",o+='Content-Disposition: form-data; name="'+e+'"\r\n\r\n',o+=t+"\r\n"}(e,t[e]))),i&&function(e,t){const n=e.split("/").reverse()[0];o+=s+"\r\n",o+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',o+="\r\n",o+=t+"\r\n"}(i,r),o+=s+"--\r\n";const a={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+s.slice(2)},data:o};return n.httpRequestCoreAsync(a)},n.toDataUri=function(e,n){return/^https?:/i.test(e)||/^data:/i.test(e)?e:(n||/^<svg/i.test(e)&&(n="image/svg+xml"),/xml|svg/.test(n)?`data:${n},${encodeURIComponent(e)}`:`data:${n||"image/png"};base64,${t.encodeBase64(p(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const i=n.imageHeaderSize+t.length,r=3*(e.width*e.height-1);let s=1;for(;s<4&&!(r*s>=8*i);)s++;let o=r*s>>3,a=i-o,l=0,c=e.width*e.height*4;if(a>0){const t=3*e.width;l=Math.ceil(a/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+l;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,l,0,0,0,0,0,0]);function d(e,t,n,i){let r=0,s=0,o=i[s++];const a=(1<<n)-1;let l=!0;for(;l;){let c=o>>r&a,u=8-r;if(u<=n){if(s>=i.length){if(0==u)break;l=!1}o=i[s++],c|=o<<u&a,r=n-u}else r+=n;e[t]=255&(e[t]&~a|c),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const h=e.getContext("2d"),p=h.getImageData(0,0,e.width,e.height);d(p.data,0,1,[s]);let f=4;if(f=d(p.data,f,s,u),pxt.Util.assert(0==(3&f)),0==l)f=d(p.data,f,s,t);else{let e=o-u.length;f=d(p.data,f,s,t.slice(0,e)),f=d(p.data,c,8,t.slice(e))}for(f|=3;f<p.data.length;)p.data[f]=255,f+=4;return h.putImageData(p,0,0),e},n.decodeBlobAsync=function(e){return pxt.BrowserUtils.loadCanvasAsync(e).then((e=>{const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data,i=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(i>5||0==i)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function r(e,n,i){let r=0,s=0,o=0;const a=(1<<n)-1;for(;s<i.length;)o|=(t[e++]&a)<<r,3==(3&e)&&e++,r+=n,r>=8&&(i[s++]=255&o,o>>=8,r-=8);return e}const s=new Uint8Array(pxt.Util.imageHeaderSize);let o=r(4,i,s);const a=pxt.HF2.decodeU32LE(s);if(a[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const l=new Uint8Array(a[1]),c=a[2];if(c>0){const t=(e.height-c)*e.width,n=new Uint8Array((3*(t-1)*i>>3)-pxt.Util.imageHeaderSize);r(o,i,n),l.set(n);const s=new Uint8Array(l.length-n.length);r(4*t,8,s),l.set(s,n.length)}else r(o,i,l);return l}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,i)=>(t[decodeURIComponent(n)]=decodeURIComponent(i),""))),t},n.stringifyQueryString=function(e,t){for(let n of Object.keys(t))e.indexOf("?")>=0?e+="&":e+="?",e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]);return e},n.cloneTargetBundle=function(e){const t=(e=Object.assign({},e)).apiInfo;delete e.apiInfo;const i=e.bundleddirs;delete e.bundleddirs;const r=e.bundledpkgs;delete e.bundledpkgs;const s=e.tutorialInfo;delete e.tutorialInfo;const o=n.clone(e);if(t){o.apiInfo={};for(const e of Object.keys(t)){const n=t[e].apis;o.apiInfo[e]={sha:t[e].sha,apis:{jres:Object.assign({},n.jres),byQName:w(n.byQName)}}}}if(i&&(o.bundleddirs=[...i]),r){o.bundledpkgs={};for(const e of Object.keys(r))o.bundledpkgs[e]=Object.assign({},r[e])}if(s){o.tutorialInfo={};for(const e of Object.keys(s)){const t=s[e];o.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks)}}}return o},n.cloneApis=w,n.cloneSymbolInfo=x,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)}}(t.Util||(t.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){e.Util.httpRequestCoreAsync=function(t){return new Promise(((n,i)=>{let r,s=!1,o=e.Util.clone(t.headers)||{};r=new XMLHttpRequest,t.responseArrayBuffer&&(r.responseType="arraybuffer"),t.withCredentials&&(r.withCredentials=!0),r.onreadystatechange=()=>{if(!s&&4==r.readyState){s=!0;let e={statusCode:r.status,headers:{},buffer:r.responseBody||r.response,text:t.responseArrayBuffer?void 0:r.responseText};r.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let a,l=t.data,c=t.method||(null==l?"GET":"POST");null==l?a=null:l instanceof Uint8Array?a=l:"object"==typeof l?(a=JSON.stringify(l),o["content-type"]="application/json; charset=utf8"):"string"==typeof l?a=l:e.Util.oops("bad data"),r.open(c,t.url),Object.keys(o).forEach((e=>{r.setRequestHeader(e,o[e])})),null==a?r.send():r.send(a)}))},e.Util.sha256=o,e.Util.getRandomBuf=e=>{if(window.crypto)window.crypto.getRandomValues(e);else for(let t=0;t<e.length;++t)e[t]=Math.floor(255*Math.random())};const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,t){return e>>>t|e<<32-t}function r(t,r){e.Util.assert(8==t.length),e.Util.assert(64==r.length);for(let e=16;e<64;++e){let t=i(r[e-15],7)^i(r[e-15],18)^r[e-15]>>>3,n=i(r[e-2],17)^i(r[e-2],19)^r[e-2]>>>10;r[e]=r[e-16]+t+r[e-7]+n|0}let s=t[0],o=t[1],a=t[2],l=t[3],c=t[4],u=t[5],d=t[6],h=t[7];for(let e=0;e<64;++e){let t=h+(i(c,6)^i(c,11)^i(c,25))+(c&u^~c&d)+n[e]+r[e]|0,p=s&o^s&a^o&a;h=d,d=u,u=c,c=l+t|0,l=a,a=o,o=s,s=t+((i(s,2)^i(s,13)^i(s,22))+p|0)|0}t[0]+=s,t[1]+=o,t[2]+=a,t[3]+=l,t[4]+=c,t[5]+=u,t[6]+=d,t[7]+=h}function s(e){let t=new Uint32Array(8);t[0]=1779033703,t[1]=3144134277,t[2]=1013904242,t[3]=2773480762,t[4]=1359893119,t[5]=2600822924,t[6]=528734635,t[7]=1541459225;let n=new Uint32Array(64);function i(e){let i=e.length-63;for(let s=0;s<i;s+=64){for(let t=0;t<16;t++){let i=(t<<2)+s;n[t]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}r(t,n)}}i(e);let s=64-(e.length+9)%64;64==s&&(s=0);let o=e.length-e.length%64,a=new Uint8Array(e.length-o+1+s+8),l=0;for(;o<e.length;)a[l++]=e[o++];for(a[l++]=128;s-- >0;)a[l++]=0;let c=8*e.length;for(l=a.length;c>0;)a[--l]=255&c,c>>=8;i(a);let u="";for(let e=0;e<t.length;++e)u+=("000000000"+t[e].toString(16)).slice(-8);return u.toLowerCase()}function o(t){pxt.perf.measureStart("sha256buffer");const n=s(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=s,t.sha256string=o}(e.BrowserImpl||(e.BrowserImpl={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={add:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");if(t in e)throw new Error(`jsonPatch: object already contains key ${t}`);e[t]=n},replace:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");e[t]=n},remove:(e,t)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");delete e[t]}},i={add:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");if(t in e)throw new Error(`jsonPatch: key ${t} already exists in array`);"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,0,n)},replace:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,1,n)},remove:(e,t)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?delete e[t]:e.splice(t,1)}};t.diff=function(e,t){const n={add:[],remove:[],replace:[]};function i(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,r,s){if(!Object.is(t,r)){r=r||{},t=t||{};for(let e of Object.keys(t))if(!(e in r)){const r=i(t,e);n.remove.push({op:"remove",path:s.concat(r)})}for(const o of Object.keys(r)){const a=t[o],l=r[o],c=i(r,o);c in t?"object"!=typeof a&&"object"!=typeof l&&a!==l||typeof a!=typeof l||Array.isArray(a)!==Array.isArray(l)?n.replace.push({op:"replace",path:s.concat(c),value:l}):e(a,l,s.concat(c)):void 0!==r[c]&&(s.length&&n.add.push({op:"add",path:s,value:Array.isArray(r)?[]:{}}),n.add.push({op:"add",path:s.concat(c),value:l}))}}}(e,t,[]),[...n.remove.reverse(),...n.replace,...n.add.sort(((e,t)=>e.path.length-t.path.length))]},t.patchInPlace=function(e,t){if(!e||"object"!=typeof e)throw new Error("jsonPatch: Must be an object or an array.");for(const r of t){const t=r.path.slice(),s=t.pop();if(null==s)throw new Error("jsonPatch: missing last key");let o=e,a=t.shift();for(;null!=a;){if(!(a in o))throw new Error(`jsonPatch: missing parent element ${a}`);o=o[a],a=t.shift()}if(Array.isArray(o)&&"number"!=typeof s)throw new Error("jsonPatch: expected numeric index for array object");const l=Array.isArray(o)?i:n;"remove"===r.op?l.remove(o,s):"add"!==r.op||s in o?"replace"===r.op&&l.replace(o,s,r.value):l.add(o,s,r.value)}},t.opsAreEqual=function(t,n){return t.op===n.op&&e.U.arrayEquals(t.path,n.path)}}(e.jsonPatch||(e.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(t){!function(t){function n(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){const i=Array.isArray(e),r=Array.isArray(t);if(i&&r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(!n(e[i],t[i]))return!1;return!0}if(i!==r)return!1;const s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(const i of s){if(!t.hasOwnProperty(i))return!1;if(!n(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}t.diffTests=function(){const t=[{comment:"test 1",obja:{a:4,b:5},objb:{a:3,b:5},expected:[{op:"replace",path:["a"],value:3}]},{comment:"test 2",obja:{a:3,b:5},objb:{a:4,c:5},expected:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}]},{comment:"test 3",obja:{a:4,b:[1,2,3]},objb:{a:3,b:[1,2,4]},expected:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4}]},{comment:"test 4",obja:{a:3,b:[1,2,4]},objb:{a:3,b:[1,2,4,5]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",3],value:5}]},{comment:"test 5",obja:{a:4,b:{c:3}},objb:{a:4,b:{c:4}},expected:[{op:"replace",path:["b","c"],value:4}]},{comment:"test 6",obja:{a:4,b:{c:4}},objb:{a:5,b:{d:4}},expected:[{op:"remove",path:["b","c"]},{op:"replace",path:["a"],value:5},{op:"add",path:["b"],value:{}},{op:"add",path:["b","d"],value:4}]},{comment:"test 7",obja:{a:4,b:[2,"foo"]},objb:{a:4,b:[2,"foo",["this","that"]]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",2],value:["this","that"]}]}];for(const i of t){console.log(i.comment);const t=e.pxtc.jsonPatch.diff(i.obja,i.objb);n(t,i.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",i.expected))}},t.patchTests=function(){const t=[{comment:"test 1",obj:{a:"foo",b:[4,11]},patches:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}],expected:{a:4,c:5}},{comment:"test 2",obj:{a:4,b:[1,2,3]},patches:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4},{op:"add",path:["b",3],value:9}],expected:{a:3,b:[1,2,4,9]}},{comment:"test 3",obj:{a:4,b:{c:3}},patches:[{op:"replace",path:["a"],value:5},{op:"remove",path:["b","c"]},{op:"add",path:["b","d"],value:4}],expected:{a:5,b:{d:4}}},{comment:"test 4",obj:{a:4},patches:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",0],value:"foo"},{op:"add",path:["b",1],value:"bar"}],expected:{a:4,b:["foo","bar"]},validate:e=>e.b&&e.b.forEach}];for(const i of t){console.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches);!n(i.obj,i.expected)||!i.validate||i.validate(i.obj)?console.log("succeeded"):i.expected&&(console.error("FAILED"),console.log("got",i.obj),console.log("exp",i.expected))}}}(t.tests||(t.tests={}))}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.report||(pxt.perf.report=()=>{}),pxt.perf.recordMilestone||(pxt.perf.recordMilestone=()=>{}),pxt.perf.measureStart||(pxt.perf.measureStart=()=>{}),pxt.perf.measureEnd||(pxt.perf.measureEnd=()=>{}),function(e){let t;e.U=pxtc.Util,e.Util=pxtc.Util;let n,i,r,s={};function o(n,i){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(s[n]=i,e.U.jsonCopyFrom(e.appTarget.compile.switches,s),e.U.jsonCopyFrom(t.compile.switches,s))}function a(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,s),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex");const i=e.appTarget.appTheme;i&&Object.keys(i).filter((e=>/(logo|hero)$/i.test(e)&&/^@cdnUrl@/.test(i[e]))).forEach((t=>i[t]=e.BrowserUtils.patchCdn(i[t])));const r=e.appTarget.simulator;if(r&&r.boardDefinition&&r.boardDefinition.visual){let t=r.boardDefinition.visual;t.image&&(t.image=e.BrowserUtils.patchCdn(t.image),t.outlineImage&&(t.outlineImage=e.BrowserUtils.patchCdn(t.outlineImage)))}if(Object.keys(e.appTarget.bundledpkgs).forEach((t=>{const n=e.appTarget.bundledpkgs[t],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)})),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach((i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function l(n=!1){e.perf.measureStart("reloadAppTargetVariant");const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}a(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function c(){return{relprefix:"/--",workerjs:"/worker.js",monacoworkerjs:"/monacoworker.js",gifworkerjs:"/gifjs/gif.worker.js",serviceworkerjs:"/serviceworker.js",typeScriptWorkerJs:"/tsworker.js",pxtVersion:"local",pxtRelId:"localRelId",pxtCdnUrl:"/cdn/",commitCdnUrl:"/cdn/",blobCdnUrl:"/blb/",cdnUrl:"/cdn/",targetUrl:"",targetVersion:"local",targetRelId:"",targetId:e.appTarget?e.appTarget.id:"",simUrl:"/sim/simulator.html",simserviceworkerUrl:"/simulatorserviceworker.js",simworkerconfigUrl:"/sim/workerConfig.js",partsUrl:"/sim/siminstructions.html"}}function u(){return r||(r=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),r}function d(t=null){return t||(t=e.appTarget.compile),t.nativeType==ts.pxtc.NATIVE_TYPE_VM?t.useESP?t.useUF2?ts.pxtc.BINARY_UF2:ts.pxtc.BINARY_ESP:ts.pxtc.BINARY_PXT64:t.useUF2&&!t.switches.rawELF?ts.pxtc.BINARY_UF2:t.useELF?ts.pxtc.BINARY_ELF:ts.pxtc.BINARY_HEX}e.setAppTarget=function(n){e.appTarget=n||{},a(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),r=t.pyQName,s=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:r,pyName:r?r.slice(r.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map((e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters}))):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},o=s.attributes;o.paramDefl||(o.paramDefl={}),o.callingConvention||(o.callingConvention=0),o.paramHelp||(o.paramHelp={}),o.jsDoc||(o.jsDoc=""),o._name=s.name.replace(/@.*/,"")}}n=e},e.getBundledApiInfo=function(){return n},e.savedAppTheme=function(){return t?t.appTheme:void 0},e.setCompileSwitch=o,e.setCompileSwitches=function(e){if(e)for(let t of e.split(/[\s,;:]+/))t&&("-"==t[0]?o(t.slice(1),!1):o(t,!0))},e.bundledSvg=function(t){if(!t)return;let n=i&&i[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;i||(i={});const r=e.appTarget.bundledpkgs[t];if(!r)return;if(JSON.parse(r["pxt.json"]).core&&r["board.json"]){const n=JSON.parse(r["board.json"]);if(n&&n.visual&&n.visual.image){let s=n.visual.image;/^pkg:\/\//.test(s)&&(s=r[s.slice(6)]),i[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(s))}`}}return i[t]},e.reloadAppTargetVariant=l,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,l(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some((e=>/^hw---/.test(e)))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter((e=>/^hw---/.test(e))).map((t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME]))).filter((t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw)):[]},e.options={},e.debug="undefined"!=typeof console&&console.debug?t=>{e.options.debug&&console.debug(t)}:()=>{},e.log="undefined"!=typeof console&&console.log?e=>{console.log(e)}:()=>{},e.reportException=function(e,t){if(console&&(console.error(e),t))try{console.log(t)}catch(e){}},e.reportError=function(t,n,i){if(console&&(console.error(`${t}: ${n}`),i))try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=c,e.getOnlineCdnUrl=function(){if(!e.webConfig)return null;let t=/^(https:\/\/[^\/]+)/.exec(e.webConfig.commitCdnUrl);return t?t[1]:null},e.setupWebConfig=function(t){t?e.webConfig=t:e.webConfig||(e.webConfig=c())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=u,e.packagesConfigAsync=function(){return u().then((e=>e?e.packages:void 0))},e.CONFIG_NAME="pxt.json",e.SIMSTATE_JSON=".simstate.json",e.SERIAL_EDITOR_FILE="serial.txt",e.README_FILE="README.md",e.GITIGNORE_FILE=".gitignore",e.ASSETS_FILE="assets.json",e.CLOUD_ID="pxt/",e.BLOCKS_PROJECT_NAME="blocksprj",e.JAVASCRIPT_PROJECT_NAME="tsprj",e.PYTHON_PROJECT_NAME="pyprj",e.MAIN_BLOCKS="main.blocks",e.MAIN_TS="main.ts",e.MAIN_PY="main.py",e.DEFAULT_GROUP_NAME="other",e.TILEMAP_CODE="tilemap.g.ts",e.TILEMAP_JRES="tilemap.g.jres",e.IMAGES_CODE="images.g.ts",e.IMAGES_JRES="images.g.jres",e.TUTORIAL_CODE_START="_onCodeStart.ts",e.TUTORIAL_CODE_STOP="_onCodeStop.ts",e.TUTORIAL_INFO_FILE="tutorial-info-cache.json",e.TUTORIAL_CUSTOM_TS="tutorial.custom.ts",e.BREAKPOINT_TABLET=991,e.outputName=d,e.isOutputText=function(e=null){return d(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let i;function r(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.lf("while %1"),appendField:e.Util.lf("{id:while}do")}},pxt_controls_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},controls_simple_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},pxt_controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},math_op2:{name:e.Util.lf("minimum or maximum of 2 numbers"),tooltip:{min:e.Util.lf("smaller value of 2 numbers"),max:e.Util.lf("larger value of 2 numbers")},url:"/blocks/math",operators:{op:["min","max"]},category:"math"},math_op3:{name:e.Util.lf("absolute number"),tooltip:e.Util.lf("absolute value of a number"),url:"/reference/math",category:"math",block:{message0:e.Util.lf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.appTarget&&e.appTarget.compile?e.Util.lf("a decimal number"):e.Util.lf("an integer number")},math_integer:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math"},math_arithmetic:{name:e.Util.lf("arithmetic operation"),url:"/blocks/math",tooltip:{ADD:e.Util.lf("Return the sum of the two numbers."),MINUS:e.Util.lf("Return the difference of the two numbers."),MULTIPLY:e.Util.lf("Return the product of the two numbers."),DIVIDE:e.Util.lf("Return the quotient of the two numbers."),POWER:e.Util.lf("Return the first number raised to the power of the second number.")},operators:{OP:["ADD","MINUS","MULTIPLY","DIVIDE","POWER"]},category:"math",block:{MATH_ADDITION_SYMBOL:e.Util.lf("{id:op}+"),MATH_SUBTRACTION_SYMBOL:e.Util.lf("{id:op}-"),MATH_MULTIPLICATION_SYMBOL:e.Util.lf("{id:op}×"),MATH_DIVISION_SYMBOL:e.Util.lf("{id:op}÷"),MATH_POWER_SYMBOL:e.Util.lf("{id:op}**")}},math_modulo:{name:e.Util.lf("division remainder"),tooltip:e.Util.lf("Return the remainder from dividing the two numbers."),url:"/blocks/math",category:"math",block:{MATH_MODULO_TITLE:e.Util.lf("remainder of %1 ÷ %2")}},math_js_op:{name:e.Util.lf("math function"),tooltip:{sqrt:e.Util.lf("Returns the square root of the argument"),sin:e.Util.lf("Returns the sine of the argument"),cos:e.Util.lf("Returns the cosine of the argument"),tan:e.Util.lf("Returns the tangent of the argument"),atan2:e.Util.lf("Returns the arctangent of the quotient of the two arguments"),idiv:e.Util.lf("Returns the integer portion of the division operation on the two arguments"),imul:e.Util.lf("Returns the integer portion of the multiplication operation on the two arguments")},url:"/blocks/math",operators:{OP:["sqrt","sin","cos","tan","atan2","idiv","imul"]},category:"math",block:{sqrt:e.Util.lf("{id:op}square root"),sin:e.Util.lf("{id:op}sin"),cos:e.Util.lf("{id:op}cos"),tan:e.Util.lf("{id:op}tan"),atan2:e.Util.lf("{id:op}atan2"),idiv:e.Util.lf("{id:op}integer ÷"),imul:e.Util.lf("{id:op}integer ×")}},math_js_round:{name:e.Util.lf("rounding functions"),tooltip:{round:e.Util.lf("Increases the argument to the next higher whole number if its fractional part is more than one half"),ceil:e.Util.lf("Increases the argument to the next higher whole number"),floor:e.Util.lf("Decreases the argument to the next lower whole number"),trunc:e.Util.lf("Removes the fractional part of the argument")},url:"/blocks/math",operators:{OP:["round","ceil","floor","trunc"]},category:"math",block:{round:e.Util.lf("{id:op}round"),ceil:e.Util.lf("{id:op}ceiling"),floor:e.Util.lf("{id:op}floor"),trunc:e.Util.lf("{id:op}truncate")}},variables_change:{name:e.Util.lf("update the value of a number variable"),tooltip:e.Util.lf("Changes the value of the variable by this amount"),url:"/blocks/variables/change",category:"variables",block:{message0:e.Util.lf("change %1 by %2")}},controls_repeat_ext:{name:e.Util.lf("a loop that repeats and increments an index"),tooltip:e.Util.lf("Do some statements several times."),url:"/blocks/loops/repeat",category:"loops",block:{CONTROLS_REPEAT_TITLE:e.Util.lf("repeat %1 times"),CONTROLS_REPEAT_INPUT_DO:e.Util.lf("{id:repeat}do")}},variables_get:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_get_reporter:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_set:{name:e.Util.lf("assign the value of a variable"),tooltip:e.Util.lf("Sets this variable to be equal to the input."),url:"/blocks/variables/assign",category:"variables",block:{VARIABLES_SET:e.Util.lf("set %1 to %2")}},controls_if:{name:e.Util.lf("a conditional statement"),tooltip:{CONTROLS_IF_TOOLTIP_1:e.Util.lf("If a value is true, then do some statements."),CONTROLS_IF_TOOLTIP_2:e.Util.lf("If a value is true, then do the first block of statements. Otherwise, do the second block of statements."),CONTROLS_IF_TOOLTIP_3:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."),CONTROLS_IF_TOOLTIP_4:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.")},tooltipSearch:"CONTROLS_IF_TOOLTIP_2",url:"/blocks/logic/if",category:"logic",block:{CONTROLS_IF_MSG_IF:e.Util.lf("{id:logic}if"),CONTROLS_IF_MSG_THEN:e.Util.lf("{id:logic}then"),CONTROLS_IF_MSG_ELSE:e.Util.lf("{id:logic}else"),CONTROLS_IF_MSG_ELSEIF:e.Util.lf("{id:logic}else if")}},lists_create_with:{name:e.Util.lf("create an array"),tooltip:e.Util.lf("Creates a new array."),url:"/reference/arrays/create",category:"arrays",blockTextSearch:"LISTS_CREATE_WITH_INPUT_WITH",block:{LISTS_CREATE_EMPTY_TITLE:e.Util.lf("empty array"),LISTS_CREATE_WITH_INPUT_WITH:e.Util.lf("array of"),LISTS_CREATE_WITH_CONTAINER_TITLE_ADD:e.Util.lf("array"),LISTS_CREATE_WITH_ITEM_TITLE:e.Util.lf("value")}},lists_length:{name:e.Util.lf("array length"),tooltip:e.Util.lf("Returns the number of items in an array."),url:"/reference/arrays/length",category:"arrays",block:{LISTS_LENGTH_TITLE:e.Util.lf("length of array %1")}},lists_index_get:{name:e.Util.lf("get a value in an array"),tooltip:e.Util.lf("Returns the value at the given index in an array."),url:"/reference/arrays/get",category:"arrays",block:{message0:e.Util.lf("%1 get value at %2")}},lists_index_set:{name:e.Util.lf("set a value in an array"),tooltip:e.Util.lf("Sets the value at the given index in an array"),url:"/reference/arrays/set",category:"arrays",block:{message0:e.Util.lf("%1 set value at %2 to %3")}},logic_compare:{name:e.Util.lf("comparing two numbers"),tooltip:{LOGIC_COMPARE_TOOLTIP_EQ:e.Util.lf("Return true if both inputs equal each other."),LOGIC_COMPARE_TOOLTIP_NEQ:e.Util.lf("Return true if both inputs are not equal to each other."),LOGIC_COMPARE_TOOLTIP_LT:e.Util.lf("Return true if the first input is smaller than the second input."),LOGIC_COMPARE_TOOLTIP_LTE:e.Util.lf("Return true if the first input is smaller than or equal to the second input."),LOGIC_COMPARE_TOOLTIP_GT:e.Util.lf("Return true if the first input is greater than the second input."),LOGIC_COMPARE_TOOLTIP_GTE:e.Util.lf("Return true if the first input is greater than or equal to the second input.")},url:"/blocks/logic/boolean",category:"logic",block:{search:"= ≠ < ≤ > ≥"}},logic_operation:{name:e.Util.lf("boolean operation"),tooltip:{LOGIC_OPERATION_TOOLTIP_AND:e.Util.lf("Return true if both inputs are true."),LOGIC_OPERATION_TOOLTIP_OR:e.Util.lf("Return true if at least one of the inputs is true.")},url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_OPERATION_AND:e.Util.lf("{id:op}and"),LOGIC_OPERATION_OR:e.Util.lf("{id:op}or")}},logic_negate:{name:e.Util.lf("logical negation"),tooltip:e.Util.lf("Returns true if the input is false. Returns false if the input is true."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_NEGATE_TITLE:e.Util.lf("not %1")}},logic_boolean:{name:e.Util.lf("a `true` or `false` value"),tooltip:e.Util.lf("Returns either true or false."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_BOOLEAN_TRUE:e.Util.lf("{id:boolean}true"),LOGIC_BOOLEAN_FALSE:e.Util.lf("{id:boolean}false")}},text:{name:e.Util.lf("a piece of text"),tooltip:e.Util.lf("A letter, word, or line of text."),url:"types/string",category:"text",block:{search:e.Util.lf("a piece of text")}},text_length:{name:e.Util.lf("number of characters in the string"),tooltip:e.Util.lf("Returns the number of letters (including spaces) in the provided text."),url:"reference/text/length",category:"text",block:{TEXT_LENGTH_TITLE:e.Util.lf("length of %1")}},text_join:{name:e.Util.lf("join items to create text"),tooltip:e.Util.lf("Create a piece of text by joining together any number of items."),url:"reference/text/join",category:"text",block:{TEXT_JOIN_TITLE_CREATEWITH:e.Util.lf("join")}},procedures_defnoreturn:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"types/function/define",category:"functions",block:{PROCEDURES_DEFNORETURN_TITLE:e.Util.lf("function"),PROCEDURE_ALREADY_EXISTS:e.Util.lf("A function named '%1' already exists.")}},procedures_callnoreturn:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"types/function/call",category:"functions",block:{PROCEDURES_CALLNORETURN_TITLE:e.Util.lf("call function")}},function_return:{name:e.Util.lf("return a value from within a function"),tooltip:e.Util.lf("Return a value from within a user-defined function."),url:"types/function/return",category:"functions",block:{message_with_value:e.Util.lf("return %1"),message_no_value:e.Util.lf("return")}},function_definition:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"types/function/define",category:"functions",block:{FUNCTIONS_EDIT_OPTION:e.Util.lf("Edit Function")}},function_call:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"types/function/call",category:"functions",block:{FUNCTIONS_CALL_TITLE:e.Util.lf("call"),FUNCTIONS_GO_TO_DEFINITION_OPTION:e.Util.lf("Go to Definition")}},function_call_output:{name:e.Util.lf("call the function with a return value"),tooltip:e.Util.lf("Call the user-defined function with a return value."),url:"types/function/call",category:"functions",block:{}}},i[pxtc.ON_START_TYPE]={name:e.Util.lf("on start event"),tooltip:e.Util.lf("Run code when the program starts"),url:"/blocks/on-start",category:"loops",block:{message0:e.Util.lf("on start %1 %2")}},i[pxtc.PAUSE_UNTIL_TYPE]={name:e.Util.lf("pause until"),tooltip:e.Util.lf("Pause execution of code until the given boolean expression is true"),url:"/blocks/pause-until",category:"loops",block:{message0:e.Util.lf("pause until %1")}},i[pxtc.TS_BREAK_TYPE]={name:e.Util.lf("break"),tooltip:e.Util.lf("Break out of the current loop or switch"),url:"/blocks/loops/break",category:"loops",block:{message0:e.Util.lf("break")}},i[pxtc.TS_CONTINUE_TYPE]={name:e.Util.lf("continue"),tooltip:e.Util.lf("Skip current iteration and continues with the next iteration in the loop"),url:"/blocks/loops/continue",category:"loops",block:{message0:e.Util.lf("continue")}},e.Util.isTranslationMode()){const t=Blockly.Msg;e.Util.values(i).filter((e=>e.block)).forEach((n=>{const i=Object.keys(n.block);n.translationIds=e.Util.values(n.block),i.forEach((i=>e.crowdin.inContextLoadAsync(n.block[i]).then((e=>{n.block[i]=e,/^[A-Z_]+$/.test(i)&&(t[i]=e)}))))}))}}t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan"],binary:["atan2"],infix:["idiv","imul"]},t.ROUNDING_FUNCTIONS=["round","ceil","floor","trunc"],t.builtinFunctionInfo={"Math.abs":{blockId:"math_op3",params:["x"]},"Math.min":{blockId:"math_op2",params:["x","y"]},"Math.max":{blockId:"math_op2",params:["x","y"]}},t.normalizeBlock=function(t,n=e.log){if(!t)return t;let i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){const i={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},r=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,s=!!e.attributes._def,o=s?e.attributes._def.parameters.slice(0):void 0,a=s?o.length:e.parameters?e.parameters.length:0,l=t.builtinFunctionInfo[e.qName];s&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const c={},u=o?o.filter((e=>!e.ref||(c[e.name]=e,!1))):[];if(r&&s&&o.length){const t=c.this||o[0],r=t.name;let s;(!t.shadowBlockId||"variables_get"===t.shadowBlockId)&&(s=t.varName||e.attributes.paramDefl[r]||e.attributes.paramDefl.this),i.thisParameter={actualName:n,definitionName:r,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:s,fieldEditor:d(r,n),fieldOptions:h(r,n),shadowOptions:p(r,n)}}if(e.parameters){let t=r&&!c.this?1:0;e.parameters.forEach(((e,n)=>{let r;if(c[e.name]?r=c[e.name]:t<u.length&&(r=u[t],++t),r||!s){let n;e.options&&e.options.min&&e.options.max&&(n={min:e.options.min.value,max:e.options.max.value});const s=r?r.name:l?l.params[t++]:e.name,c=r&&("variables_get"===r.shadowBlockId||"lists_create_with"==r.shadowBlockId);i.parameters.push({actualName:e.name,type:e.type,defaultValue:c&&r.varName||e.default,definitionName:s,shadowBlockId:r&&r.shadowBlockId,isOptional:!!o&&o.indexOf(r)>=a,fieldEditor:d(s,e.name),fieldOptions:h(s,e.name),shadowOptions:p(s,e.name),range:n})}e.handlerParameters&&e.handlerParameters.forEach((e=>{i.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!o&&o.some((t=>t.ref&&t.name===e.name))})}))}))}return i.parameters.forEach((e=>{i.actualNameToParam[e.actualName]=e,i.definitionNameToParam[e.definitionName]=e})),i;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function h(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function p(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some((e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)}))},t.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),t},t.defaultIconForArgType=function(e=""){switch(e){case"number":return"calculator";case"string":return"text width";case"boolean":return"random";case"Array":return"list";default:return"align justify"}},t.parseFields=function(e){return e.split("|").map(((e,t)=>{let n=/([^%]*)\s*%([a-zA-Z0-9_]+)/.exec(e);if(!n)return{n:e,ni:t};let i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}}))},t.blockDefinitions=function(){return i||r(),i},t.getBlockDefinition=function(e){return i||r(),i[e]}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function i(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function r(){return n()&&/mobi/i.test(navigator.userAgent)}function s(){return n()&&/Mac/i.test(navigator.platform)}function o(){return!!navigator&&/Linux/i.test(navigator.platform)}function a(){return n()&&/arm/i.test(navigator.platform)}function l(){return n()&&/Edge/i.test(navigator.userAgent)}function c(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!l()&&!c()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!l()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function h(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function p(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function f(){return n()&&/Midori/i.test(navigator.userAgent)}function m(){return n()&&/Epiphany/i.test(navigator.userAgent)}function g(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&(t||!/nolocalhost=1/.test(window.location.href))&&!(null===(n=null==e?void 0:e.webConfig)||void 0===n?void 0:n.isStatic)}catch(e){return!1}}function x(){return"undefined"!=typeof window&&!!window.PointerEvent}function k(){return i()?"windows":s()?"mac":o()&&a()?"rpi":o()?"linux":"unknown"}function A(){return l()?"edge":m()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function T(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=r,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=s,t.isLinux=o,t.isARM=a,t.isUwpEdge=function(){return"undefined"!=typeof window&&!!window.Windows},t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>!1,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)Map=1/.test(window.location.href)}catch(e){return!1}},t.isTabletSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)<e.BREAKPOINT_TABLET},t.isComputerSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)>=e.BREAKPOINT_TABLET},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=x,t.hasSaveAs=function(){return l()||c()||h()},t.os=k,t.browser=A,t.browserVersion=T;let E=!1;function C(){return r()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function S(t,n,i){const s=C(),o=T(),a=parseInt(o||"0");if(s)i?i.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(a<10||0==o.indexOf("10.0")||r())){let n=document.getElementById("downloader");n||(e.debug("injecting downloader iframe"),n=document.createElement("iframe"),n.id="downloader",n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.zIndex="-1",n.style.width="1px",n.style.height="1px",document.body.appendChild(n)),n.src=t}else if(/^data:/i.test(t)&&(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())){let i=atob(t.split(",")[1]),r=e.Util.stringToUint8Array(i),s=new Blob([r],{type:"img/png"});window.navigator.msSaveOrOpenBlob(s,n)}else{let e=window.document.createElement("a");"string"==typeof e.download?(e.href=t,e.download=n,document.body.appendChild(e),e.click(),document.body.removeChild(e)):document.location.href=t}}function I(t,n){let i="data";r()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(i=e.appTarget.appTheme.mobileSafariDownloadProtocol);const s=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);s&&(i=s[1]);return i+":"+n+";base64,"+t}function P(t,n,i={}){var r;e.debug("trigger download");const{contentType:s="application/octet-stream",userContextWindow:o,onError:a,maintainObjectURL:l}=i,c=null===(r=window.URL)||void 0===r?void 0:r.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(c&&!u){const i=c(new Blob([e.Util.stringToUint8Array(atob(t))],{type:s}));S(i,n,o),l?d=i:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=I(t,n),S(d,n,o)}catch(t){a&&a(t),e.debug("saving failed")}return d}function U(e){const t=document.createElement("img");return new Promise(((n,i)=>{t.onload=()=>n(t),t.onerror=()=>n(void 0),t.crossOrigin="anonymous",t.src=e}))}t.isBrowserSupported=function(){var t,n;if(!navigator)return!0;if(/bot|crawler|spider|crawling/i.test(navigator.userAgent))return!0;const i=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==i?void 0:i.some((e=>e.id==A())))return!1;const r=T(),s=parseInt(r||"0"),c=u()&&s>=38,g=h()&&s>=31,b=l(),y=d()&&s>=9,v=p()&&u()&&s>=21;let w=c||g||b||y||v;const x=f()||o()&&a()&&m();return w=w&&!x,w=w||/anybrowser=(true|1)/.test(window.location.href),E||(e.log(`Browser: ${A()} ${r} on ${k()}`),w||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),E=!0),w},t.devicePixelRatio=function(){if("undefined"==typeof window||!window.screen)return 1;const e=window.screen.systemXDPI,t=window.screen.logicalXDPI;return void 0!==e&&void 0!==t&&e>t?e/t:window&&void 0!==window.devicePixelRatio?window.devicePixelRatio:1},t.browserDownloadBinText=function(e,t,n){return P(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return P(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=C,t.isBrowserDownloadWithinUserContext=function(){const e=T(),t=parseInt(e||"0");return r()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=S,t.browserDownloadUInt8Array=function(t,n,i){return P(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=I,t.browserDownloadBase64=P,t.loadImageAsync=U,t.loadCanvasAsync=function(e){return U(e).then((e=>{const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}))},t.scaleImageData=function(e,t){const n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t;const i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),i.getImageData(0,0,e.width*t,e.height*t)},t.imageDataToPNG=function(e,t=1){if(!e)return;const n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t;const i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),n.toDataURL("image/png")};const _=1e6;function N(t){if(/^https?:\/\//i.test(t))return t;const n=(window.MonacoPaths||{})[t];return n||(e.U.startsWith(t,e.webConfig.commitCdnUrl)?t:e.webConfig.commitCdnUrl+t)}t.encodeToPngAsync=function(t,n){const{width:i,height:r,pixelDensity:s=4,maxSize:o=_,text:a}=n||{};return new Promise(((n,l)=>{const c=new Image;c.onload=function(){const t=document.createElement("canvas"),l=t.getContext("2d");t.width=(i||c.width)*s,t.height=(r||c.height)*s,a&&(l.fillStyle="#fff",l.fillRect(0,0,t.width,t.height)),l.drawImage(c,0,0,i,r,0,0,t.width,t.height);let u=t.toDataURL("image/png");for(;u.length>o;)t.width=t.width/2>>0,t.height=t.height/2>>0,e.debug(`screenshot size ${u.length}b, shrinking to ${t.width}x${t.height}`),l.drawImage(c,0,0,i,r,0,0,t.width,t.height),u=t.toDataURL("image/png");if(a){e.lzmaCompressAsync(a).then((i=>{const r=e.Util.encodeBlobAsync(t,i);n(r.toDataURL("image/png"))}))}else n(u)},c.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},c.src=t}))},t.resolveCdnUrl=N,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const i="style-"+t;if(document.getElementById(i))return Promise.resolve();const r=N(t),s=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==r))[0];return s?(s.id||(s.id=i),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=r,n.rel="stylesheet",n.type="text/css",n.id=i,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let O,D,R,M={};function L(e,t){if(!e)return t;if(!t)return e;return(e.indexOf("/")==e.length-1?e.substring(0,e.length-1):e)+"/"+(0==t.indexOf("/")?t.substring(1):t)}function B(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=N(t);let i=M[n];return i||(i=M[n]=new Promise(((t,i)=>{e.debug(`script: loading ${n}`);const r=document.createElement("script");r.type="text/javascript",r.addEventListener("load",(()=>t())),r.addEventListener("error",(e=>{delete M[n],i(e)})),r.src=n,r.async=!0,document.body.appendChild(r)}))),i},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&(200==i.status?t(i.responseText):n(i.status))},i.open("GET",e,!0),i.send()}))},t.loadBlocklyAsync=function(){if(!O){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());"undefined"==typeof Blockly&&(t=t.then((()=>e.BrowserUtils.loadScriptAsync("pxtblockly.js")))),t=t.then((()=>{e.debug("blockly: loaded")})),O=t}return O},t.patchCdn=function(t){if(!t)return t;const n=e.getOnlineCdnUrl();return n?t.replace("@cdnUrl@",n):t.replace(/@cdnUrl@\/(blob|commit)\/[a-f0-9]{40}\//,"./")},t.initTheme=function(){const t=e.appTarget.appTheme;if(t&&t.accentColor){let e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode(`.ui.accent { color: ${t.accentColor}; }\n .ui.inverted.menu .accent.active.item, .ui.inverted.accent.menu { background-color: ${t.accentColor}; }`)),document.getElementsByTagName("head")[0].appendChild(e)}if(e.Util.isUserLanguageRtl()){e.debug("rtl layout"),e.BrowserUtils.addClass(document.body,"rtl"),document.body.style.direction="rtl";const t=e.Util.toArray(document.head.getElementsByTagName("link")),n=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0];if(n){const t=n.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),n.setAttribute("href",t))}const i=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(i){const t=i.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),i.setAttribute("href",t),i.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=L,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=L(t,e[n]);return t},t.storageEstimateAsync=B,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){B().then((t=>(e.debug(`storage estimate: ${t.usage/t.quota*100>>0}%, ${t.usage/1e6>>0}/${t.quota/1e6>>0}Mb`),t.quota&&t.usage&&t.quota>1e6&&t.usage/t.quota>.9?(e.log("quota usage exceeded, clearing translations"),e.tickEvent("storage.cleanup"),V()):Promise.resolve()))).catch((t=>{e.reportException(t)}))}),1e4,!1):()=>{},t.stressTranslationsAsync=function t(){let n="...";for(let e=0;e<16;++e)n+=n+Math.random();return console.log(`adding entry ${2*n.length} bytes`),e.U.delay(1).then((()=>H())).then((e=>e.setAsync("foobar",Math.random().toString(),"",null,void 0,n))).then((()=>e.BrowserUtils.storageEstimateAsync())).then((e=>!e.quota||e.usage/e.quota<.8?t():Promise.resolve()))};class F{constructor(){this.translations={}}key(e,t,n){return`${e}|${t}|${n||"master"}`}get(e,t,n){return this.translations[this.key(e,t,n)]}getAsync(e,t,n){return Promise.resolve(this.get(e,t,n))}set(e,t,n,i,r,s,o){this.translations[this.key(e,t,n)]={etag:i,time:r,strings:s,md:o}}setAsync(t,n,i,r,s,o){return this.set(t,n,i,r,e.Util.now(),s),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class ${constructor(e,t,n,i){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler())}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise(((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)}))}openAsync(){return new Promise(((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)}))}getAsync(e,t){return new Promise(((n,i)=>{const r=this.getObjectStore(e).get(t);r.onsuccess=()=>n(r.result),r.onerror=()=>this.errorHandler(r.error,"get",i)}))}getAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e).openCursor(),r=[];i.onsuccess=()=>{i.result?(r.push(i.result.value),i.result.continue()):t(r)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,i)=>{const r=this.getObjectStore(e,"readwrite");let s;s=void 0!==t.id&&null!==t.id?r.put(t):r.add(t),s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"set",i)}))}deleteAsync(e,t){return new Promise(((n,i)=>{const r=this.getObjectStore(e,"readwrite").delete(t);r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"delete",i)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)}))}}t.IDBWrapper=$;class j{constructor(e){this.db=e,this.mem=new F}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new $(j.dbName(),2,((e,t)=>{t.result.createObjectStore(j.TABLE,{keyPath:j.KEYPATH})}),(()=>{V().catch((e=>{}))}));return e.openAsync().then((()=>new j(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),$.deleteDatabaseAsync(j.dbName()).then((()=>e())))))}getAsync(e,t,n){e=(e||"en-US").toLowerCase();const i=this.mem.key(e,t,n),r=this.mem.get(e,t,n);return r?Promise.resolve(r):this.db.getAsync(j.TABLE,i).then((i=>i?(this.mem.set(e,t,n,i.etag,i.time,i.strings),Promise.resolve(i)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,i,r,s,o,a){n=(n||"en-US").toLowerCase();const l=this.mem.key(n,i,r);let c=e.Util.now();this.mem.set(n,i,r,s,c,o,a),o&&Object.keys(o).filter((e=>!o[e])).forEach((e=>delete o[e]));const u={id:l,etag:s,time:c,strings:o,md:a};return this.db.setAsync(j.TABLE,u).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(j.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function H(){return e.Util.isNodeJS?Promise.resolve(new F):(D||(D=j.createAsync().catch((()=>new F))),D)}function V(){function t(){const t=j.dbName();return $.deleteDatabaseAsync(t).then((()=>{D=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),D=void 0}))}return D?D.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function G(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function z(e,t){return`${e}|${t||"master"}`}j.TABLE="files",j.KEYPATH="id",t.translationDbAsync=H,t.clearTranslationDbAsync=V,t.getTutorialCodeHash=G;class W{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(W.dbName(),2,((e,t)=>{t.result.createObjectStore(W.TABLE,{keyPath:W.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName())}));return t.openAsync().then((()=>new W(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName()).then((()=>t())))))}getAsync(t,n,i){const r=z(t,i),s=G(n);return this.db.getAsync(W.TABLE,r).then((t=>{if(t&&t.hash==s&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(W.TABLE,r)}))}setAsync(t,n,i,r){e.perf.measureStart("tutorial info db setAsync");z(t,r);const s=G(i);return this.setWithHashAsync(t,n,s)}setWithHashAsync(t,n,i,r){e.perf.measureStart("tutorial info db setAsync");const s=z(t,r),o={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{o[t]=n[e][t]}))}));const a={id:s,time:e.Util.now(),hash:i,snippets:n,blocks:o};return this.db.setAsync(W.TABLE,a).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(W.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function q(e){return e.split(/\s+/).filter((e=>!!e))}function J(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}W.TABLE="info",W.KEYPATH="id",t.tutorialInfoDbAsync=function(){return R||(R=W.createAsync()),R},t.clearTutorialInfoDbAsync=function(){function t(){const t=W.dbName();return $.deleteDatabaseAsync(t).then((()=>{R=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),R=void 0}))}return R?R.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=x()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:g()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,r){try{const e=window.screenLeft?window.screenLeft:window.screenX,s=window.screenTop?window.screenTop:window.screenY,o=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,l=o/2-i/2+e,c=a/2-r/2+s,u=window.open(t,n,"width="+i+", height="+r+", top="+c+", left="+l);return u.focus&&u.focus(),u}catch(n){return e.tickEvent("pxt.popupError",{url:t,msg:n.message}),null}},t.containsClass=function(e,t){return q(t).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},t.addClass=function(e,t){q(t).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},t.removeClass=function(e,t){q(t).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},t.getCookieLang=J,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==J()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){e.cloudStatus={none:{value:"none"},synced:{value:"synced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved"),longStatus:lf("Saved to cloud"),indicator:""},justSynced:{value:"justSynced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved!"),longStatus:lf("Saved to cloud!"),indicator:""},offline:{value:"offline",icon:"cloud-error-b",tooltip:lf("Unable to connect to cloud"),shortStatus:lf("offline"),longStatus:lf("Offline"),indicator:lf("offline")},syncing:{value:"syncing",icon:"cloud-saving-b",tooltip:lf("Saving project to cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:lf("syncing...")},conflict:{value:"conflict",icon:"cloud-error-b",tooltip:lf("Project was edited in two places and the changes conflict"),shortStatus:lf("conflict!"),longStatus:lf("Project has a conflict!"),indicator:"!"},localEdits:{value:"localEdits",icon:"cloud-saving-b",tooltip:lf("Saving project to the cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.deployCoreAsync=void 0,e.deployFallbackAsync=void 0,e.hasDeployFn=()=>e.deployCoreAsync||e.deployFallbackAsync,e.deployAsync=(t,n)=>(e.deployCoreAsync||e.deployFallbackAsync)(t,n),e.patchCompileResultAsync=void 0,e.browserDownloadAsync=void 0,e.saveOnlyAsync=void 0,e.renderBrowserDownloadInstructions=void 0,e.renderUsbPairDialog=void 0,e.renderIncompatibleHardwareDialog=void 0,e.showUploadInstructionsAsync=void 0,e.saveProjectAsync=void 0,e.electronDeployAsync=void 0,e.webUsbPairDialogAsync=void 0,e.onTutorialCompleted=void 0,e.workspaceLoadedAsync=void 0}(e.commands||(e.commands={}))}(pxt||(pxt={})),function(e){function t(){let t;return t||(t=e.U.isNodeJS?Promise.resolve(require("lzma")):Promise.resolve(window.LZMA),t.then((t=>(t||e.reportError("lzma","failed to load"),t)))),t}e.lzmaDecompressAsync=function(n){return t().then((t=>new Promise(((i,r)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),i(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),i(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((i,r)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),i(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),i(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i=n.lf;const r={"pxt::mkAction":1,"pxt::dumpPerfCounters":1,"pxt::deepSleep":1,"pxt::getConfig":1,"pxtrt::mkMap":1,"pxtrt::mapSet":1,"pxtrt::stclo":1,"pxtrt::mklocRef":1,"pxtrt::stlocRef":1,"pxtrt::ldlocRef":1,"pxtrt::panic":1};function s(e="namespace"){let t="",n="",i=(i,r="")=>{n!=i&&(n&&(t+="}\n"),i&&(t+=r||e+" "+i+" {\n"),n=i)},r=" ";return{setNs:i,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,r).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{r+=" "},decrIndent:()=>{r=r.slice(4)},finish:()=>(i(""),t)}}function o(e){if(!e)return null;e=e.trim();let t=/^\((.*)\)/.exec(e);return t&&(e=t[1]),/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(e)?parseInt(e):null}t.nsWriter=s,t.parseCppInt=o;let a={};class l extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function c(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e[n];t+=37==i||i>127?"%"+i.toString(16):String.fromCharCode(i)}return decodeURIComponent(t)}function u(t){let n="",i=0;for(;i<t.length;i+=2)n=t[i]+t[i+1]+n;return e.Util.assert(i==t.length),n}function d(e){let t=[65,20,14,47,184,47,162,187];e:for(let n=0;n<e.length;n+=16){if(e[n]!=t[0])continue;for(let i=0;i<t.length;++i)if(e[n+i]!=t[i])continue e;let i=e[n+8]|e[n+9]<<8,r=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let s=n+i+r;if(s>e.length)continue;let o=e.slice(n,n+i),a=e.slice(n+i,s);return{meta:c(o),text:a}}return null}function h(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let i;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(i=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(i=d(t)),58==t[0]){i=function(e){if(!e)return;let t,n=0,i=0,r=0,s=0;if(e.split(/\r?\n/).forEach((e=>{let o=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(o)n=parseInt(u(o[1]),16),i=parseInt(u(o[2]),16),r=n+i,t=new Uint8Array(r);else if(r>0){if(o=/^:10....0[0E](.*)(..)$/.exec(e),!o)return;let n=o[1];for(;r>0&&n.length>0;)t[s++]=parseInt(n[0]+n[1],16),n=n.slice(2),r--}})),!t||0!=r||s!=t.length)return;let o=new Uint8Array(n),a=new Uint8Array(i);for(let e=0;e<n;++e)o[e]=t[e];for(let e=0;e<i;++e)a[e]=t[n+e];return{meta:c(o),text:a}}(c(t)||"")}if(!i||!i.meta||!i.text)return n("This .hex file doesn't contain source.");let r=JSON.parse(i.meta);return r?"LZMA"==r.compression?e.lzmaDecompressAsync(i.text).then((t=>{if(!t)return null;let n=t.slice(0,r.headerSize||r.metaSize||0),i=t.slice(n.length);return n&&e.Util.jsonCopyFrom(r,JSON.parse(n)),{meta:r,source:i}})):r.compression?n(`Compression type ${r.compression} not supported.`):Promise.resolve({source:c(i.text)}):n("This .hex file is not valid.")}t.PkgConflictError=l,t.getExtensionInfo=function(t){const c={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",h="",p=[];const f=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of f)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(h&&(h+=", "),h+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(p.push(t),t.addSnapshot(c,[u,".h",".cpp"]));const m=JSON.stringify(c),g=a[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,x="codal"==y.buildEngine||"dockercodal"==y.buildEngine,k="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,A="dockerespidf"==y.buildEngine,T=!(w||x||k||A),E=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":x||k?d="/pxtapp/":A&&(d="/main/");let C="// Configuration defines\n",S="\nPXT_SHIMS_BEGIN\n",I="",P="",U='#include "pxt.h"\n',_="",N=e=>_+=` ${D}(${O}): ${e}\n`,O=0,D="",R=s("namespace"),M=s("declare namespace"),L=s("declare namespace"),B="",F={},$={};const j={true:"1",false:"0",null:"0",NULL:"0"};function H(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of p){if(t.getFiles().indexOf(u)>=0){const n=t.host().readFile(t,u);e.Util.assert(!!n,`dal.d.ts not found in ${t.id}`),n.split(/\r?\n/).forEach((e=>{let t=/^\s*(\w+) = (.*),/.exec(e);t&&(j[t[1]]=t[2])}))}for(const e of t.getFiles())(["Makefile","sdkconfig.defaults","CMakeLists.txt"].indexOf(e)>=0||n.endsWith(e,".mk"))&&(b.generatedFiles["/"+e]=t.host().readFile(t,e))}let V=["0","false","PXT_UTF8"],G={};function z(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(G.PXT_BOX_DEBUG=1),v.utf8&&(G.PXT_UTF8=1),v.switches.profile&&(G.PXT_PROFILE=1),v.switches.gcDebug&&(G.PXT_GC_DEBUG=1),v.switches.numFloat&&(G.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(G.PXT_VM=1);let W=0,q=!1,J="",Y="",K="",X=!1;function Q(){M.setNs(""),M.write(""),M.write(""),(K||Y)&&(M.write(Y),M.write(K),K="",Y="")}function Z(e,t){let s;J="",Y="",K="",X=!1;let a=-1;function l(){let e=J.replace(/Methods$/,"");return e==J?null:e}function c(e){switch(e.replace(/\s+/g,"")){case"void":return"void";case"int32_t":case"int":return"int32";case"uint32_t":case"unsigned":return"uint32";case"TNumber":case"float":case"double":return"number";case"uint16_t":return"uint16";case"int16_t":case"short":return"int16";case"uint8_t":case"byte":return"uint8";case"int8_t":case"sbyte":return"int8";case"bool":return v.shortPointers&&N("use 'boolean' not 'bool' on 8 bit targets"),"boolean";case"StringData*":case"String":case"ImageLiteral_":case"ImageLiteral":return"string";case"Action":return"() => void";case"TValue":return"any";default:return H(e)}}function u(e){switch(e=e.replace(/\s+/g,"")){case"int32_t":case"uint32_t":case"unsigned":case"uint16_t":case"int16_t":case"short":case"uint8_t":case"byte":case"int8_t":case"sbyte":case"int":case"ramint_t":return"I";case"void":return"V";case"float":return"F";case"TNumber":return"N";case"TValue":return"T";case"bool":return"B";case"double":return"D";case"ImageLiteral_":return"T";case"String":return"S";default:return n.lookup(F,e)?"I":"_"+e.replace(/[\*_]+$/,"")}}e=e.replace(/^(\s*#\s*if\s+(\w+)\s*$)([^]*?)(^\s*#\s*(elif|else|endif)\s*$)/gm,((e,t,n,i,r)=>V.indexOf(n)>=0&&!G[n]?t+i.replace(/[^\n]/g,"")+r:e)),O=0,q=!1,W=0,L.setNs(""),M.setNs(""),e.split(/\r?\n/).forEach((e=>{++O;let d=z(e);!function(e){let t=z(e);if(q&&t.indexOf("}")>=0&&(q=!1,L.write("}")),!q)return;let i=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(i){let e=i[1],r=i[3],s="";if(r){r=r.trim();let e=n.lookup(j,r);null!=e&&(s=" // "+r,r=e),W=o(r),null==W&&N("cannot determine value of "+t)}else W++,r=W+"";L.write(` ${H(e)} = ${r},${s}`)}else L.write(e)}(e);let h=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var p,f;if(h&&(p=h[2],f=h[3],q=!0,W=-1,L.write(""),L.write(""),(K||Y)&&(L.write(Y),L.write(K),K="",Y=""),L.write(`declare const enum ${H(p)} ${f}`),F[p]=!0,t||(R.setNs(J),R.write(`enum ${h[2]} : int;`))),function(e){return!(!q&&(/^\s*\/\*\*/.test(e)?(X=!0,Y=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(Y+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(K+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(R.setNs(J),R.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(m)if(J=m[1],l()){Q();let e=l();M.setNs(J,`declare interface ${e} {`)}else(K||Y)&&(Q(),M.setNs(H(J)),L.setNs(H(J)));else{if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!E&&(S+=`PXT_FNPTR(::${m[1]}),\n`,P+=`extern "C" void ${m[1]}();\n`,b.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(b.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!K||!m){if(m=/^\s*extern const (\w+) (\w+);/.exec(e),K&&m){let e={name:J+"::"+m[2],argsFmt:[],value:null};return b.functions.push(e),E||(S+="PXT_FNPTR(&::"+e.name+"),\n"),void(K="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),K&&m){let e=pxtc.parseCommentString(K);e.indexedInstanceNS&&(s=e,M.setNs(e.indexedInstanceNS),a=0);let t=m[1],n=m[2];if(s)return K=K.trim(),K+=` fixedInstance shim=${s.indexedInstanceShim}(${a++})`,M.write(""),M.write(Y),M.write(K),M.write(`const ${n}: ${c(t)};`),Y="",void(K="")}return K&&e.trim()?(N("declaration not understood: "+e),K="",void(Y="")):void 0}{s=null;let e=pxtc.parseCommentString(K);J||N("missing namespace declaration");let a=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],h=m[4];K=K.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(a)],f=[],g=h.split(/,/).filter((e=>!!e)).map((t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),r="",s="";if(i&&(r=i[2],s="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return N("invalid argument: "+t),{name:"???",type:"int"};let a=i[2];e.paramDefl[a]&&(r=e.paramDefl[a],s="?");let l=r?n.lookup(j,r):null;return null!=l&&(r=l),r&&(null==o(r)&&N("Invalid default value (non-integer): "+r),K+=` ${a}.defl=${r}`),{name:a+s,type:i[1]}}(e,t);return p.push(u(i.type)),f.push(i.type.replace(/ /g,"")),`${i.name}: ${c(i.type)}`})),y={name:J+"::"+d,argsFmt:p,value:null};if(Y)if(M.setNs(H(J)),M.write(""),M.write(Y),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(K)&&(K+=" imageLiteral=1"),K+=` shim=${y.name}`,M.write(K),d=H(d),l()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&N(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(K)?M.write(`${d}: ${c(a)};`):M.write(`${d}(${g.join(", ")}): ${c(a)};`)}else M.write(`function ${d}(${g.join(", ")}): ${c(a)};`);if(Y="",K="",t||(R.setNs(J),R.write(`${a} ${d}(${h});`)),b.functions.push(y),T)S+="(uint32_t)(void*)::"+y.name+",\n";else if(E){if(n.startsWith(y.name,"pxt::op_")||r[y.name]||e.expose||!n.startsWith(y.name,"pxt::")&&!n.startsWith(y.name,"pxtrt::")){const e=function(e,t){if("FiberContext*"==t[0])return"::"+e.name;let n="_wrp_"+e.name.replace(/:/g,"_");if($[e.name])return n;$[e.name]=!0,I+=`\nvoid ${n}(FiberContext *ctx) {\n`;const i=t.length;let r=[],s=!1,o="";for(let n=0;n<i;++n){const a=e.argsFmt[n+1],l=t[n];let c="I"==a?"toInt":"B"==a?"numops::toBool":"";const u=n==i-1?"ctx->r0":`ctx->sp[${i-n-2}]`;let d="";switch(l){case"TValue":case"TNumber":break;case"Action":c="asRefAction";break;case"String":c="convertToString",d="ctx, ",s=!0;break;default:c||(c="as"+l.replace(/\*/g,""))}o+=` ${l} a${n} = (${l}) ${c}(${d}${u});\n`,r.push("a"+n)}s&&(I+=" auto prevSP = ctx->sp;\n"),I+=o,s&&(I+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const a=`::${e.name}(${r.join(", ")})`;return"V"==e.argsFmt[0]?(I+=` ${a};\n`,I+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?I+=` ctx->r0 = fromInt(${a});\n`:"B"==e.argsFmt[0]?I+=` ctx->r0 = fromBool(${a});\n`:I+=` ctx->r0 = (TValue)${a};\n`,s&&(I+=" ctx->sp = prevSP;\n"),i>1&&(I+=` ctx->sp += ${i-1};\n`),I+="}\n",n}(y,f),t=y.argsFmt.length-1;S+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else S+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},ie={};function re(t){const r=t.config.platformio;r&&r.dependencies&&n.jsonCopyFrom(b.platformio.dependencies,r.dependencies),b.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(b.npmDependencies,t.config.npmDependencies);const s=t.config.codal;if(x&&s)for(const t of s.libraries||[]){const r=e.github.parseRepoId(t);r||n.userError(i("codal library {0} doesn't look like github repo",t));const s=e.github.stringifyRepo(r),o=n.lookup(ie,r.project);o?e.github.stringifyRepo(o)!=s&&n.userError(i("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(o),s)):ie[r.project]=r}const o=t.config.yotta;if(o){if(o.dependencies&&n.jsonCopyFrom(b.yotta.dependencies,o.dependencies),o.config){const e=n.jsonFlatten(o.config);for(const r of Object.keys(e)){const s=n.lookup(ne,r),o=e[r];if(!s||s.config.yotta.configIsJustDefaults)ne[r]=t,ee[r]=o;else if(ee[r]===o);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new l(i("conflict on yotta setting {0} between extensions {1} and {2}",r,t.id,s.id));throw e.pkg0=s,e.pkg1=t,e.settingName=r,e}}}if(o.optionalConfig){const e=n.jsonFlatten(o.optionalConfig);for(const t of Object.keys(e)){const n=e[t];te[t]=n}}}}if(T&&v.hasHex){let e=y;n.assert(!!e.yottaCorePackage),n.assert(!!e.githubCorePackage),n.assert(!!e.gittag);let t=e.githubCorePackage+"#"+y.gittag;b.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let r of p){_="",re(r),r==t?(e=!0,M.clear(),L.clear()):n.assert(!e);const s=e=>n.endsWith(e,".h"),o=".cpp",a=r.getFiles().filter(s).concat(r.getFiles().filter((e=>!s(e))));for(let e of a){const t=s(e);if(t||n.endsWith(e,o)){let s=r.config.name+"/"+e;("base"==r.config.name||/^core($|---)/.test(r.config.name))&&t&&(s=e),t&&(U+=`#include "${T?d.slice(1):""}${s}"\n`);let o=r.readFile(e);null==o&&n.userError(i("C++ file {0} is missing in extension {1}.",e,r.config.name)),D=s,Z(o,t),b.extensionFiles[d+s]=o,0==r.level&&(b.onlyPublic=!1),r.verProtocol()&&"pub"!=r.verProtocol()&&"embed"!=r.verProtocol()&&(b.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=r.readFile(e);b.extensionFiles[d+r.config.name+"/"+e.replace(/\.S$/,".s")]=t}}_&&(B+=i("Extension {0}:\n",r.id)+_)}e||(M.clear(),L.clear())}function se(e){return Object.keys(b.extensionFiles).concat(Object.keys(b.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}B&&n.userError(B),n.jsonCopyFrom(te,ee),n.iterMap(te,((e,t)=>{null===t&&delete te[e]})),Object.keys(te).filter((e=>/-/.test(e))).forEach((e=>{const t=te[e];delete te[e],te[e.replace(/-/g,"_")]=t})),!T&&y.yottaConfigCompatibility&&Object.keys(te).forEach((e=>te["YOTTA_CFG_"+e]=te[e])),te.PXT_TARGET=JSON.stringify(e.appTarget.id);const oe=n.jsonUnFlatten(te);if(k){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(A){const e=n.concatArrayLike([se(".c"),se(".cpp"),se(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),b.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(x){let t=y,i=n.clone(t.codalDefinitions)||{},r=t.codalTarget;"string"==typeof r&&(r+=".json");let s={target:r,definitions:i,config:i,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(ie).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==s.libraries.length&&delete s.libraries,n.iterMap(n.jsonFlatten(oe),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),i[e]=t})),b.generatedFiles["/codal.json"]=JSON.stringify(s,null,4)+"\n",e.debug(`codal.json: ${b.generatedFiles["/codal.json"]}`)}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,((t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)})),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=oe;let t="pxt-app";y.yottaBinary&&(t=y.yottaBinary.replace(/-combined/,"").replace(/\.hex$/,""));let n={name:t,version:"0.0.0",description:"Auto-generated. Do not edit.",license:"n/a",dependencies:b.yotta.dependencies,targetDependencies:{},bin:"./source"};b.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${b.generatedFiles["/module.json"]}`)}for(let e of Object.keys(G))C+=`#define ${e} ${G[e]}\n`;if(v.uf2Family&&(C+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),b.generatedFiles[d+"pointers.cpp"]=U+R.finish()+P+I+S+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=C,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),T&&(b.generatedFiles["/config.json"]=JSON.stringify(oe,null,4)+"\n",e.debug(`yotta config.json: ${b.generatedFiles["/config.json"]}`)),b.generatedFiles[d+"main.cpp"]='\n#include "pxt.h"\n#ifdef PXT_MAIN\nPXT_MAIN\n#else\nint main() {\n uBit.init();\n pxt::start();\n release_fiber();\n return 0; // your program will never reach this line.\n}\n#endif\n',b.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${se(n).join(" ")}\n`};t("PXT_C",".c"),t("PXT_CPP",".cpp"),t("PXT_S",".s"),t("PXT_HEADERS",".h"),e+="PXT_SOURCES := $(PXT_C) $(PXT_S) $(PXT_CPP)\n",e+="PXT_OBJS := $(addprefix bld/, $(PXT_C:.c=.o) $(PXT_S:.s=.o) $(PXT_CPP:.cpp=.o))\n",b.generatedFiles["/Makefile.inc"]=e}b.generatedFiles["/functions.json"]=JSON.stringify(b.functions,null,1);let ae=b.extensionFiles;n.jsonCopyFrom(ae,b.generatedFiles);let le={config:y.serviceId,tag:y.gittag,replaceFiles:ae,dependencies:T?b.yotta.dependencies:null},ce=JSON.stringify(le);return b.sha=n.sha256(ce),b.skipCloudBuild=!!y.skipCloudBuild,b.compileData=ts.pxtc.encodeBase64(n.toUTF8(ce)),b.shimsDTS=M.finish(),b.enumsDTS=L.finish(),Object.keys(a).length>10&&(a={}),a[m]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>h(new Uint8Array(e))))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,r={};function s(r){return n.hasOwnProperty(r.sha)||(n[r.sha]=function(n){let r="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then((t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()})).catch((t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve())));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then((e=>e.json))).then((e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)));var n,i}(n).then((s=>s?(e.tickEvent("cppcompile.cachehit"),s):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(r=t+"/compile/"+n.sha,e.U.httpGetTextAsync(r+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,i)=>{let s=0;const o=8e3,a=3e5,l=e.U.now(),c=()=>{if(s++,e.U.now()-l>a)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:s}),n(null),null;let i=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${i} (attempt #${s})`),e.tickEvent("cppcompile.poll",{retry:s}),e.Util.httpGetJsonAsync(i).then((t=>{e.log(`build log ${i.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:s,duration:e.U.now()-l}),t.success?(e.log("fetching "+r+".hex"),n(e.U.httpGetTextAsync(r+".hex"))):(e.log("build failed"),t.mbedresponse&&t.mbedresponse.result&&t.mbedresponse.result.exception&&e.log(t.mbedresponse.result.exception),n(null))}),(t=>(e.log(`waiting ${o/1e3|0}s for C++ build...`),setTimeout(c,o),null)))};c()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(r)),n[r.sha]}function o(t,n,i,r,s=10){return t.cacheStoreAsync(i,r).then((()=>t.cacheGetAsync(n))).then((r=>{let o;try{o=JSON.parse(r||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),o=[]}o=o.filter((e=>e!=i)),o.unshift(i);let a=o.slice(s);return o=o.slice(0,s),e.U.promiseMapAll(a,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(o))))}))}function a(e,t,n){return e.cacheGetAsync(t).then((i=>{let r;try{r=JSON.parse(i||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return r[0]!=n?(r=r.filter((e=>e!=n)),r.unshift(n),e.cacheStoreAsync(t,JSON.stringify(r))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=o,t.recordGetAsync=a,t.getHexInfoAsync=function(t,n,i){if(!n.sha)return Promise.resolve(null);const l=r[n.sha];if(l)return Promise.resolve(l);e.debug("get hex info: "+n.sha);let c="hex-"+n.sha;return t.cacheGetAsync(c).then((i=>{let r;try{r=i?JSON.parse(i):null}catch(e){console.log("invalid cache entry, clearing entry"),r=null}return r&&r.hex?(e.debug("cache hit, size="+i.length),r.hex=function(t){let n=[];for(let i=0;i<t.length;i++){let r=/^([@!])(....)$/.exec(t[i]);if(!r){n.push(t[i]);continue}let s=parseInt(r[2],16),o=t[++i],a="";if("@"==r[1]){a="";let e=parseInt(o,16);for(;e-- >0;)a+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else a=ts.pxtc.decodeBase64(o);e.Util.assert(a.length>0),e.Util.assert(a.length%16==0);for(let e=0;e<a.length;){let t=[16,s>>8&255,255&s,0];s+=16;for(let n=0;n<16;++n)t.push(a.charCodeAt(e++));let i=0;for(let e=0;e<t.length;++e)i+=t[e];t.push(255&-i);let r=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(r+="0"),r+=n.toString(16)}n.push(r.toUpperCase())}}return n}(r.hex),a(t,"hex-keys",c).then((()=>r))):s(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let i=0;i<e.length;i+=n){let r=-1,s="";n=0;let o=!1;for(;n<500;){let a=/^:10(....)00(.{32})(..)$/.exec(e[i+n]);if(!a)break;let l=a[2],c=/^0+$/.test(l),u=parseInt(a[1],16);if(-1==r)o=c,t.push((o?"@":"!")+a[1]),r=u-16;else{if(c!=o)break;if(r+16!=u)break}o||(s+=l),r=u,n++}if(0==n)t.push(e[i]),n=1;else if(o)t.push(n.toString(16));else{let e="";for(let t=0;t<s.length;t+=2)e+=String.fromCharCode(parseInt(s.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let i=JSON.stringify(e);return e.hex=n,o(t,"hex-keys",c,i).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(r).length>20&&(r={}),r[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){function n(n,i,r={},s=null,o=null){if(t.testMode||n==t.TEST_KEY){const e={success:!0};return Promise.resolve({statusCode:200,headers:{},text:JSON.stringify(e),json:e})}return e.Util.multipartPostAsync(i,r,s,o)}function i(n,i,r,s,o){e.Util.assert(!!i&&!!r&&!!s);const a="https://api.crowdin.com/api/project/"+i+"/";return o=o||{},t.testMode?delete o.key:o.key=r,n&&(o.branch=n),a+s+"?"+Object.keys(o).map((e=>`${e}=${encodeURIComponent(o[e])}`)).join("&")}function r(e){let t=0;return function(){if(t++>10)throw new Error("Too many API calls for "+e)}}function s(t,a,l,c,u){return c=o(c),e.debug(`create directory ${t||""}/${c}`),u||(u=r(c)),n(l,i(t,a,l,"add-directory"),{json:"true",name:c}).then((n=>{if(e.debug(`crowdin resp: ${n.statusCode}`),200==n.statusCode||400==n.statusCode)return Promise.resolve();if(500==n.statusCode&&n.text){if(50===JSON.parse(n.text).error.code)return e.log("directory already exists"),Promise.resolve()}const i=n.json||JSON.parse(n.text)||{error:{}};if(404==n.statusCode&&17==i.error.code){e.log(`parent directory missing for ${c}`);const n=c.replace(/\/[^\/]+$/,"");if(n!=c)return s(t,a,l,n,u).then((()=>s(t,a,l,c,u)))}throw new Error(`cannot create directory ${t||""}/${c}: ${n.statusCode} ${JSON.stringify(i)}`)}))}function o(e){return e.replace(/\\/g,"/")}function a(e,t,n,i){const r=t.name,s=n?n+"/"+r:r;switch(t.fullName=s,t.branch=i||"",t.node_type){case"file":e.push(t);break;case"directory":(t.files||[]).forEach((t=>a(e,t,s,i)));break;case"branch":(t.files||[]).forEach((i=>a(e,i,n,t.name)))}}function l(t,n){const i=e.appTarget.versions.pxtCrowdinBranch||"",r=e.appTarget.versions.targetCrowdinBranch||"";let s=[];if(t.forEach((e=>a(s,e,""))),s=s.filter((e=>e.fullName.indexOf("/")<0?e.branch==i:e.branch==r)),n&&(s=s.filter((e=>0==e.fullName.indexOf(n)))),"core"!=e.appTarget.id){const t=e.appTarget.id+"/";s=s.filter((e=>e.fullName.indexOf("/")<0||e.fullName.substr(0,t.length)==t||e.fullName.indexOf("common-docs")>=0))}return s}function c(t,n){const r=i("",t,n,"info",{json:"true"});return e.Util.httpGetTextAsync(r).then((e=>JSON.parse(e)))}t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.TEST_KEY="!!!testmode!!!",t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.downloadTranslationsAsync=function(t,n,r,s,a={}){const l=i(t,n,r,"info",{json:"true"}),c={};return s=o(s),e.Util.httpGetTextAsync(l).then((o=>{const l=JSON.parse(o);if(!l)throw new Error("info failed");let u=l.languages.filter((e=>"en"!=e.code));e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.availableLocales&&(u=u.filter((t=>e.appTarget.appTheme.availableLocales.indexOf(t.code)>-1))),e.log("languages: "+u.map((e=>e.code)).join(", "));const d=()=>{const o=u.pop();if(!o)return Promise.resolve();const l=i(t,n,r,"export-file",{file:s,language:o.code,export_translated_only:a.translatedOnly?"1":"0",export_approved_only:a.validatedOnly?"1":"0"});return e.log(`downloading ${o.name} - ${o.code} (${u.length} more)`),e.Util.httpGetTextAsync(l).then((t=>{try{const e=JSON.parse(t);e&&(c[o.code]=e)}catch(t){e.log(l+" "+t)}return d()})).then((()=>e.Util.delay(1e3)))};return d()})).then((()=>c))},t.createDirectoryAsync=s,t.uploadTranslationAsync=function t(a,l,c,u,d){e.Util.assert(!!l),e.Util.assert(!!c);const h=r(u=o(u));function p(){return f("update-file",{update_option:"update_as_unapproved"})}function f(r,o){return o.type="auto",o.json="",o.escape_quotes="0",h(),n(c,i(a,l,c,r),o,u,d).then((n=>function(n){const i=n.statusCode,r=e.Util.jsonTryParse(n.text)||{};if(e.debug(`upload result: ${i}`),404==i&&r.error&&8==r.error.code)return e.log(`create new translation file: ${u}`),f("add-file",{});if(404==i&&r.error&&17==r.error.code)return s(a,l,c,u.replace(/\/[^\/]+$/,""),h).then((()=>p()));if(!r.success&&r.error&&53==r.error.code)return e.log(`${u} being updated, waiting 5s and retry...`),e.U.delay(5e3).then((()=>t(a,l,c,u,d)));if(200==i||r.success)return Promise.resolve();throw new Error(`Error, upload translation: ${u}, ${i}, ${n.text}`)}(n)))}return p()},t.projectInfoAsync=c,t.listFilesAsync=function(t,n,i){return e.log(`crowdin: listing files under ${i}`),c(t,n).then((t=>{if(!t)throw new Error("info failed");let n=l(t.files,i);return e.debug(`crowdin: found ${n.length} under ${i}`),n.map((e=>({fullName:e.fullName,branch:e.branch||""})))}))},t.languageStatsAsync=function(t,n,r){const s=i("",t,n,"language-status",{language:r,json:"true"});return e.Util.httpGetJsonAsync(s).then((e=>l(e.files)))},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise(((i,r)=>{const s=new MutationObserver((()=>{if(t==n.value)return;const r=e.Util.rlf(n.value);n.remove(),s.disconnect(),i(r)}));s.observe(n,{attributes:!0})}));return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function i(e,t,i={}){i.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const r=n(e),s=n(t),o=Math.min(i.maxDiffSize||1024,r.length+s.length);if(0==o)return[];const a=r.length>65520?Uint32Array:Uint16Array,l={};let c=0;const u=h(r),d=h(s);function h(e){const t=new a(e.length);let n=0;for(let r of e)i.ignoreWhitespace&&(r=r.replace(/\s+$/g,"").replace(/^\s+/g,"")),l.hasOwnProperty(r)?t[n]=l[r]:(++c,t[n]=c,l[r]=c),n++;return t}const p=new a(2*o+1);let f=-1;for(let e=0;e<=o;e++)null!=T(e,p)&&(f=e);if(-1==f)return null;const m=[];let g=null;for(let e=0;e<=f;e++){const t=m.length?m[m.length-1].slice(0):new a(2*f+1);if(m.push(t),g=T(e,t),null!=g)break}const b=[];let y=g;for(let e=m.length-1;e>=0;e--){const t=m[e];let n=0,i=0;y==-e||y!=e&&t[o+y-1]<t[o+y+1]?(i=y+1,n=t[o+i]):(i=y-1,n=t[o+i]+1);let a=n-y;for(let e=t[o+y]-n-1;e>=0;--e)b.push(" "+s[a+e]);i==y-1?b.push("- "+r[n-1]):a>0&&b.push("+ "+s[a-1]),y=i}if(b.reverse(),i.context==1/0||i.full)return b;let v=1,w=1,x=0;const k=[],A=i.context||3;for(;x<b.length;){let e=x;for(;e<b.length&&" "==b[e][0];)e++;if(e==b.length)break;const t=e-A,n=t-x;n>0&&(v+=n,w+=n,x=t);const i=k.length,r=v,s=w;k.push("@@");let o=x,a=0;for(;o<b.length;){if(" "==b[o][0]){if(a++,a>2*A+2){o-=A+2;break}}else a=0;o++}for(;x<o;){k.push(b[x]);switch(b[x][0]){case"-":v++;break;case"+":w++;break;case" ":v++,w++}x++}k[i]=`@@ -${r},${v-r} +${s},${w-s} @@`}return k;function T(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let r=i-n;for(;i<u.length&&r<d.length&&u[i]==d[r];)i++,r++;if(t[o+n]=i,i>=u.length&&r>=d.length)return n}return null}}function r(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function s(e){const t=/^@@ -(\d+),(\d+) \+(\d+),(\d+)/.exec(e);return t&&{oldStart:parseInt(t[1])-1,oldLength:parseInt(t[2]),newStart:parseInt(t[3])-1,newLength:parseInt(t[4])}}t.toLines=n,t.compute=i,t.diff3=function(t,r,s,o,a){const l=g(t),c=g(s);if(!l||!c)return;const u=n(t),d=n(s);let h=0,p=[],f=0,m=0;for(let t=0;t<l.length-1;)if(l[t]==f&&c[t]==m)p.push(u[f]),f++,m++,t++;else{let n=!0,i=!0,r=t;for(;r<l.length&&(l[r]!=f+r-t&&(n=!1),c[r]!=m+r-t&&(i=!1),null==l[r]||null==c[r]);)r++;if(e.U.assert(r<l.length),n)for(;m<c[r];)p.push(d[m++]);else if(i)for(;f<l[r];)p.push(u[f++]);else if(u.slice(f,l[r]).join("\n")==d.slice(m,c[r]).join("\n"))for(;f<l[r];)p.push(u[f++]);else{for(h++,p.push("<<<<<<< "+o);f<l[r];)p.push(u[f++]);for(p.push("=======");m<c[r];)p.push(d[m++]);p.push(">>>>>>> "+a)}t=r,f=l[r],m=c[r]}return{merged:p.join("\n"),numConflicts:h};function g(t){const n=i(r,t,{context:1/0});if(!n)return;const s=[];let o=0,a=0;for(let t of n)"+"==t[0]?o++:"-"==t[0]?(s[a]=null,a++):" "==t[0]?(s[a]=o,o++,a++):e.U.oops();return s.push(o+1),s}},t.removeTrailingSemiColumns=r,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let i=n[0].replace(/\n$/,""),s=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=r(i),s=r(s)),{fileA:i,fileB:s}},t.parseDiffMarker=s,t.render=function(t,n,r={}){const o=i(t,n,r);if(!o)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const a={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let l=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(r.update?"update":"")},d);let p=null;return o.forEach(((t,n)=>{const h=s(t);h?(l=h.oldStart,c=h.newStart):("+"!=t[0]&&l++,"-"!=t[0]&&c++);const f=o[n+1]?o[n+1][0]:"",m=o[n+2]?o[n+2][0]:"",g=t.slice(2);let b=e.dom.el("code",null,g);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=m&&"@"!=m&&""!=m)){const r=function(t,n){const r=i(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!r)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const s=[],o=[];for(let t=0;t<r.length;){let n=t;const i=r[t][0];for(;r[n]&&r[n][0]==i;)n++;const a=r.slice(t,n).map((e=>e.slice(2))).join("");" "==i?(s.push(e.dom.el("code",{class:"ch-common"},a)),o.push(e.dom.el("code",{class:"ch-common"},a))):"-"==i?s.push(e.dom.el("code",{class:"ch-removed"},a)):"+"==i?o.push(e.dom.el("code",{class:"ch-added"},a)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},s),b:e.dom.el("div",{class:"inline-diff"},o)}}(t.slice(2),o[n+1].slice(2));b=r.a,p=r.b}if(u=t[0],r.hideMarkerLine&&"@"==u||r.hideRemoved&&"-"==u)return;const y="@"==u,v=`${a[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!r.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":l}),!r.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":c}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!r.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},b)]))})),h},t.resolveMergeConflictMarker=function(t,n,i,r){let s=e.diff.toLines(t),o=n;for(;o<s.length&&!/^<<<<<<<[^<]/.test(s[o]);)o++;let a=o+1;for(;a<s.length&&!/^=======$/.test(s[a]);)a++;let l=a+1;for(;l<s.length&&!/^>>>>>>>[^>]/.test(s[l]);)l++;if(l>=s.length)return e.debug(`diff marker mistmatch: ${s.length} -> ${o} ${a} ${l}`),t;if(s[o]=void 0,s[a]=void 0,s[l]=void 0,!i)for(let e=o;e<=a;++e)s[e]=void 0;if(!r)for(let e=a;e<=l;++e)s[e]=void 0;return s.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,i){let r=e.Util.jsonTryParse(t),s=e.Util.jsonTryParse(n),o=e.Util.jsonTryParse(i);if(r&&!o)return t;if(!r)return i||n;if(!s&&o&&(s=o),!r||!s||!o)return;delete r.installedVersion,delete s.installedVersion,delete o.installedVersion;const a={},l=e.U.unique(Object.keys(s).concat(Object.keys(r)).concat(Object.keys(o)),(e=>e));for(const t of l){const n=r[t],i=s[t],l=o[t];if(JSON.stringify(n)==JSON.stringify(l))void 0!==n&&(a[t]=n);else switch(t){case"name":a[t]=c(n,i,l);break;case"version":a[t]=e.semver.strcmp(n,l)>0?n:l;break;case"languageRestriction":case"preferredEditor":case"targetVersion":a[t]=n;break;case"public":a[t]=n&&l;break;case"files":case"testFiles":{const e=u(n||[],i||[],l||[]);if(!e)return;a[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},i||{},l||{});if(Object.keys(e).length)return;a[t]=e;break}case"description":if(n&&!l)a[t]=n;else{if(n||!l)return;a[t]=l}break;default:return}}return e.Package.stringifyConfig(a);function c(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,i){const r=[],s=e.U.unique(n.concat(t).concat(i),(e=>e));for(const e of s){const s=t.indexOf(e)>-1,o=i.indexOf(e)>-1,a=n.indexOf(e)>-1;s==o||o==a?s&&r.push(e):o&&r.push(e)}return r}function d(t,n,i){const r={},s=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(i)),(e=>e));for(const o of s){const s=t[o],a=i[o],l=n[o];if(s==a)s&&(r[o]=s);else{const t=e.github.parseRepoId(s),n=e.github.parseRepoId(a);if(t&&n&&e.semver.tryParse(t.tag)&&e.semver.tryParse(n.tag)&&t.owner&&t.project&&t.owner==n.owner&&t.project==n.project){const i=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;r[o]=`github:${t.owner}/${t.project}#${i}`}else a==l?s&&(r[o]=s):a&&(r[o]=a)}}return r}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,i,r){let s={},o=i.tree.tree.map((e=>e.path)).filter((e=>/\.(ts|blocks|md|jres|asm|json)$/.test(e))).filter((t=>t!=e.CONFIG_NAME));return t.fileName&&(o=o.filter((e=>0===e.indexOf(t.fileName))).map((e=>e.slice(t.fileName.length+1)))),o.find((e=>/\.ts$/.test(e)))||(r.config.files.filter((e=>o.indexOf(e)<0)).forEach((e=>{o.push(e),n[e]=r.files[e]})),e.Util.jsonCopyFrom(s,r.config.dependencies)),Object.keys(s).length||(s[e.appTarget.corepkg]="*"),{name:"",files:o,dependencies:s,preferredEditor:o.find((e=>/.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME}}}(e.diff||(e.diff={}))}(pxt||(pxt={})),function(e){!function(t){t.extractSharedIdFromPostUrl=function(t){return e.Util.httpGetJsonAsync(t+".json").then((t=>t.post_stream&&t.post_stream.posts&&t.post_stream.posts[0]&&t.post_stream.posts[0].link_counts.map((t=>e.Cloud.parseScriptId(t.url))).filter((e=>!!e))[0]))},t.topicsByTag=function(t,n){const i=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(i).then((n=>{const i=e.Util.toDictionary(n.users,(e=>e.id.toString()));return n.topic_list.topics.map((e=>({id:e.id,title:e.title,url:`${t}/t/${e.slug}/${e.id}`,imageUrl:e.image_url,author:i[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i,r={},s={};const o="\x3c!-- @CMD@ @ARGS@ --\x3e";let a={parent:o,short:o,description:"\x3c!-- desc --\x3e",activities:"\x3c!-- activities --\x3e",explicitHints:"\x3c!-- hints --\x3e",flyoutOnly:"\x3c!-- flyout --\x3e",hideIteration:"\x3c!-- iter --\x3e",codeStart:"\x3c!-- start --\x3e",codeStop:"\x3c!-- stop --\x3e",autoOpen:"\x3c!-- autoOpen --\x3e",autoexpandOff:"\x3c!-- autoexpandOff --\x3e",preferredEditor:"\x3c!-- preferredEditor --\x3e",tutorialCodeValidation:"\x3c!-- tutorialCodeValidation --\x3e"};function l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&"),e=l(e,"<","<"),e=l(e,">",">"),e=l(e,'"',"""),e=l(e,"'","'")}function u(e){return e?c(e.replace(/\&([#a-z0-9A-Z]+);/g,((e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';default:return"#"==t[0]?String.fromCharCode(parseInt(t.slice(1))):e}}))):e}t.htmlQuote=c,t.html2Quote=u;const d=[{rx:/^vimeo\.com\/(\d+)/i,cmd:"### @vimeo $1"},{rx:/^(www\.youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+(\#t=([0-9]+m[0-9]+s|[0-9]+m|[0-9]+s))?)/i,cmd:"### @youtube $2"}];t.requireMarked=()=>"undefined"!=typeof marked?marked:"undefined"!=typeof require?require("marked"):void 0,t.requireDOMSanitizer=()=>"undefined"!=typeof DOMPurify?DOMPurify.sanitize:"undefined"!=typeof require?require("DOMPurify").sanitize:void 0;const h=e=>`<div class='ui negative message'>${c(e)}</div>`;function p(e){let t=n.clone(r),i=n.clone(s),o=n.clone(a),l={},c={},d=e.params,p=e.theme;e.boxes=t,e.macros=i,e.settings=o,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,r)=>{let s=function(e){let t={};for(;e.trim();){let n=/\s*([^=\s]+)=("([^"]*)"|'([^']*)'|(\S*))/.exec(e);if(n){let e=n[3]||n[4]||n[5]||"";t[n[1].toLowerCase()]=e}else n=/^\s*(\S+)/.exec(e),t[n[1]]="true";e=e.slice(n[0].length)}return t}(n),a=s["data-name"]||s.id;return a?(/box/.test(s.class)?t[a]=r:/aside/.test(s.class)?t[a]=`\x3c!-- BEGIN-ASIDE ${a} --\x3e${r}\x3c!-- END-ASIDE --\x3e`:/setting/.test(s.class)?o[a]=r:/menu/.test(s.class)?l[a]=r:/toc/.test(s.class)?c[a]=r:i[a]=r,`\x3c!-- macro ${a} --\x3e`):h("id or data-name missing on macro")}));let f=(e,t)=>{let n=l.item,i={NAME:e.name};if(e.subitems)n=l["toc-dropdown"]?l["toc-dropdown"]:0==t?l["top-dropdown"]:l["inner-dropdown"],i.ITEMS=e.subitems.map((e=>f(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=l.divider),e.path&&!/^(https?:|\/)/.test(e.path))return h("Invalid link: "+e.path);i.LINK=e.path}return g(n,i,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||0!=e.filepath.indexOf(t.path))&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,r={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),r.LINK=t.path,y.indexOf(t)>=0?(r.ACTIVE="active",r.EXPANDED="true",m.push({name:t.name,href:t.path})):r.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],r.ITEMS=t.subitems.map((e=>w(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),g(i,r,["ITEMS"]))};d.menu=(p.docMenu||[]).map((e=>f(e,0))).join("\n"),d.TOC=b.map((e=>w(e,0))).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let x="";m.length>1&&(x=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${m.map(((e,t)=>`<a class="${t==m.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==m.length-1?"page":""}">${u(e.name)}</a>`)).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=x,p.boardName&&(d.boardname=u(p.boardName)),p.boardNickname&&(d.boardnickname=u(p.boardNickname)),p.driveDisplayName&&(d.drivename=u(p.driveDisplayName)),p.homeUrl&&(d.homeurl=u(p.homeUrl)),d.targetid=p.id||"???",d.targetname=p.name||"Microsoft MakeCode",d.docsheader=p.docsHeader||"Documentation",d.orgtitle="MakeCode";const k=p.docsLogo&&n.htmlEscape(p.docsLogo),A=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),T=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=k?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${k}" />`:"",d.orglogo=A?`<img aria-hidden="true" role="presentation" class="ui image" src="${A}" />`:"",d.orglogomobile=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"";let E=e.ghEditURLs||[];if(E.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of E)e+=`<a href="${n}"><i class="write icon"></i>${t}</a><br>\n`,t=lf("Edit template of this page on GitHub");e+="</p>\n",d.github=e}else d.github="";const C=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=C;const S=lf("Print this page"),I=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${S}" aria-label="${S}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=I;const P=`\n <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="${lf("Side menu")}" role="menuitem" aria-expanded="false">\n <i class="content icon"></i>\n </a>\n `;d.sidebarToggle=P;const U=["tocsearch1","tocsearch2"].map((e=>`\n <input type="search" name="q" placeholder="${lf("Search...")}" aria-label="${lf("Search Documentation")}">\n <i onclick="document.getElementById('${e}').submit();" tabindex="0" class="search link icon" aria-label="${lf("Search")}" role="button"></i>\n `));d.searchBar1=U[0],d.searchBar2=U[1];let _="";p.accentColor&&(_+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=_,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>g(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e){e.image=function(e,t,n){let i='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(i+=' title="'+t+'"'),i+=' loading="lazy"',i+=this.options.xhtml?"/>":">",i},e.listitem=function(e){const t=/^\s*\[( |x)\]/i.exec(e);return t?`<li class="${" "==t[1]?"unchecked":"checked"}">`+e.slice(t[0].length)+"</li>\n":"<li>"+e+"</li>\n"},e.heading=function(e,t,n){let i=/(.*)#([\w\-]+)\s*$/.exec(e),r="";return i?(e=i[1],r=i[2]):r=n.toLowerCase().replace(/[^\w]+/g,"-"),e&&(e=e.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"")),(e=e.trim()).match(/^\{([\s\S]+)\}$/)&&(e=e.substr(1,e.length-2)),`<h${t} id="${this.options.headerPrefix}${r}">${e}</h${t}>`}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,i,r)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${r}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`))}function g(e,t,i=[]){return e?e.replace(/@(\w+)@/g,((e,r)=>{let s=n.lookup(t,r)||"";return s+="",i.indexOf(r)<0&&(s=u(s)),s})):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let r=!0;e.pubinfo||(r=!1,e.pubinfo={});let s=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,s.time){let e=parseInt(s.time);s.timems||(s.timems=1e3*e+""),s.humantime||(s.humantime=n.isoTime(e))}s.name&&(s.dirname=s.name.replace(/[^A-Za-z0-9_]/g,"-"),s.title=s.name),r&&(s.JSON=JSON.stringify(s,null,4).replace(/</g,"\\u003c"));let o=e.template;o=o.replace(/<!--\s*@include\s+(\S+)\s*-->/g,((t,n)=>"\x3c!-- include "+n+" --\x3e\n"+((e.theme.htmlDocIncludes||{})[n]||"")+"\n\x3c!-- end include --\x3e\n")),o=m(o,s),e.locale&&(o=y(o,e.locale).text);let a={html:o,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:s,TOC:e.TOC};p(a),i||(i=t.requireMarked());let l=new i.Renderer;f(l);const c=l.link;l.link=function(e,t,n){const i=new RegExp("^[/#]").test(e),r=i?"":"_blank";i&&a.versionPath&&(e=`/${a.versionPath}${e}`);return c.call(l,e,t,n).replace(/^<a /,`<a ${r?`target="${r}"`:""} rel="nofollow noopener" `)};let b=t.requireDOMSanitizer();i.setOptions({renderer:l,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:b,smartLists:!0,smartypants:!0});let v=e.markdown;e.repo&&(v+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),v=v.replace(/^\s*https?:\/\/(\S+)\s*$/gm,((e,t)=>{for(let e of d){let n=e.rx.exec(t);if(n)return e.cmd.replace(/\$(\d+)/g,((e,t)=>n[parseInt(t)]||""))+"\n"}return e})),v=v.replace(/@([a-z]+)@/gi,((t,i)=>{let r=s[i];return!r&&e.throwOnError&&n.userError(`unknown macro ${i}`),r||"unknown macro"}));let w=i(v);w=w.replace(/<br\s*\/>/gi,"<br/>"),w=w.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let x="",k=0;function A(e,t,n){let i=n;return e<=k&&(i=x+i,x="",k=0),i}if(w=w.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,i,r,o)=>{let l=/^(\w+)\s+(.*)/.exec(o),c=l?l[1]:o,d=l?l[2]:"";if(d=u(d),c=u(c),i=parseInt(i),r){if("@"==r){let t=n.lookup(a.settings,c);if(null!=t)s[c]=d;else if(t=n.lookup(a.macros,c),null==t)return e.throwOnError&&n.userError(`Unknown command: @${c}`),h(`Unknown command: @${c}`);return A(i,0,g(t,{ARGS:d,CMD:c},["ARGS","CMD"]))}{if(!c){let e=x;return x="",e}let t=n.lookup(a.boxes,c);if(t){let e=t.split("@BODY@"),n=A(i,0,e[0].replace("@ARGS@",d));x=e[1];let r=t.match(/data-[^>\s]+/gi);return r&&r.indexOf("data-inferred")>=0&&(k=i),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return A(i,0,t)})),x&&(w+=x),!s.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(w);e&&(s.title=u(e[1]))}if(!s.description){let e=/<p>([^]+?)<\/p>/.exec(w);e&&(s.description=u(e[1]))}const T=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(w)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(w);T&&(s.cardLogo=u(T[1])),s.twitter=u(e.theme.twitter||"@msmakecode");let E={main:""};w=w.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,i)=>{let r=n.lookup(E,t);return E[t]=(r||"")+i,"\x3c!-- aside --\x3e"})),w=w.replace(/\n<\/code>/g,"</code>"),E.main=w,w="";for(let e of Object.keys(E))w+=(C=e+"-container",S=E[e],g(a.boxes[C]||"@BODY@",{BODY:S},["BODY"]));var C,S;s.body=w,s.name=s.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(s["theme_"+t]=n)}return a.finish()},t.embedUrl=function(e,t,n,i){return`<div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${`${e}#${t}:${n}`}" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div>`},t.runUrl=function(e,t,n){return`<div style="position:relative;height:0;padding-bottom:${t};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${e}?id=${encodeURIComponent(n)}" allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div>`},t.codeEmbedUrl=function(e,t,n){const i=`${e}---codeembed#pub:${t}`;return`<div style="position:relative;height:calc(${n=Math.ceil(n||300)}px + 5em);width:100%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const b={b:1,strong:1,em:1};function y(e,t){const i={};function r(e){let r=/^(\s*)([^]*?)(\s*)$/.exec(e),s=r[2].replace(/\s+/g," ");if(""==s||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|( )+)\s*)+$/.test(s))return null;let o=n.lookup(t,s);return o?s=o:i[s]="",r[1]+s+r[3]}function s(e){return e.replace(/&llt;/g,"<").replace(/&ggt;/g,">")}return{text:e=(e=(e=(e="<start>"+(e=e.replace(/<([\/\w]+)([^<>]*)>/g,((e,t,n)=>{let i=t.replace(/^\//,"").toLowerCase();return 1===b[i]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,i,o)=>{if("script"==n||"style"==n)return s(e);let a=r(s(o));return null==a?s(e):t+a}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,i)=>null==r(i)?e:t+n+'="'+i.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:i}}function v(e,t){if(e.id==t)return e;for(let n of e.children){let e=v(n,t);if(e)return e}return null}function w(e,t){let n=0,i=[{level:0,id:"",title:"",start:n,text:"",children:[]}],r=(e=e.replace(/\r/g,"")).split(/\n/),s={};for(let e of r){let r=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),o=null;if(t&&r)if(r[4])if(s[r[4]])r=null;else{o=v(t,r[4]);let e=t=>{t.id&&(s[t.id]=!0),t.children.forEach(e)};o&&e(o)}else r=null;if(r){let s={level:t?1:r[1].length,title:r[2].trim(),id:r[4]||"",start:n,text:"",children:[]};if(o){e="";for(let t=0;t<o.level;++t)e+="#";e+=" ",e+=s.title||o.title,e+=" #"+s.id}for(;i[i.length-1].level>=s.level;)i.pop();i[i.length-1].children.push(s),i.push(s)}i[i.length-1].text+=e+"\n",n++}return i[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const i=e.docs.requireMarked(),r=t.requireDOMSanitizer(),s={renderer:new i.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:r,smartLists:!1,smartypants:!1};let o={name:"dummy",subitems:[]},a=[];a.push(o);let l=i.lexer(n,s),c=!1;l.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":c=!0;let t={name:"",path:"",subitems:[]};return void a.push(t);case"text":let n=a[a.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,i){n.name=t,n.path=i.replace(".md","")})):c&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let i=a.pop();a[a.length-1].subitems.push(i)}c=!1}));let u=o.subitems;return u&&0!=u.length?u:null},t.visitTOC=function(e,t){e.forEach((function(e){t(e),e.subitems&&e.subitems.forEach(t)}))};let x=!1;function k(e,t){if(x||function(){function e(e,t,n){let i=k(e,t).trim();if(i!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${i}`),new Error("augment docs test fail")}x=!0;let t="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nTEx2\n### Example 3\nTEx3\n\n## See also #also\nTAlso\n",n="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",i="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nMy example\n### Example 3\nTEx3\n\n## See Also These! #also\nMy links\n",r="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",s="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";e(t,"",t),e(t," ",t),e(t,n,i),e(t,r,s)}(),!t)return e;let i=w(e,null),r=w(t,i),s={},o={};for(let e of r.children)n.assert(0==e.children.length),n.assert(!!e.id),s[e.id]=e.text;let a=e=>{e.id&&void 0!==s[e.id]&&(o[e.id]=!0,e.text=s[e.id],e.children=[]),e.children.forEach(a)};a(i);let l="",c=e=>{l+=e.text,e.children.forEach(c)};c(i);let u="",d=r.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of r.children)o[e.id]||(u+=e.text);return u&&(l+="## Couldn't apply replacement logic to:\n"+u),l}t.augmentDocs=k}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const i=document.createElement(e);return t&&Object.keys(t).forEach((e=>i.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?i.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&i.appendChild(t)}(n),i}}(e.dom||(e.dom={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){const t=/```package\s+((.|\s)+?)\s*```/i.exec(e);let n;return t&&(n={},t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).forEach((e=>n[e[0]]=e[1]||"*"))),n}function i(e){const t=/```config\s+((.|\s)+?)\s*```/i.exec(e);let n=[];return t&&t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).filter((e=>"feature"==e[0]&&!!e[1])).forEach((e=>n.push(e[1]))),n.length?n:void 0}function r(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],i=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(i)}}}function s(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function o(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter((e=>!!e)).map((e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,((e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map((e=>null==e?void 0:e.trim()));(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function a(t){if(!t)return[];const n=[];let i,r=!1,s="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))r=!0;else if(/^(### ~|```)$/.test(t)){if(r=!1,i&&s){const t=o(s);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}s="",i=void 0}else r&&(s+=t+"\n")})),n.forEach((t=>t.cards.forEach((t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map((e=>({url:t.url,cardType:t.cardType,editor:e})))}})))),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=r,t.parseTemplateProjectJSON=s,t.parseExampleMarkdown=function(t,o){if(!o)return;const a=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(o);if(!a)return;const l=n(o),c=a[1],u=a[2],d=i(o),h=r(o),p={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===a[1]?e.MAIN_PY:e.MAIN_TS]:u},dependencies:l,features:d,snippetType:c,source:u};return p.filesOverride=Object.assign(Object.assign({},p.filesOverride),s(o)),h&&(p.filesOverride[e.TILEMAP_JRES]=h.jres,p.filesOverride[e.TILEMAP_CODE]=h.ts),p},t.parseCodeCards=o,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach((e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach((e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&i.push(n),n=void 0)})),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=a,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>a(e)))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map((e=>Object.keys(e).filter((t=>!!e[t])).map((t=>"otherActions"===t?e[t].map((e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`)).join("\n"):`* ${t}: ${e[t]}`)).join("\n"))).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,r=t.charAt(t.length-1);for(;i-- >0;)t+=r}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,(e=>"OK"==e))}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(i).then((()=>null)):new Promise((r=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),r(i)},this.io.sendPacketAsync(i)}))))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",(()=>new Promise((r=>{this.onResponse=n=>{var s;"OK"!=n&&"O"==n[0]?i+=(s=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(s))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),r(i))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const i=this.pktSize/2-6;if(n>i){const r=new Uint8Array(n),s=o=>{const a=Math.min(n-o,i);return 0==a?Promise.resolve(r):this.readMemAsync(t+o,a).then((t=>(e.U.memcpy(r,o,t),s(o+a))))};return s(0)}return this.sendCmdAsync("m"+t.toString(16)+","+n.toString(16)).then((t=>e.U.fromHex(t)))}initBMPAsync(){return Promise.resolve().then((()=>this.sendRCmdAsync("swdp_scan"))).then((e=>(this.targetInfo=e,this.sendCmdAsync("vAttach;1",(e=>"T"==e[0]))))).then((()=>{}))}initAsync(){return e.U.delay(1e3).then((()=>this.sendCmdAsync("!"))).then((()=>this.sendCmdAsync("qSupported"))).then((t=>{let n={};return t=(t=";"+t+";").replace(/;([^;]+)[=:]([^:;]+)/g,((e,t,i)=>(n[t]=i,";"))),this.pktSize=parseInt(n.PacketSize)||1024,e.log("GDB-server caps: "+JSON.stringify(n)+" "+t.replace(/;+/g,";")),this.bmpMode?this.initBMPAsync():this.sendCmdAsync("c").then((()=>{}))}))}}}(pxt||(pxt={})),function(e){!function(t){function n(){var n,i;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(i=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===i?void 0:i.noGithubProxy)}t.token=null,t.forceProxy=!1;const i={};function r(n){var i;return n.method=null!==(i=n.method)&&void 0!==i?i:"GET",function i(r){var s;const o=e.U.clone(n);t.token&&(o.headers||(o.headers={}),o.url==_?o.headers.Authorization=`bearer ${t.token}`:(o.url=e.BrowserUtils.cacheBustingUrl(o.url),o.headers.Authorization=`token ${t.token}`));return o.allowHttpErrors=null!==(s=o.allowHttpErrors)&&void 0!==s&&s,e.U.requestAsync(o).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(o,n))return i(!1)}throw n}))}(t.token)}function s(e){return r({url:e,method:"GET"}).then((e=>e.json))}function o(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then((e=>e.json))}function a(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return r({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class l{constructor(){this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let r=this.packages[i];if(r)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(r);const s=E(t);return o(I(s.slug,n,s.fileName,"text")).then((e=>this.packages[i]={files:e}))}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(i="master");const r=`${t}/${i}`;let s=this.configs[r];if(s)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(s);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(r,n.files[e.CONFIG_NAME])}catch(e){a(e)}const o=await u(t,i,e.CONFIG_NAME);return this.cacheConfig(r,o)}async loadPackageAsync(t,i){if(i||(i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then((t=>e.U.clone(t)))}catch(e){a(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return g(t,n).then((i=>{const r=`${t}/${i}`;let s=this.packages[r];return s?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(s))):(e.log(`Downloading ${t}/${n} -> ${i}`),u(t,i,e.CONFIG_NAME).then((n=>{const s={files:{}};s.files[e.CONFIG_NAME]=n;const o=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(o).slice(1),(e=>u(t,i,e).then((t=>{s.files[e]=t})))).then((()=>(this.packages[r]=s,e.U.clone(s))))})))}))}}function c(t,n,s){return r({url:"https://api.github.com/repos/"+I(t.slug,"contents",t.fileName,s+"?ref="+n),method:"GET"}).then((n=>{const r=n.json;return i[t.slug]=!0,r&&"base64"==r.encoding&&null!=r.content?atob(r.content):e.U.httpGetTextAsync(r.download_url)}))}function u(t,n,r){const s=E(t);return i[s.slug]?c(s,n,r):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+I(s.slug,n,s.fileName,r),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:c(s,n,r)))}function d(e,t,n,i){return r({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:i||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function h(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function p(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function f(i,r="tags",o,a){const l=E(i),c=(u=o,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const h=c?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${l.slug}/refs${a?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+r+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):s(`https://api.github.com/repos/${l.slug}/git/refs/${r}/?per_page=100`);let p=e=>e.replace(/^refs\/[^\/]+\//,"");return h.then((t=>{t.sort(((t,n)=>e.semver.strcmp(p(t.ref),p(n.ref))));let n={};for(let e of t)n[p(e.ref)]=e.object.sha;return{refs:n,head:d}}),(e=>404==e.statusCode?{refs:{}}:Promise.reject(e)))}function m(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?s(e.object.url).then((e=>"commit"==e.object.type?e.object.sha:Promise.reject(new Error("Bad type (2nd order) "+e.object.type)))):Promise.reject(new Error("Bad type "+e.object.type))}function g(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=E(e);return s(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(m,(e=>s(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(m)))}function b(e,n="master"){return t.db.loadConfigAsync(e,n)}function y(n,i){const r=E(n);return r?A(r,i)?(e.tickEvent("github.download.banned"),e.log("Github repo is banned"),Promise.resolve(void 0)):t.db.loadPackageAsync(r.fullName,r.tag).then((t=>{const r=U(i,n);if(r){const i=e.Package.parseAndValidConfig(t.files[e.CONFIG_NAME]);i&&(e.log(`auto-disable ${r.join(",")} due to targetconfig entry for ${n}`),i.disablesVariants=r,t.files[e.CONFIG_NAME]=e.Package.stringifyConfig(i))}return t})):(e.log("Unknown GitHub syntax"),Promise.resolve(void 0))}let v;function w(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function x(e,t){var n;if(!e)return;const i={owner:e.owner.login.toLowerCase(),slug:e.full_name.toLowerCase(),fullName:((null==t?void 0:t.fullName)||e.full_name).toLowerCase(),fileName:null===(n=null==t?void 0:t.fileName)||void 0===n?void 0:n.toLocaleLowerCase(),name:e.name,description:e.description,defaultBranch:e.default_branch,tag:null==t?void 0:t.tag,updatedAt:Math.round(new Date(e.updated_at).getTime()/1e3),fork:e.fork,private:e.private};return i.status=k(i,null==t?void 0:t.config),i}function k(e,t){return e?A(e,t)?v.Banned:function(e,t){return!!function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t)||!(!e||!t)&&!!(e.fullName&&t.approvedRepos&&t.approvedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase())))}(e,t)?v.Approved:v.Unknown:v.Unknown}function A(e,t){return!!function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase()))))}(e,t)||!!t&&(!e||!e.fullName||!(!t.bannedRepos||!t.bannedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase()))))}async function T(t,i){const r=E(t);if(!r)return;const l=k(r,i);if(l==v.Banned)return;if(n())try{return await function(t,n){return o(t.slug).then((e=>{if(e)return{github:!0,owner:t.owner,fullName:t.fullName,fileName:t.fileName,slug:t.slug,name:t.fileName?`${e.name}-${t.fileName}`:e.name,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}})).catch((t=>{e.reportException(t)}))}(r,l)}catch(e){a(e)}return x(await s("https://api.github.com/repos/"+r.slug),{config:i,fullName:r.fullName,fileName:r.fileName,tag:r.tag})}function E(e){if(!e)return;e=(e=e.trim()).replace(/\/$/,"");const t=/^https:\/\/([^./#]+)\.github\.io\/([^/#]+)\/?$/i.exec(e);t&&(e=`github:${t[1]}/${t[2]}`),e=(e=(e=e.replace(/^github:/i,"")).replace(/^https:\/\/github\.com\//i,"")).replace(/\.git\b/i,"");const n=/^([^#\/:]+)\/([^#\/:]+)(\/([^#]+))?(#([^\/:]*))?$/.exec(e);if(!n)return;const i=n[1],r=n[2];let s=n[4];const o=n[6],a=s&&/^tree\/([^\/]+\/)/.exec(s);return a&&(s=s.slice(a[0].length)),{owner:i,project:r,slug:I(i,r),fullName:I(i,r,s),tag:o,fileName:s}}function C(e){return!!e&&"github:"==e.slice(0,7)}function S(e){return e?"github:"+e.fullName.toLowerCase()+"#"+(e.tag||"master"):void 0}function I(...e){return e.filter((e=>!!e)).join("/")}function P(t,n){if(!t||!t.upgrades)return null;const i=E(n);return i?e.U.lookup(t.upgrades,i.fullName.toLowerCase()):null}function U(e,t){const n=P(e,t),i=/^dv:(.*)/.exec(n);if(i){const e=i[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}return null}t.MemoryGithubDb=l,t.downloadTextAsync=u,t.db=new l,t.authenticatedUserAsync=function(){return t.token?s("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return s("https://api.github.com/repos/"+E(e).slug+"/commits?sha="+t).then((e=>e.map((e=>{const t=e.commit;return t.url=e.url,t.sha=e.sha,t}))))},t.getCommitAsync=function(e,t){return s("https://api.github.com/repos/"+E(e).slug+"/git/commits/"+t).then((e=>s(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(E(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,i,r){return d(`${E(e).slug}/commits/${t}/comments`,{body:n,path:i,position:r}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const i=E(e);return 200==(await r({url:`https://api.github.com/repos/${i.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,i){const s=E(t);await r({url:`https://api.github.com/repos/${e.github.join(s.slug,"contents",s.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(i)),branch:"master"},successCodes:[201]})},t.createTagAsync=async function(e,t,n){await d(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await d(e+"/releases",{tag_name:t,target_commitish:n,name:t,draft:!1,prerelease:!1})},t.createPRFromBranchAsync=async function(e,t,n,i,r){const s=await d(e+"/pulls",{title:i,body:r||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==s?void 0:s.html_url},t.mergeAsync=function(t,n,i,s){return r({url:`https://api.github.com/repos/${E(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:s}}).then((n=>{if(201==n.statusCode||204==n.statusCode)return n.json.sha;if(409==n.statusCode)return null;throw e.U.userError(lf("Cannot merge in github.com/{1}; code: {2}",t,n.statusCode))}))},t.getRefAsync=function(e,t){return s("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(m).catch((e=>{404!=e.statusCode&&Promise.reject(e)}))},t.getNewBranchNameAsync=async function(e,t="patch-"){return h(await f(e,"heads"),t)},t.createNewBranchAsync=p,t.forkRepoAsync=async function(t,n,i="pr-"){const r=E(t),s=x(await d(`${r.slug}/forks`,{}),{fullName:r.fullName,fileName:r.fileName}),o=Date.now()+3e5;let a=null;for(;!a&&Date.now()<o;){await e.U.delay(1e3);try{a=await f(s.slug,"heads")}catch(e){}}if(!a)throw new Error(lf("Timeout waiting for fork"));const l=h(a,i);return await p(s.slug,l,n),s.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return f(e,t,n,i).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=f,t.pkgConfigAsync=b,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t){const n=await e.packagesConfigAsync(),i=await e.github.latestVersionAsync(t.slug,n),r=`${t.fullName}#${i}`;return await e.github.downloadPackageAsync(r,n),{version:`github:${r}`,config:await b(t.fullName,i)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>C(t.dependencies[e])));if(i.length){const n=await e.packagesConfigAsync();await Promise.all(i.map((async e=>{const i=t.dependencies[e];if(!await y(i,n))throw new Error(lf("Cannot load extension {0} from {1}",e,i))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.listUserReposAsync=function(){return N('{\n viewer {\n repositories(first: 100, affiliations: [OWNER, COLLABORATOR], orderBy: {field: PUSHED_AT, direction: DESC}) {\n nodes {\n name\n description\n full_name: nameWithOwner\n private: isPrivate\n fork: isFork\n updated_at: updatedAt\n owner {\n login\n }\n defaultBranchRef {\n name\n }\n pxtjson: object(expression: "master:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "master:README.md") {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n}').then((t=>t.data.viewer.repositories.nodes.filter((e=>e.pxtjson)).filter((t=>{t.default_branch=t.defaultBranchRef.name;const n=e.Package.parseAndValidConfig(t.pxtjson&&t.pxtjson.text),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>x(e,{fullName:e.full_name})))))},t.createRepoAsync=function(e,t,n){return d("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then((e=>x(e)))},t.enablePagesAsync=async function(t){const n=E(t);let i;try{const e=await s(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await d(`https://api.github.com/repos/${n.slug}/pages`,{source:{branch:"master",path:"/"}},{Accept:"application/vnd.github.switcheroo-preview+json"})).html_url}catch(t){e.tickEvent("github.pages.error"),e.reportException(t)}if(i){const n=await s(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:i},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return w(e)},t.mkRepoIconUrl=w,t.repoStatus=k,t.repoAsync=T,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(E).filter((e=>!!e));return i.length>0?Promise.all(i.map((e=>T(e.fullName,n)))).then((e=>e.filter((e=>e&&e.status!=v.Banned)))):e.U.httpGetJsonAsync(`${e.Cloud.apiRoot}ghsearch/${e.appTarget.id}/${e.appTarget.platformid||e.appTarget.id}?q=${encodeURIComponent(t)}`).then((t=>t.items.map((e=>x(e,{config:n,fullName:e.full_name}))).filter((e=>e.status==v.Approved||n.allowUnapproved&&e.status==v.Unknown)).filter((t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())))).catch((e=>[]))},t.parseRepoId=E,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=C,t.stringifyRepo=S,t.normalizeRepoId=function(e){const t=E(e);if(t)return t.tag=t.tag||"master",S(t)},t.join=I,t.upgradedPackageReference=function(t,n){const i=P(t,n);if(!i)return null;const r=/^min:(.*)/.exec(i),s=r&&e.semver.tryParse(r[1]);if(s){const t=E(n),i=e.semver.tryParse(t.tag);return i&&e.semver.cmp(i,s)<0?(t.tag=r[1],e.debug(`upgrading ${n} to ${r[1]}`),S(t)):(i||e.log(`not upgrading ${n} - cannot parse version`),null)}return U(t,n)||e.log(`invalid upgrade rule: ${n} -> ${i}`),n},t.upgradedPackageId=function(e,t){const n=U(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,i,r){const s=E(t);return s?T(s.slug,n).then((t=>{if(t)return f(t.slug,"tags",i,r).then((i=>{let r=Object.keys(i.refs);r=e.semver.sortLatestTags(r);const o=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(o&&n.releases&&n.releases["v"+o.major]){const i=n.releases["v"+o.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==s.fullName.toLowerCase()))[0];if(i){if(r.some((e=>e==i.tag)))return e.debug(`approved release ${i.fullName}#${i.tag} for v${o.major}`),Promise.resolve(i.tag);e.reportError("packages",`approved release ${i.fullName}#${i.tag} for v${o.major} not found anymore`,{repo:t.fullName})}}return r[0]?Promise.resolve(r[0]):i.head||g(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const i={};return Object.keys(n).map((e=>({id:e,ghid:t.parseRepoId(n[e])}))).filter((e=>{var t;return null===(t=e.ghid)||void 0===t?void 0:t.tag})).forEach((t=>{const{id:n,ghid:r}=t;let s=i[r.slug];s||(s=i[r.slug]={tag:r.tag,deps:[]}),s.deps.push(t),e.semver.strcmp(s.tag,r.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(r)}`),s.tag=r.tag)})),e.U.values(i).forEach((t=>t.deps.forEach((i=>{i.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(i.ghid)} -> ${t.tag}`),i.ghid.tag=t.tag,n[i.id]=e.github.stringifyRepo(i.ghid))})))),n},t.GIT_JSON=".git.json";const _="https://api.github.com/graphql";function N(e){const t=JSON.stringify({query:e});return d(_,t)}t.lookupFile=function(e,t,n){if(!t)return null;const i=I(e.fileName,n);return t.tree.tree.find((e=>e.path==i))},t.ghGraphQLQueryAsync=N,t.findPRNumberforBranchAsync=function(e,t){const n=E(e);return N(`\n{\n repository(owner: ${JSON.stringify(n.owner)}, name: ${JSON.stringify(n.project)}) {\n pullRequests(last: 1, states: [OPEN, MERGED], headRefName: ${JSON.stringify(t)}) {\n edges {\n node {\n number\n state\n mergeable\n baseRefName\n url\n isDraft\n }\n }\n }\n }\n}\n`).then((e=>{const t=e.data.repository.pullRequests.edges[0];if(t&&t.node){const e=t.node;return{number:e.number,mergeable:e.mergeable,state:e.state,title:e.title,url:e.url,base:e.baseRefName}}return{number:-1}}))},t.getPagesStatusAsync=function(e){return s(`https://api.github.com/repos/${e}/pages`).catch((e=>({status:null})))}}(e.github||(e.github={}))}(pxt||(pxt={})),function(e){let t;e.REFCNT_FLASH="0xfffe",e.VTABLE_MAGIC=249,e.ValTypeObject=4,function(e){e[e.BoxedString=1]="BoxedString",e[e.BoxedNumber=2]="BoxedNumber",e[e.BoxedBuffer=3]="BoxedBuffer",e[e.RefAction=4]="RefAction",e[e.RefImage=5]="RefImage",e[e.RefCollection=6]="RefCollection",e[e.RefRefLocal=7]="RefRefLocal",e[e.RefMap=8]="RefMap",e[e.RefMImage=9]="RefMImage",e[e.MMap=10]="MMap",e[e.BoxedString_SkipList=11]="BoxedString_SkipList",e[e.BoxedString_ASCII=12]="BoxedString_ASCII",e[e.ZPin=13]="ZPin",e[e.User0=16]="User0"}(t=e.BuiltInType||(e.BuiltInType={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function i(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function r(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return e[t]|e[t+1]<<8}function o(e){let t=new Uint8Array(4*e.length);for(let i=0;i<e.length;++i)n(t,4*i,e[i]);return t}t.HF2_CMD_BININFO=1,t.HF2_MODE_BOOTLOADER=1,t.HF2_MODE_USERSPACE=2,t.HF2_CMD_INFO=2,t.HF2_CMD_RESET_INTO_APP=3,t.HF2_CMD_RESET_INTO_BOOTLOADER=4,t.HF2_CMD_START_FLASH=5,t.HF2_CMD_WRITE_FLASH_PAGE=6,t.HF2_CMD_CHKSUM_PAGES=7,t.HF2_CMD_READ_WORDS=8,t.HF2_CMD_WRITE_WORDS=9,t.HF2_CMD_DMESG=16,t.HF2_FLAG_SERIAL_OUT=128,t.HF2_FLAG_SERIAL_ERR=192,t.HF2_FLAG_CMDPKT_LAST=64,t.HF2_FLAG_CMDPKT_BODY=0,t.HF2_FLAG_MASK=192,t.HF2_SIZE_MASK=63,t.HF2_STATUS_OK=0,t.HF2_STATUS_INVALID_CMD=1,t.HF2_STATUS_EXEC_ERR=2,t.HF2_STATUS_EVENT=128,t.HF2_CMD_JDS_CONFIG=32,t.HF2_CMD_JDS_SEND=33,t.HF2_EV_JDS_PACKET=8388640,t.CUSTOM_EV_JACDAC="jacdac",t.HF2_EV_MASK=8388608,t.write32=n,t.write16=i,t.read32=r,t.read16=s,t.encodeU32LE=o,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(r(e,n));return t};let a=!1;function l(t){a?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){a=!0};class c{constructor(n){var i;this.io=n,this.cmdSeq=e.U.randomUint32(),this.lock=new e.U.PromiseQueue,this.flashing=!1,this.rawMode=!1,this.maxMsgSize=63,this.bootloaderMode=!1,this.reconnectTries=0,this.autoReconnect=!1,this.icon=(null===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{};let s=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let r=i[0]&t.HF2_FLAG_MASK,o=63&i[0],a=new Uint8Array(o);if(e.U.memcpy(a,0,i,1,o),r&t.HF2_FLAG_SERIAL_OUT)this.onSerial(a,r==t.HF2_FLAG_SERIAL_ERR);else if(s.push(a),r!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(r==t.HF2_FLAG_CMDPKT_LAST);let i=0;for(let e of s)i+=e.length;let o=new Uint8Array(i),a=0;for(let t of s)e.U.memcpy(o,a,t),a+=t.length;s=[],o[2]&t.HF2_STATUS_EVENT?n.onEvent(o):this.msgs.push(o)}},n.onEvent=t=>{let n=r(t,0),i=e.U.lookup(this.eventHandlers,n+"");i?i(t.slice(4)):l("unhandled event: "+n.toString(16))},n.onError=e=>{l("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{l("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then((()=>{})):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(r,o){if(this.io.talksAsync)return this.io.talksAsync([{cmd:r,data:o}]).then((e=>e[0]));let a=8;o&&(a+=o.length);let c=new Uint8Array(a),u=65535&++this.cmdSeq;n(c,0,r),i(c,4,u),i(c,6,0),o&&e.U.memcpy(c,8,o,0,o.length);let d=0,h=()=>this.msgs.shiftAsync(1e3).then((e=>{if(s(e,0)!=u){if(d<3)return d++,l(`message out of sync, (${u} vs ${s(e,0)}); will re-try`),h();this.error("out of sync")}let n="";switch(e[3]&&(n="; info="+e[3]),e[2]){case t.HF2_STATUS_OK:return e.slice(4);case t.HF2_STATUS_INVALID_CMD:this.error("invalid command"+n);break;case t.HF2_STATUS_EXEC_ERR:this.error("execution error"+n);break;default:this.error("error "+e[2]+n)}return null}));return this.sendMsgAsync(c).then(h)}sendMsgAsync(e){return this.sendMsgCoreAsync(e)}sendSerialAsync(e,t=!1){return this.io.sendSerialAsync?this.io.sendSerialAsync(e,t):this.sendMsgCoreAsync(e,t?2:1)}sendMsgCoreAsync(e,n=0){let i=new Uint8Array(64),r=s=>{let o=e.length-s;if(o<=0)return Promise.resolve();o>63?(o=63,i[0]=t.HF2_FLAG_CMDPKT_BODY):i[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(i[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),i[0]|=o;for(let t=0;t<o;++t)i[t+1]=e[s+t];return this.io.sendPacketAsync(i).then((()=>r(s+o)))};return this.lock.enqueue("out",(()=>r(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(l("Switching into bootloader mode"),this.io.isSwitchingToBootloader&&this.io.isSwitchingToBootloader(),this.maybeReconnectAsync().then((()=>this.talkAsync(t.HF2_CMD_START_FLASH).then((()=>{}),(e=>this.talkAsync(t.HF2_CMD_RESET_INTO_BOOTLOADER).then((()=>{}),(e=>{})).then((()=>this.reconnectAsync().catch((e=>{throw"devicenotfound"===e.type&&(e.type="repairbootloader"),e})))))))).then((()=>this.initAsync())).then((()=>{this.bootloaderMode||this.error("cannot switch into bootloader mode")})))}isFlashing(){return!!this.flashing}reflashAsync(t){l("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],i=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(i))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,i){return e.U.assert(i.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,o([n,i.length].concat(i))).then((()=>{}))}readWordsAsync(i,r){let s=new Uint8Array(8);return n(s,0,i),n(s,4,r),e.U.assert(r<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,s)}pingAsync(){return this.rawMode?Promise.resolve():this.talkAsync(t.HF2_CMD_BININFO).then((e=>{}))}maybeReconnectAsync(){return this.pingAsync().catch((e=>this.reconnectAsync().then((()=>this.pingAsync()))))}flashAsync(i){let r=Date.now(),s=0,o=r=>{if(r>=i.length)return Promise.resolve();let s=i[r],a=new Uint8Array(4+s.payloadSize);return n(a,0,s.targetAddr),e.U.memcpy(a,4,s.data,0,s.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,a).then((()=>o(r+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*i.length;return l(`Starting flash (${Math.round(e/1024)}kB).`),s=Date.now(),this.pageSize>16384?i:u(i,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=i.length){let t=256*(i=e).length;l(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>o(0))).then((()=>{let e=Date.now(),t=e-r,n=e-s;l(`Flashing done at ${Math.round(256*i.length/n*1e3/1024)} kB/s in ${t}ms (reset ${t-n}ms). Resetting.`)})).then((()=>this.talkAsync(t.HF2_CMD_RESET_INTO_APP).catch((e=>{})))).then((()=>{}))}initAsync(){return this.rawMode?Promise.resolve():Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=r(e,4),this.flashSize=r(e,8)*this.pageSize,this.maxMsgSize=r(e,12),this.familyID=r(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO)))).then((t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,((e,t,i)=>(n[t.replace(/-/g,"")]=i,""))),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)})).then((()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then((()=>{this.jacdacAvailable=!0}),(e=>{this.jacdacAvailable=!1})))).then((()=>{this.reconnectTries=0}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),s=pxtc.parseChecksumBlock(i);return s?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then((t=>r(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>s.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;l("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let i=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const r=i.read32;let s,o,a,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function m(e){return 1&e?e>>1:0!=e?2&e?e==t.taggedNull?null:e!=t.taggedFalse&&(e==t.taggedTrue||{tagged:e>>2}):{ptr:e}:void 0}function g(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let r=[];for(;t>0;){let n=Math.min(i,t);r.push(g(e,n)),t-=n,e+=n}return Promise.all(r).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let r=0;return g(t.ptr,56).then((s=>{r=i.read16(s,2);let o=s.length;return r==e.BuiltInType.BoxedString||r==e.BuiltInType.BoxedBuffer?o=i.read16(s,4)+6:r==e.BuiltInType.BoxedNumber&&(o=12),o>s.length?g(t.ptr+s.length,o-s.length).then((e=>n.uint8ArrayConcat([s,e]))):o<s.length?s.slice(0,o):s})).then((t=>r==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):r==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:r==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:r,refcnt:i.read16(t,0),data:t.slice(4)}))}return Promise.resolve(t)}function y(e){let t=[];for(let n of Object.keys(e))t.push(b(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=s.breakpoints,n=t[0],i=1/0;for(let r of t){let t=e-r.binAddr;t>=0&&t<i&&(i=t,n=r)}return n}function w(e){if(p)return Promise.resolve();let r;return p=!0,T().then((t=>{let o=i.decodeU32LE(e)[0],l={};for(let e of s.procDebugInfo[0].locals){let r=t.globals,s=(()=>{switch(e.type){case"uint32":return i.read32(r,e.index);case"int32":return 0|i.read32(r,e.index);case"uint16":return i.read16(r,e.index);case"int16":return i.read16(r,e.index)<<16>>16;case"uint8":return r[e.index];case"int8":return r[e.index]<<24>>24;default:return null}})();null===s&&(n.assert(0==(3&e.index)),s=m(i.read32(r,e.index))),l[e.name]=s}return c=v(o),r={type:"debugger",subtype:"breakpoint",breakpointId:c.id,globals:l,stackframes:[]},a(),h.talkAsync(1888490768)})).then((e=>{!function(e,t){let i=c.binAddr,r=0,o=s.procDebugInfo.filter((e=>e.codeStartLoc<=i&&i<=e.codeEndLoc))[0];for(;o&&o!=s.procDebugInfo[0];){let s=v(i),a=n.clone(s);a.functionName=o.name,a.argumentNames=o.args&&o.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:a,breakpointId:s.id});let l=t.stackframes[t.stackframes.length-1],c=0;for(let t of o.locals)n.assert(t.index==c++),l.locals[t.name]=m(e[r++]);i=2147483646&e[r++];let d=u[i+""];for(let t of o.args)l.locals[t.name]=m(e[r+(o.args.length-1-t.index)]);if(!d)break;o=d.from,r+=d.stack-o.localsMark}}(i.decodeU32LE(e),r);let t=[r.globals].concat(r.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(r)))}function x(){p=!1,o=new Promise(((e,t)=>{a=e}))}function k(e=!1){return Promise.resolve().then((()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3])))).then(x)}function A(){return o||(o=Promise.resolve()),o}function T(){return(l?Promise.resolve(l):h.talkAsync(1409050336).then((e=>l={numGlobals:r(e,0),globalsPtr:r(e,4)}))).then((e=>h.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:l,globals:e})))}t.taggedUndefined=0,t.taggedNull=f(1),t.taggedFalse=f(2),t.taggedTrue=f(16),t.postMessage=e=>console.log(e),t.decodeValue=m,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,s=null,l=null,Promise.resolve()).then((()=>{s=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}})).then((()=>{let e=s.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(s).then((()=>h.reconnectAsync()))})).then((()=>h.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>h.reconnectAsync())).then(x).then(A)},t.handleMessage=function(e){if(console.log("HWDBGMSG",e),"debugger"!=e.type)return;let t=!1;switch(e.subtype){case"stepinto":t=!0;case"stepover":k(t)}},t.resumeAsync=k,t.waitForHaltAsync=A,t.getHwStateAsync=T}(e.HWDBG||(e.HWDBG={}))}(pxt||(pxt={})),function(e){e.ImageConverter=class{logTime(){if(this.start){let t=Date.now()-this.start;e.debug("Icon creation: "+t+"ms")}}convert(t){this.start||(this.start=Date.now());let n=atob(t.slice(t.indexOf(",")+1)),i=n.charCodeAt(0),r=n.charCodeAt(1),s=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),r=n.charCodeAt(2)|n.charCodeAt(3)<<8,s=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(!this.palette){let t=e.appTarget.runtime.palette.map((function(e){const t=parseInt(e.replace(/#/,""),16);return[t>>0&255,t>>8&255,t>>16&255,255]}));t[0][3]=0,this.palette=new Uint8Array(4*t.length);for(let e=0;e<t.length;++e)this.palette[4*e+0]=t[e][0],this.palette[4*e+1]=t[e][1],this.palette[4*e+2]=t[e][2],this.palette[4*e+3]=t[e][3]}if(225==i)return this.genMonochrome(n,r,s);const o=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&r<100&&s<100?3:1;return this.genColor(n,r,s,o)}genMonochrome(t,n,i){let r=n+3&-4,s=54+this.palette.length,o=s+r*i,a=new Uint8Array(o);a[0]=66,a[1]=77,e.HF2.write32(a,2,o),e.HF2.write32(a,10,s),e.HF2.write32(a,14,40),e.HF2.write32(a,18,n),e.HF2.write32(a,22,-i),e.HF2.write16(a,26,1),e.HF2.write16(a,28,8),e.HF2.write32(a,38,2835),e.HF2.write32(a,42,2835),e.HF2.write32(a,46,this.palette.length>>2),a.set(this.palette,54);let l=4,c=s,u=1,d=t.charCodeAt(l++);for(let e=0;e<n;++e){c=s+e;for(let e=0;e<i;++e)a[c]=d&u?1:0,c+=r,u<<=1,256==u&&(u=1,d=t.charCodeAt(l++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(a))}genColor(t,n,i,r){const s=n*(r=Math.max(1,0|r)),o=i*r;let a=s<<2,l=138,c=l+a*o,u=new Uint8Array(c);u[0]=66,u[1]=77,e.HF2.write32(u,2,c),e.HF2.write32(u,10,l),e.HF2.write32(u,14,124),e.HF2.write32(u,18,s),e.HF2.write32(u,22,-o),e.HF2.write16(u,26,1),e.HF2.write16(u,28,32),e.HF2.write16(u,30,3),e.HF2.write32(u,38,2835),e.HF2.write32(u,42,2835),e.HF2.write32(u,54,16711680),e.HF2.write32(u,58,65280),e.HF2.write32(u,62,255),e.HF2.write32(u,66,4278190080),u[70]=66,u[71]=71,u[72]=82,u[73]=115;let d=4,h=l,p=!0;for(let e=0;e<s;e++){let n=!1;h=l+(e<<2);let s=d,c=t.charCodeAt(d++),f=n?(c>>4&15)<<2:(15&c)<<2;for(let e=0;e<o;e++)c&&(p=!1),u[h]=this.palette[f],u[h+1]=this.palette[f+1],u[h+2]=this.palette[f+2],u[h+3]=this.palette[f+3],h+=a,e%r==r-1&&(n&&(c=t.charCodeAt(d++)),n=!n,f=n?(c>>4&15)<<2:(15&c)<<2);if(p&&(u[141]=1),e%r==r-1)for(i%2||--d;3&d;)d++;else d=s}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}}}(pxt||(pxt={})),function(e){!function(t){function n(){const e={"tsconfig.json":t.TS_CONFIG,"test.ts":`// ${lf("tests go here; this will not be compiled when this package is used as an extension.")}\n`,"_config.yml":"makecode:\n target: @TARGET@\n platform: @PLATFORM@\n home_url: @HOMEURL@\ntheme: jekyll-theme-slate\ninclude:\n - assets\n - README.md\n",Makefile:"all: deploy\n\nbuild:\n\tpxt build\n\ndeploy:\n\tpxt deploy\n\ntest:\n\tpxt test\n",Gemfile:"source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins","README.md":`\n> ${lf("Open this page at {0}","[https://@REPOOWNER@.github.io/@REPONAME@/](https://@REPOOWNER@.github.io/@REPONAME@/)")}\n\n## ${lf("Use as Extension")}\n\n${lf("This repository can be added as an **extension** in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **New Project**")}\n* ${lf("click on **Extensions** under the gearwheel menu")}\n* ${lf("search for **https://github.com/@REPO@** and import")}\n\n## ${lf("Edit this project")} \n\n${lf("To edit this repository in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **Import** then click on **Import URL**")}\n* ${lf("paste **https://github.com/@REPO@** and click import")}\n\n## ${lf("Blocks preview")}\n\n${lf("This image shows the blocks code from the last commit in master.")}\n${lf("This image may take a few minutes to refresh.")}\n\n\n\n#### ${lf("Metadata (used for search, rendering)")}\n\n* for PXT/@TARGET@\n<script src="https://makecode.com/gh-pages-embed.js"><\/script><script>makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");<\/script>\n`,".gitignore":"# MakeCode\nbuilt\nnode_modules\nyotta_modules\nyotta_targets\npxt_modules\n_site\n*.db\n*.tgz\n.header.json\n.simstate.json\n",".vscode/settings.json":'{\n "editor.formatOnType": true,\n "files.autoSave": "afterDelay",\n "files.watcherExclude": {\n "**/.git/objects/**": true,\n "**/built/**": true,\n "**/node_modules/**": true,\n "**/yotta_modules/**": true,\n "**/yotta_targets": true,\n "**/pxt_modules/**": true\n },\n "files.associations": {\n "*.blocks": "html",\n "*.jres": "json"\n },\n "search.exclude": {\n "**/built": true,\n "**/node_modules": true,\n "**/yotta_modules": true,\n "**/yotta_targets": true,\n "**/pxt_modules": true\n }\n}',".github/workflows/makecode.yml":"name: MakeCode\n\non: [push]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [14.x]\n\n steps:\n - uses: actions/checkout@v1\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: build\n run: |\n pxt install\n pxt build --cloud\n env:\n CI: true\n",".github/workflows/cfg-check.yml":"name: Check pxt.json\n\non:\n push:\n branches:\n - 'master'\n - 'main'\n\njobs:\n check-cfg:\n runs-on: ubuntu-latest\n strategy:\n matrix:\n node-version: [14.x]\n steps:\n - uses: actions/checkout@v2\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: Checkout current state\n run: |\n git checkout -- .\n git clean -fd\n - name: Fix files listed in config if necessary\n run: pxt checkpkgcfg\n - name: Create Pull Request\n uses: peter-evans/create-pull-request@v3\n continue-on-error: true\n with:\n title: 'Removing missing files from pxt.json'\n commit-message: 'Removing missing files from pxt.json'\n delete-branch: true\n",".vscode/tasks.json":'\n// A task runner that calls the MakeCode (PXT) compiler\n{\n "version": "2.0.0",\n "tasks": [{\n "label": "pxt deploy",\n "type": "shell",\n "command": "pxt deploy --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt build",\n "type": "shell",\n "command": "pxt build --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt install",\n "type": "shell",\n "command": "pxt install",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt clean",\n "type": "shell",\n "command": "pxt clean",\n "group": "test",\n "problemMatcher": [ "$tsc" ]\n }]\n}\n'},n=i();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,r=e.U.clone(i.config);delete r.installedVersion,delete r.additionalFilePath,delete r.additionalFilePaths,r.preferredEditor=r.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,r.name=t,r.public=!0,r.version||(r.version="0.0.0");const s={},o=n();for(const e in o)s[e]=o[e];for(const e in i.files)"README.md"!=e&&(s[e]=i.files[e]);const a=Object.keys(s).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return r.files=a.filter((e=>!/test/.test(e))),r.testFiles=a.filter((e=>/test/.test(e))),r.supportedTargets=[e.appTarget.id],s[e.CONFIG_NAME]=e.Package.stringifyConfig(r),s},t.packageFilesFixup=function(t,n){const i=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(i,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>i[t.toLowerCase()]=e.webConfig[t])),i.platform=e.appTarget.platformid||e.appTarget.id,i.target=e.appTarget.id,i.docs=e.appTarget.appTheme.homeUrl||"./",i.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>i[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.Prefix=0]="Prefix",e[e.Postfix=1]="Postfix",e[e.Infix=2]="Infix",e[e.Block=3]="Block",e[e.NewLine=4]="NewLine"}(n=t.NT||(t.NT={})),function(e){e[e.None=0]="None",e[e.WithSpace=1]="WithSpace",e[e.NoSpace=2]="NoSpace"}(i=t.GlueMode||(t.GlueMode={}));const r=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"];function s(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function o(e){return e.length>20&&/\n/.test(e)?s(e):JSON.stringify(e)}function a(e,t,n){return{type:e,op:t,children:n}}function l(){return a(n.NewLine,"",[])}function c(e,t){return a(n.Prefix,e,t)}function u(e,t,i){return a(n.Infix,t,null==e?[i]:[e,i])}function d(e){return c(e,[])}function h(e){return a(n.Block,"",e)}function p(e){return c("",e)}function f(e,t=!1){const n=[];for(const i of e)t?(n.length>0&&n.push(d(",")),n.push(l())):n.length>0&&n.push(d(", ")),n.push(i);return t&&n.push(l()),p(n)}let m;t.backtickLit=s,t.stringLit=o,t.mkNode=a,t.mkNewLine=l,t.mkPrefix=c,t.mkPostfix=function(e,t){return a(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=h,t.mkGroup=p,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(l()),p(e)},t.mkCommaSep=f,function(t){function n(e,t,n=!1,i=!1){return p(i?[u(t[0],".",d(e)),d("("),f(t.slice(1),n),d(")")]:[d(e),d("("),f(t,n),d(")")])}function i(e,t,i,r){return n(e+"."+t,i,r)}function r(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return p([d("["),f(e,t),d("]")])},t.mkNumberLiteral=function(e){return d(e.toString())},t.mkBooleanLiteral=function(e){return d(e?"true":"false")},t.mkStringLiteral=function(e){return d(o(e))},t.mkPropertyAccess=function(e,t){return p([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,i){return n(e,t,i)},t.extensionCall=function(e,t,i){return n(e,t,i,!0)},t.namespaceCall=i,t.mathCall=function(e,t){return i("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=r,t.mkWhile=function(e,t){return p([d("while ("),e,d(")"),h(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),l()];return e.split("\n").forEach(((e,n,i)=>{e&&(t.push(d(" * "+e)),t.push(l()),n<i.length-1&&(t.push(d(" * ")),t.push(l())))})),p(t.concat([d(" */"),l()]))},t.mkAssign=function(e,t){return r("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(b([e]).output)?e:p([d("("),e,d(")")])}}(m=t.Helpers||(t.Helpers={})),t.H=m;const g={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let r=[],s={},o="",a="",l=[{}],c=0;function u(e){"string"==typeof e&&(c+=(e.match(/\n/g)||[]).length),o+=e}let h=p(t);return function t(i,r){if(i.type!=n.Infix){for(let e of i.children)t(e,-1);return}let s=[];function o(e){"P"==e[0]&&(e=e.slice(1)),s.push(d(e))}let a=e.U.lookup(g,i.op);if(null==a&&e.U.oops("bad infix op: "+i.op),a<r&&o("("),1==i.children.length)o(i.op),t(i.children[0],a),s.push(i.children[0]);else{let e,n=3!=a&&"**"!=i.op;t(i.children[0],n?a:a+.1),s.push(i.children[0]),e&&"number"!=e&&(o(": "),o(e)),"."==i.op?o("."):o(" "+i.op+" "),t(i.children[1],n?a+.1:a),s.push(i.children[1])}a<r&&o(")"),i.type=n.Prefix,i.op="",i.children=s}(h,-1),f(h),o||u("\n"),{output:o,sourceMap:r};function f(t){t.glueToBlock&&(b(),t.glueToBlock==i.WithSpace&&u(" "));let d=c,h=o.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+a);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void m(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),a+=" "," "!=o[o.length-1]&&m(" ");m("{\n");for(let e of t.children)f(e);a=a.slice(4),b(),m("\n}"+n),l.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op),t.children.forEach(f);break;case n.Postfix:t.children.forEach(f),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op)}let p=c,g=Math.max(o.length,1);if(t.id)if(s[t.id]){const e=s[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,p),e.startPos=Math.min(e.startPos,h),e.endPos=Math.max(e.endPos,g)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:g};s[t.id]=e,r.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+a))}function b(){o=o.replace(/\n *$/,(function(){return c--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const i=e[n];if("("===i)t++;else if(")"===i&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=b,t.isReservedWord=function(e){return-1!==r.indexOf(e)},t.isParenthesized=y}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];t.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",t.TILE_PREFIX="tile",t.TILE_NAMESPACE="myTiles",t.IMAGES_NAMESPACE="myImages",t.IMAGE_PREFIX="image",t.ANIMATION_NAMESPACE="myAnimations",t.ANIMATION_PREFIX="anim";class i{constructor(e,t,n=0,i=0,r){this.width=e,this.height=t,this.x0=n,this.y0=i,this.width||(this.width=16),this.height||(this.height=16),this.buf=r||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}set(e,t,n){if(e<this.width&&t<this.height&&e>=0&&t>=0){const i=this.coordToIndex(e,t);this.setCore(i,n)}}get(e,t){if(e<this.width&&t<this.height&&e>=0&&t>=0){const n=this.coordToIndex(e,t);return this.getCore(n)}return 0}copy(e=0,t=0,n=this.width,r=this.height){const s=new i(n,r);s.x0=e,s.y0=t;for(let i=0;i<n;i++)for(let n=0;n<r;n++)s.set(i,n,this.get(e+i,t+n));return s}apply(e,t=!1){let n;for(let i=0;i<e.width;i++)for(let r=0;r<e.height;r++)n=e.get(i,r),!n&&t||this.set(e.x0+i,e.y0+r,n)}equals(e){if(this.width===e.width&&this.height===e.height&&this.x0===e.x0&&this.y0===e.y0&&this.buf.length===e.buf.length){for(let t=0;t<this.buf.length;t++)if(this.buf[t]!==e.buf[t])return!1;return!0}return!1}data(){return{width:this.width,height:this.height,x0:this.x0,y0:this.y0,data:this.buf}}resize(e,t){return h(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}t.Bitmap=i;class r extends i{static fromData(e){return new r(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const s=new r(n,i);s.x0=e,s.y0=t;for(let r=0;r<n;r++)for(let n=0;n<i;n++)s.set(r,n,this.get(e+r,t+n));return s}resize(e,t){return p(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=r;class s{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(){const e=this.tilemap.copy(),t={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map((e=>Object.assign(Object.assign({},e),{bitmap:i.fromData(e.bitmap).copy().data()})))},n=i.fromData(this.layers).copy().data();return new s(e,t,n)}equals(t){if(!this.tilemap.equals(t.tilemap)||this.tileset.tileWidth!=t.tileset.tileWidth||this.tileset.tiles.length!=t.tileset.tiles.length||!y(this.layers,t.layers))return!1;for(let n=0;n<this.tileset.tiles.length;n++)if(!e.assetEquals(this.tileset.tiles[n],t.tileset.tiles[n]))return!1;return!0}}t.TilemapData=s;function o(e){return a(atob(e.slice(e.indexOf(",")+1)))}function a(t){let n=t.charCodeAt(0),i=t.charCodeAt(1),r=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),i=t.charCodeAt(2)|t.charCodeAt(3)<<8,r=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const s=new e.sprite.Bitmap(i,r);let o=4;if(225===n){let e=1,n=t.charCodeAt(o++);for(let a=0;a<i;++a)for(let i=0;i<r;++i)s.set(a,i,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(o++))}else for(let e=0;e<i;e++){for(let n=0;n<r;n+=2){let i=t.charCodeAt(o++);s.set(e,n,15&i),n!=r-1&&s.set(e,n+1,i>>4&15)}for(;3&o;)o++}return s}function l(e,t){!(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,s=x(e.substring(8));return r.fromData({width:n,height:i,x0:0,y0:0,data:s})}function c(e){return`${d(e.width,2)}${d(e.height,2)}${k(e.data().data)}`}function u(e,t){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e,t){if(0===(e=e.trim()).indexOf("img")){const n=f(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const i=t<<1;for(1&n.length&&(n="0"+n);n.length<i;)n+="0";return n}function h(e,t,n){const r=new i(t,n);return r.apply(e),r}function p(e,t,n){const i=new r(t,n);return i.apply(e),i}function f(e){const t=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),n=[];let r=0;for(let e=0;e<t.length;e++){const i=t[e],s=[];for(let e=0;e<i.length;e++)switch(i[e]){case"0":case".":s.push(0);break;case"1":case"#":s.push(1);break;case"2":case"T":s.push(2);break;case"3":case"t":s.push(3);break;case"4":case"N":s.push(4);break;case"5":case"n":s.push(5);break;case"6":case"G":s.push(6);break;case"7":case"g":s.push(7);break;case"8":s.push(8);break;case"9":s.push(9);break;case"a":case"A":case"R":s.push(10);break;case"b":case"B":case"P":s.push(11);break;case"c":case"C":case"p":s.push(12);break;case"d":case"D":case"O":s.push(13);break;case"e":case"E":case"Y":s.push(14);break;case"f":case"F":case"W":s.push(15);break;default:if(!/\s/.test(i[e]))return}s.length&&(n.push(s),r=Math.max(r,s.length))}const s=n.length,o=new i(r,s);for(let e=0;e<s;e++){const t=n[e];for(let n=0;n<r;n++)n<t.length?o.set(n,e,t[n]):o.set(n,e,0)}return o}function m(e){let t="";switch(e){case"python":t='img("""';break;default:t="img`"}return t}function g(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function b(e,t){if(!e||0===e.height||0===e.width)return"";let i=m(t);if(e){const t=e.width*e.height>300?"":" ";for(let r=0;r<e.height;r++){i+="\n";for(let s=0;s<e.width;s++)i+=n[e.get(s,r)]+t}}return i+="\n",i+=g(t),i}function y(t,n){return e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function v(e){switch(e){case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function w(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function x(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function k(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function A(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function T(e){const t=function(e){if(e){if(6===e.length)return parseInt("0x"+e);if(7===e.length)return parseInt("0x"+e.substr(1))}return 0}(e);return[E(t),C(t),S(t)]}function E(e){return e>>16&255}function C(e){return e>>8&255}function S(e){return 255&e}t.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const n=e+this.width*t,i=n>>3,r=7&n;this.mask[i]|=1<<r}get(e,t){const n=e+this.width*t,i=n>>3,r=7&n;return this.mask[i]>>r&1}},t.encodeTilemap=function(e,t){return e?`tiles.createTilemap(${function(e){return e?`hex\`${c(e)}\``:"hex``"}(e.tilemap)}, ${b(i.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t){return e.id}(e)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const r=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),o=(t=t.substr(r.length+1)).substr(0,t.indexOf(",")),a=(t=t.substr(o.length+1)).substr(0,t.lastIndexOf("]")+1),c=t=t.substr(a.length+1);return new s(l(r),{tiles:u(a,i),tileWidth:w(c)},f(o).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,i={};i[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let r=0;r<n.height;r++)i[t[n.get(e,r)].id]=!0;const r=e.editedTiles||[],s=t.filter((e=>i[e.id]||"*"===e.id.charAt(0)||-1!==r.indexOf(e.id)));if(s.length===t.length)return;const o=[];for(let e=0;e<t.length;e++)o.push(s.indexOf(t[e]));for(let e=0;e<n.width;e++)for(let t=0;t<n.height;t++)n.set(e,t,o[n.get(e,t)]);e.tileset.tiles=s},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,i=t[0].id;for(let e=0;e<n.width;e++)for(let r=0;r<n.height;r++)if(t[n.get(e,r)].id!==i)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(T),i=[0,0,0];let r=0;for(let t=0;t<e.width;t++)for(let s=0;s<e.height;s++){const o=e.get(t,s);if(o){++r;const e=n[o];i[0]+=e[0],i[1]+=e[1],i[2]+=e[2]}}return r?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(i.map((e=>Math.floor(e/r)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},t.getBitmapFromJResURL=o,t.hexToBitmap=a,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),i=t.filter((e=>0===e.indexOf("!")&&e.length>1)).map((e=>e.substring(1)));return e.filter((e=>{return t=e,n.every((e=>{const n=`?${e}`;return t.tags.some((t=>t===e||t===n))}))&&function(e){return i.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,i){let r=function(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,i);return r=r.filter((e=>e.namespace!=t.TILE_NAMESPACE)),function(t){const n=new e.ImageConverter;t.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&0==e.attributes.jresURL.indexOf("data:image/x-mkcd-f")&&(e.attributes.iconURL=n.convert(e.attributes.jresURL))}))}(r),r.map((t=>{const n=(t.attributes.tags||"").split(" ").filter((e=>!!e)).map((t=>e.Util.startsWith(t,"category-")?t:t.toLowerCase()));return{qName:t.qName,src:t.attributes.iconURL,alt:t.qName,tags:n}}))},t.base64EncodeBitmap=function(t){const n=i.fromData(t),r=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(x(r)))},t.tilemapLiteralToTilemap=l,t.hexEncodeTilemap=c,t.formatByte=d,t.resizeBitmap=h,t.resizeTilemap=p,t.imageLiteralToBitmap=f,t.encodeAnimationString=function(t,n){const i=t.map((e=>e.data)),r=new Uint8ClampedArray(8+i[0].length*i.length);A(r,0,n),A(r,2,t[0].width),A(r,4,t[0].height),A(r,6,t.length);let s=8;return i.forEach((e=>{r.set(e,s),s+=e.length})),btoa(e.sprite.uint8ArrayToHex(r))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const i of n.tiles)t.data.tileset.tiles.some((e=>e.id===i.id))||t.data.tileset.tiles.push(i),e.isAssetUsed(i,null,[t.id])&&t.data.projectReferences.push(i.id)},t.updateTilemapReferencesFromResult=function(t,n){const i=n.data;if(i.deletedTiles)for(const e of i.deletedTiles)t.deleteTile(e);if(i.editedTiles)for(const e of i.editedTiles){const n=i.tileset.tiles.findIndex((t=>t.id===e)),r=i.tileset.tiles[n];r&&(i.tileset.tiles[n]=t.updateTile(r))}for(let e=0;e<i.tileset.tiles.length;e++){const n=i.tileset.tiles[e];n.jresData||(i.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(i)},t.imageLiteralFromDimensions=function(e,t,i,r){let s=m(r);const o=e*t>300?"":" ";for(let r=0;r<t;r++){s+="\n";for(let t=0;t<e;t++)s+=n[i]+o}return s+="\n",s+=g(r),s},t.bitmapToImageLiteral=b,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=w,t.hexToUint8Array=x,t.uint8ArrayToHex=k,t.colorStringToRGB=T}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const i=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class r{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function s(e){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e){if(0===(e=e.trim()).indexOf("img")){return{data:t.imageLiteralToBitmap(e).data()}}const n=i.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=r,n.decodeTilemap=function(n,i){var o;if(!(null==(n=null===(o=e.Util.htmlUnescape(n))||void 0===o?void 0:o.trim())?void 0:n.trim()))return new r(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const a=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),l=(n=n.substr(a.length+1)).substr(0,n.indexOf(",")),c=(n=n.substr(l.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(c.length+1);return new r(t.tilemapLiteralToTilemap(a),{tiles:s(c),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(l).data())},n.tileToBlocklyVariable=function(e){return`${e.projectId};${e.data.width};${e.data.height};${pxtc.Util.toHex(e.data.data)}`},n.blocklyVariableToTile=function(e){const t=e.split(";");return 4!==t.length?null:{projectId:parseInt(t[0]),data:{width:parseInt(t[1]),height:parseInt(t[2]),data:new Uint8ClampedArray(pxtc.Util.fromHex(t[3])),x0:0,y0:0}}}}(t.legacy||(t.legacy={}))}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.items={}}removeItem(e){delete this.items[e]}getItem(e){return this.items[e]}setItem(e,t){this.items[e]=t}clear(){this.items={}}}class i{constructor(e){this.storageId=e}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach((e=>window.localStorage.removeItem(e)))}}function r(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let s;function o(){if(s)return;const t=r();let o=!1;if(!e.shell.isSandboxMode())try{window.localStorage[t]="1";window.localStorage[t];o=!0}catch(e){}o?(s=new i(t),e.debug(`storage: local under ${t}`)):(s=new n,e.debug("storage: in memory"))}t.storageId=r,t.setLocal=function(e,t){o(),s.setItem(e,t)},t.getLocal=function(e){return o(),s.getItem(e)},t.removeLocal=function(e){o(),s.removeItem(e)},t.clearLocal=function(){o(),s.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function i(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function r(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,s){if(i()){t+="-"+r();const i=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(s)}`,method:"GET",allowHttpErrors:!0});return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${s}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,s,o){if(void 0===o)return void await e.storage.shared.delAsync(t,s);let a="";if(a="object"==typeof o?JSON.stringify(o):o.toString(),i()){t+="-"+r();const i={type:"object"==typeof o?"json":"text",val:a},l=JSON.stringify(i);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(s)}`,method:"POST",data:l})}else e.storage.setLocal(`${t}:${s}`,a)},t.delAsync=async function(t,s){i()?(t+="-"+r(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(s)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${s}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i){this.id=e,this._verspec=t,this.parent=n,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every((e=>"string"==typeof e))&&n.dependencies&&Object.keys(n.dependencies).every((e=>"string"==typeof n.dependencies[e]))&&n}static getConfigAsync(t,n,i){return Promise.resolve().then((()=>{if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i);return e.packagesConfigAsync().then((n=>e.github.repoAsync(t.fullName,n))).then((n=>n?e.github.pkgConfigAsync(t.fullName,t.tag):null))}{const r=e.patching.upgradePackageReference(t,n,i),s=e.appTarget.bundledpkgs[r];return JSON.parse(s[e.CONFIG_NAME])}}))}static corePackages(){const t=e.appTarget.bundledpkgs;return Object.keys(t).map((n=>JSON.parse(t[n][e.CONFIG_NAME]))).filter((e=>!!e))}disablesVariant(e){return this.config&&this.config.disablesVariants&&this.config.disablesVariants.indexOf(e)>=0}invalid(){return/^invalid:/.test(this.version())}version(){return this.resolvedVersion||this._verspec}verProtocol(){let e=this.version().split(":");return e.length>1?e[0]:""}verArgument(){let e=this.verProtocol();return e?this.version().slice(e.length+1):this.version()}targetVersion(){return this.parent&&this.parent!=this?this.parent.targetVersion():this.config.targetVersions?this.config.targetVersions.target:void 0}commonDownloadAsync(){const t=this.verProtocol();if("pub"==t)return e.Cloud.downloadScriptFilesAsync(this.verArgument());if("github"==t)return e.packagesConfigAsync().then((t=>e.github.downloadPackageAsync(this.verArgument(),t))).then((e=>e.files));if("embed"==t){const t=e.getEmbeddedScript(this.verArgument());return Promise.resolve(t)}if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),n=ts.pxtc.Util.jsonTryParse(t);return n||e.log(`unable to find ${this.verArgument()}`),Promise.resolve(n)}return Promise.resolve(null)}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}readGitJson(){const t=this.readFile(e.github.GIT_JSON);return e.Util.jsonTryParse(t)}resolveDep(e){return this.parent.deps.hasOwnProperty(e)?this.parent.deps[e]:null}saveConfig(){const t=e.U.clone(this.config);delete t.additionalFilePaths;const n=e.Package.stringifyConfig(t);this.host().writeFile(this,e.CONFIG_NAME,n)}setPreferredEditor(e){this.config.preferredEditor!=e&&(this.config.preferredEditor=e,this.saveConfig())}getPreferredEditor(){let t=this.config.preferredEditor;if(!t){if(!(this.getFiles().indexOf(e.MAIN_BLOCKS)>=0))return e.JAVASCRIPT_PROJECT_NAME;const t=this.readFile(e.MAIN_BLOCKS),n=this.readFile(e.MAIN_TS);return!t&&n?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME}return t}parseJRes(t={}){for(const n of this.getFiles())e.U.endsWith(n,".jres")&&i(JSON.parse(this.readFile(n)),t);return t}resolveVersionAsync(){var t;let n=this._verspec;if(e.getEmbeddedScript(this.id))this.resolvedVersion=n="embed:"+this.id;else if(n&&"*"!=n){if("github"==this.verProtocol()){const i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const r=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map((t=>e.github.parseRepoId(t.version()))).filter((e=>(null==e?void 0:e.slug)===i.slug)).map((e=>e.tag)))[0];r&&(i.tag=r,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then((t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then((()=>{this.loadConfig(),e.debug(`installed ${this.id} /${t}`)}))}))}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const r=e.patching.computePatches(this.targetVersion(),"missingPackage");return r&&r.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(i=new RegExp(n,"g"))}))})),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,i={};return e.U.iterMap(this.config.dependencies,((r,s)=>{if(e.github.isGithubId(s)){const o=e.github.upgradedPackageReference(t,s);o&&o!=s&&(e.log(`upgrading dep ${r}: ${s} -> ${o}`),i[s]=o,this.config.dependencies[r]=o,n++)}})),n&&this.saveConfig(),n&&i}))}getMissingPackages(t,n){const i=e.patching.computePatches(this.targetVersion(),"missingPackage"),r={};return n&&i&&i.forEach((e=>{Object.keys(e.map).forEach((i=>{const s=new RegExp(i,"g"),o=e.map[i];n.replace(s,(e=>(t.dependencies[o]||(r[o]="*"),"")))}))})),r}findConflictsAsync(t,i){let r,s=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,i):Promise.resolve(t))).then((t=>{if(r=t,r){const t=r.yotta?e.U.jsonFlatten(r.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(r.core&&n.config.core&&r.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",r.name,n.id));return t.pkg0=n,void s.push(t)}let o=!1;if(t){const i=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!i&&!!i.yotta&&!!n.config.yotta.config){const a=e.U.jsonFlatten(i.yotta.config);for(const l of Object.keys(t)){const c=a[l],u=r.yotta.configIsJustDefaults||i.yotta.configIsJustDefaults;if(a.hasOwnProperty(l)&&c!==t[l]&&!u&&(!n.parent.config.yotta||!n.parent.config.yotta.ignoreConflicts)){const t=new e.cpp.PkgConflictError(lf("conflict on yotta setting {0} between extensions {1} and {2}",l,r.name,n.id));t.pkg0=n,t.settingName=l,s.push(t),o=!0}}}}if(!o&&r.name===n.id&&n._verspec!==i&&!/^file:/.test(n._verspec)&&!/^file:/.test(i)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),r=/^github:/.test(i)&&e.github.parseRepoId(i);if(!t||!r||t.fullName!==r.fullName||r.tag&&e.semver.strcmp(t.tag,r.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (installed: {1}, installing: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,s.push(t)}}}))}return Object.keys(r.dependencies).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,r.dependencies[t]))).then((e=>s.push.apply(s,e)))),Promise.resolve())})).then((()=>{const t=e=>{const n=[];return e.addedBy.forEach((e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))})),n},n=[];return s.forEach((s=>{n.push.apply(n,t(s.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(s.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (installed: {1}, installing: {2})",t.id,r.name,s.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",s.settingName,r.name,s.pkg0.id));return n.pkg0=t,n})))})),s.push.apply(s,n),s=s.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===s[n].pkg0.id)return!1;return!0})),s}))}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const i=JSON.stringify(this.config);for(const t in this.config.dependencies){const n=e.patching.upgradePackageReference(this.targetVersion(),t,this.config.dependencies[t]);n!=t&&(delete this.config.dependencies[t],n&&(this.config.dependencies[n]="*"))}n&&(this.config.targetVersions={target:n}),JSON.stringify(this.config)!=i&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter((t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core)));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach((t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]})))}resolvedDependencies(){return Object.keys(this.dependencies()).map((e=>this.resolveDep(e)))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,((t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}loadAsync(t=!1,i){if(this.isLoaded)return Promise.resolve();let r=Promise.resolve();0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const s=this.readFile(e.CONFIG_NAME);null==s?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):r=r.then((()=>this.parseConfig(s))),0!=this.level||t||(r=r.then((()=>this.upgradePackagesAsync().then((()=>{}))))),t&&(r=r.then((()=>this.downloadAsync()))),0==this.level&&t&&(r=r.then((()=>this.upgradePackagesAsync())).then((t=>t?(Object.keys(t).forEach((t=>e.tickEvent("package.doubleload",{extension:t}))),e.log("upgraded, downloading again"),e.debug(t),this.downloadAsync()):Promise.resolve()))),e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&(r=r.then((()=>this.patchCorePackage()))),r=r.then((()=>{if(this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")<0)return;const t=e.appTarget.simulator.boardDefinition=JSON.parse(this.readFile("board.json"));t.id=this.config.name,e.appTarget.appTheme.boardName=t.boardName||lf("board"),e.appTarget.appTheme.driveDisplayName=t.driveDisplayName||lf("DRIVE");let n=t=>{let n=/^pkg:\/\/(.*)/.exec(t);if(n){let t=n[1],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}})));const o=(t,n)=>{var i;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const r=e.github.parseRepoId(t._verspec),s=e.github.parseRepoId(n);if((null==r?void 0:r.slug)&&(null==r?void 0:r.slug)===(null==s?void 0:s.slug)){const o=(null==r?void 0:r.tag)||(null===(i=t.config)||void 0===i?void 0:i.version),a=e.semver.strcmp(o,s.tag);if(0==a)return void e.debug(`resolved version are ${o}`);if(a<0)return void e.debug(`auto-upgraded ${n} to ${o}`)}}/^file:/.test(t._verspec)||/^file:/.test(n)?e.debug("ignore file: mismatch issues"):t.configureAsInvalidPackage(lf("version mismatch"))},a=async(i,r,s=!1)=>{i||(i=r.dependencies(s)),e.debug(`deps: ${r.id}->${Object.keys(i).join(", ")}`),i=e.github.resolveMonoRepoVersions(i),e.debug(`deps: resolved ${r.id}->${Object.keys(i).join(", ")}`);for(let a of Object.keys(i)){let l=i[a]||"*";e.debug(`dep: load ${r.id}.${a}${s?"++":""}: ${l}`),"hw"==a&&e.hwVariant&&(a="hw---"+e.hwVariant);let c=r.resolveDep(a);if(c){if(c.invalid()||c._verspec===l||o(c,l),c.invalid()){c.level=Math.min(c.level,r.level+1),c.addedBy.push(r);continue}s||(c.level=Math.min(c.level,r.level+1),c.addedBy.push(r))}else{let e=new n(a,l,r.parent,r);s&&(e.cppOnly=!0),r.parent.deps[a]=e,r.parent.deps[a.replace(/---.*/,"")]=e,await e.loadAsync(t)}}};return r.then((()=>a(null,this))).then((()=>{if(this.config.palette&&e.appTarget.runtime&&(e.appTarget.runtime.palette=e.U.clone(this.config.palette),this.config.paletteNames&&(e.appTarget.runtime.paletteNames=this.config.paletteNames)),this.config.screenSize&&e.appTarget.runtime&&(e.appTarget.runtime.screenSize=e.U.clone(this.config.screenSize)),0===this.level){const t=this.readFile(e.MAIN_TS);if(!t)return Promise.resolve(null);const n=this.getMissingPackages(this.config,t);let i=!1;return Object.keys(n).reduce(((t,r)=>t.then((()=>this.findConflictsAsync(r,n[r]))).then((t=>{if(t.length){const n=t.map((e=>e.pkg0.id)).join(", "),i=t.map((e=>e.settingName)).filter((e=>!!e)).join(", ");return e.log(`skipping missing package ${r} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`),Promise.resolve(null)}{e.log(`adding missing package ${r}`),i=!0,this.config.dependencies[r]="*";const t={};return t[r]=n[r],a(t,this)}}))),Promise.resolve(null)).then((()=>(i&&(this.saveConfig(),this.validateConfig()),Promise.resolve(null))))}return Promise.resolve(null)})).then((()=>0!=this.level?Promise.resolve():Promise.all(e.U.values(this.parent.deps).map((e=>a(null,e,!0)))))).then((()=>{e.debug(` installed ${this.id}`)}))}getFiles(){let t;t=0!=this.level||this.ignoreTests?this.config.files.slice(0):this.config.files.concat(this.config.testFiles||[]);const i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const r=i=>{if("!"==(i=i.trim())[0])return!r(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const s=/^target:(\w+)$/.exec(i);return s?s[1]==e.appTarget.id||s[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},s=e.U.lookup(i,t);return!s||!s.trim()||s.split("||").some((e=>e.split("&&").every(r)))}))),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some((t=>e.U.endsWith(i,t)))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],r={},s=e.appTarget.appTheme||{};return this.config.skipLocalization?Promise.resolve(r):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map((i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`,s.crowdinBranch).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(r,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(r,this.bundledStringsForFile(t,i)))})).catch((s=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(r,this.bundledStringsForFile(t,i))}))))).then((()=>r))):(i.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(r,t))),Promise.resolve(r))}bundledStringsForFile(t,n){let i={},[r,s,o]=e.Util.normalizeLanguageCode(t);const a=this.config.files;let l=`_locales/${r}/${n}-strings.json`;return a.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):o&&(l=`_locales/${o}/${n}-strings.json`,a.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):s&&(l=`_locales/${s}/${n}-strings.json`,a.indexOf(l)>-1&&(i=JSON.parse(this.readFile(l))))),i}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let r=e[i];"string"==typeof r&&(r={data:r});let s=r.namespace||n.namespace||"";s&&(s+=".");let o=r.id||s+i,a=r.icon,l=r.mimeType||n.mimeType,c=r.dataEncoding||n.dataEncoding||"base64";a||"base64"!=c||"image/png"!=l&&"image/jpeg"!=l||(a="data:"+l+";base64,"+r.data),t[o]={id:o,data:r.data,dataEncoding:c,icon:a,namespace:s,mimeType:l,tilemapTile:r.tilemapTile,displayName:r.displayName,tileset:r.tileset}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",null,null),this._host=e,this.deps={},this.parent=this,this.addedBy=[this],this.level=0,this.deps[this.id]=this}installAllAsync(e){return this.loadAsync(!0,e)}sortedDeps(t=!1){let n={},i=[];const r=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,s=o=>{if(!o||e.U.lookup(n,o.id))return;n[o.id]=!0;const a=Object.keys(o.dependencies(t)).map((e=>this.resolveDep(e)));a.sort(((t,n)=>r(n)-r(t)||e.U.strcmp(t.id,n.id))),a.forEach(s),i.push(o.id)};return s(this),i.map((e=>this.resolveDep(e)))}localizationStringsAsync(t){const n={};return Promise.all(e.Util.values(this.deps).map((e=>e.packageLocalizationStringsAsync(t).then((e=>{e&&Object.keys(e).forEach((t=>{n[t]||(n[t]=e[t])}))}))))).then((()=>{const t=e.U.getLocalizedStrings();return Object.keys(n).forEach((i=>{(e.U.startsWith(i,"{id:subcategory}")||e.U.startsWith(i,"{id:group}"))&&(t[i]||(t[i]=n[i]))})),e.U.setLocalizedStrings(t),Promise.resolve(n)}))}getTargetOptions(){let t=e.U.clone(e.appTarget.compile);return e.U.assert(!!t),t.utf8||this.sortedDeps(!0).forEach((n=>{n.config&&n.config.utf8&&(e.debug("forcing utf8 mode: pkg="+n.id),t.utf8=!0)})),t}getJRes(){if(!this._jres){this._jres={};for(const e of this.sortedDeps())e.parseJRes(this._jres);const t=(e.appTarget.runtime&&e.appTarget.runtime.palette?e.appTarget.runtime.palette:["#000000","#ffffff"]).map((e=>("000000"+parseInt(e.replace(/#/,""),16).toString(16)).slice(-6))).join("");this._jres.__palette={id:"__palette",data:t,dataEncoding:"hex",mimeType:"application/x-palette"}}return this._jres}updateJRes(){this._jres&&this.parseJRes(this._jres)}resolveBannedCategories(){if(void 0!==this._resolvedBannedCategories)return this._resolvedBannedCategories;let t=[];return e.appTarget&&e.appTarget.runtime&&e.appTarget.runtime.bannedCategories&&e.appTarget.runtime.bannedCategories.length&&(t=e.appTarget.runtime.bannedCategories.slice(),Object.keys(this.deps).map((e=>this.deps[e])).filter((e=>!!e)).map((t=>e.Util.jsonTryParse(t.readFile(e.CONFIG_NAME)))).filter((e=>e&&e.requiredCategories)).forEach((e=>e.requiredCategories.forEach((e=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)})))),this._resolvedBannedCategories=t),this._resolvedBannedCategories=t,this._resolvedBannedCategories.length||(this._resolvedBannedCategories=null),this._resolvedBannedCategories}async getCompileOptionsAsync(t=this.getTargetOptions()){let n={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const i=(t,n)=>{this.config.files.indexOf(t)<0&&e.U.userError(lf("please add '{0}' to \"files\" in {1}",t,e.CONFIG_NAME)),n="// Auto-generated. Do not edit.\n"+n+"\n// Auto-generated. Do not edit. Really.\n",this.host().readFile(this,t,!0)!==n&&(e.debug(`updating ${t} (size=${n.length})...`),this.host().writeFile(this,t,n,!0))};let r=!1;const s=async n=>{const s={extinfo:null,target:null},o=e.appTargetVariant;n&&e.setAppTargetVariant(n,{temporary:!0});try{let a=e.cpp.getExtensionInfo(this);r||!a.shimsDTS&&!a.enumsDTS||(r=!0,a.shimsDTS&&i("shims.d.ts",a.shimsDTS),a.enumsDTS&&i("enums.d.ts",a.enumsDTS));const l=t.isNative?await this.host().getHexInfoAsync(a):null;a=e.U.flatClone(a),t.keepCppFiles||(delete a.compileData,delete a.generatedFiles,delete a.extensionFiles),a.hexinfo=l,s.extinfo=a,s.target=e.appTarget.compile}finally{n&&e.setAppTargetVariant(o,{temporary:!0})}return s};let o;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),n.target.preferredEditor=this.getPreferredEditor(),e.debug(`building: ${this.sortedDeps().map((e=>e.config.name)).join(", ")}`),o=e.appTarget.multiVariants?e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]]:[null];let a=null;for(let t of o){a&&e.debug(`building for ${t}`);const i=await s(t),r=i.extinfo;r.appVariant=t,r.outputPrefix=1!=o.length&&t?t+"-":"",a?n.otherMultiVariants.push(i):(a=r,n.otherMultiVariants=[])}n.extinfo=a;if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),i=JSON.stringify({name:this.config.name,comment:this.config.description,status:"unpublished",scriptId:this.installedVersion,cloudId:e.CLOUD_ID+e.appTarget.id,editor:this.getPreferredEditor(),targetVersions:e.appTarget.versions}),r=JSON.stringify(t),s=await e.lzmaCompressAsync(i+r);s&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:i.length,textSize:r.length,name:this.config.name,eURL:e.appTarget.appTheme.embedUrl,eVER:e.appTarget.versions?e.appTarget.versions.target:"",pxtTarget:e.appTarget.id}),n.embedBlob=ts.pxtc.encodeBase64(e.U.uint8ArrayToString(s)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let i=t;e.level>0&&(i="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(i),n.fileSystem[i]=e.readFile(t)}n.jres=this.getJRes();const l=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;return n.allowedArgumentTypes=l&&l.extraFunctionEditorTypes&&l.extraFunctionEditorTypes.map((e=>e.typeName)).concat("number","boolean","string"),n}prepareConfigToBePublished(){const t=e.U.clone(this.config);return delete t.installedVersion,delete t.additionalFilePath,delete t.additionalFilePaths,t.targetVersions||(t.targetVersions=e.Util.clone(e.appTarget.versions)),e.U.iterMap(t.dependencies,((n,i)=>{if(!i||/^(file|workspace):/.test(i)){i="*";try{const t=this.resolveDep(n).readGitJson();if(t&&t.repo){let n=e.github.parseRepoId(t.repo);n.tag=t.commit.tag||t.commit.sha,i=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=i}})),t}filesToBePublishedAsync(t=!1){const n={};return this.loadAsync().then((()=>{t||this.config.public||e.U.userError('Only packages with "public":true can be published');const i=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(i);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let i=this.readFile(t);null==i&&e.U.userError("referenced file missing: "+t),n[t]=i}return e.U.sortObjectFields(n)}))}saveToJsonAsync(){return this.filesToBePublishedAsync(!0).then((t=>({meta:{cloudId:e.CLOUD_ID+e.appTarget.id,targetVersions:e.appTarget.versions,editor:this.getPreferredEditor(),name:this.config.name},source:JSON.stringify(t,null,2)})))}compressToFileAsync(){return this.saveToJsonAsync().then((t=>e.lzmaCompressAsync(JSON.stringify(t,null,2))))}computePartDefinitions(t){if(!t||!t.length)return{};let n={};return this.sortedDeps().forEach((i=>{let r=i.readFile("pxtparts.json");if(r)try{let s=JSON.parse(r);Object.keys(s).forEach((r=>{if(t.indexOf(r)>=0){let t=n[r]=s[r];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=i.readFile(t.visual.image);n||e.reportError("parts","invalid part definition",{error:`missing visual ${t.visual.image}`}),/^data:image\/svg\+xml/.test(n)||(n="data:image/svg+xml,"+encodeURIComponent(n)),t.visual.image=n}}}))}catch(t){e.reportError("parts","invalid pxtparts.json file")}})),n}},e.inflateJRes=i,e.allPkgFiles=function(t){return[e.CONFIG_NAME].concat(t.files||[]).concat(t.testFiles||[])},e.isPkgBeta=function(e){return e&&/\bbeta\b/.test(e.description)}}(pxt||(pxt={})),function(e){!function(t){let n,i,r,s,o,a=()=>{};function l(){if(o)return o;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const r=n;t=t.then((()=>r.disconnectAsync())).then((()=>r.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{i=void 0,n=void 0,o=void 0})),a&&(t=t.then((()=>a()))),o=t}return t}t.isActive=function(){return!!n},t.isConnected=function(){return!!n&&n.io.isConnected()},t.isConnecting=function(){return!!n&&n.io.isConnecting()},t.icon=function(){var t;return!!n&&(n.icon||(null===(t=e.appTarget.appTheme.downloadDialogTheme)||void 0===t?void 0:t.deviceIcon)||"usb")},t.unsupportedParts=function(){return(null==n?void 0:n.unsupportedParts)?n.unsupportedParts():[]},t.disconnectAsync=l,t.configureEvents=function(e,t,i){a=e,r=t,s=i,n&&(n.io.onConnectionChanged=a,n.onSerial=r,n.onCustomEvent=i)},t.sendCustomEventAsync=function(e,t){return n?n.sendCustomEventAsync(e,t):Promise.resolve()},t.initAsync=function(o=!1){if(e.debug("packetio: init "+(o?"(force)":"")),!i){let c=Promise.resolve();o&&(c=c.then((()=>l()))),i=c.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=a,n=t.mkPacketIOWrapper(e),r&&(n.onSerial=r),s&&(n.onCustomEvent=s),a&&a(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{i=void 0}))}return i}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){t.computePatches=function(t,n){const i=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(!i)return;const r=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let s=[];return Object.keys(i).filter((t=>e.semver.inRange(t,r))).forEach((e=>s=s.concat(i[e]))),n&&(s=s.filter((e=>e.type==n))),s.length?s:void 0},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const r=e.patching.computePatches(t,"package");let s=n;return r&&r.forEach((e=>{Object.keys(e.map).forEach((t=>{s==t&&(s=e.map[t])}))})),s},t.patchJavaScript=function(t,n){const i=e.patching.computePatches(t);let r=n;return i&&(i.filter((e=>"api"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp(t,"g");r=r.replace(n,e.map[t])}))})),i.filter((e=>"userenum"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");r=r.replace(n,`enum ${e.map[t]} {`);const i=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");r=r.replace(i,`$1${e.map[t]}$2`)}))}))),r}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let r=0;r<t.pre.length+1;++r){let s=t.pre[r],o=n.pre[r];if(!s)return o?-1:0;if(!o)return 1;if(/^\d+$/.test(s)){if(!/^\d+$/.test(o))return-1;if(i=parseInt(s)-parseInt(o),i)return i}else{if(/^\d+$/.test(o))return 1;if(i=e.U.strcmp(s,o),i)return i}}return 0}return-1}return n?1:0}function i(t,n){let i=r(t)||r(n);return i||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),i}function r(e){if(!e)return null;if("*"===e)return{major:Number.MAX_SAFE_INTEGER,minor:Number.MAX_SAFE_INTEGER,patch:Number.MAX_SAFE_INTEGER,pre:[],build:[]};/^v\d/i.test(e)&&(e=e.slice(1));let t=/^(\d+)\.(\d+)\.(\d+)(-([0-9a-zA-Z\-\.]+))?(\+([0-9a-zA-Z\-\.]+))?$/.exec(e);return t?{major:parseInt(t[1]),minor:parseInt(t[2]),patch:parseInt(t[3]),pre:t[5]?t[5].split("."):[],build:t[7]?t[7].split("."):[]}:null}function s(e){let t=e.major+"."+e.minor+"."+e.patch;return e.pre.length&&(t+="-"+e.pre.join(".")),e.build.length&&(t+="+"+e.build.join(".")),t}function o(t,i){let s=r(t),o=r(i);return s||o?n(s,o):e.U.strcmp(t,i)}function a(e,t){let i=e.split(" - ");if(2!=i.length)return!1;let s=r(i[0]),o=r(i[1]);if(!s||!o)return!1;if(!t)return!0;const a=n(s,t),l=n(t,o);return a<=0&&l<0}t.cmp=n,t.parse=i,t.tryParse=r,t.normalize=function(e){return s(i(e))},t.stringify=s,t.majorCmp=function(e,t){let n=r(e),i=r(t);return n.major-i.major},t.strcmp=o,t.inRange=a,t.sortLatestTags=function(e){const n=e.filter((e=>!!t.tryParse(e)));return n.sort(o),n.reverse(),n},t.test=function(){console.log("Test semver");let t=["0.9.0","1.0.0-0.3.7","1.0.0-alpha","1.0.0-alpha.1","1.0.0-alpha.beta","1.0.0-beta","1.0.0-beta.2","1.0.0-beta.11","1.0.0-rc.1","1.0.0-x.7.z.92","1.0.0","1.0.1","1.9.0","1.10.0","1.11.0"];for(let r=0;r<t.length;++r){let o=i(t[r]);console.log(t[r],o),e.U.assert(s(o)==t[r]);for(let s=0;s<t.length;++s){let a=n(o,i(t[s]));console.log(t[r],t[s],a),r<s?e.U.assert(a<0):r>s?e.U.assert(a>0):e.U.assert(0==a)}}const o=r("1.2.3");e.U.assert(a("0.1.2 - 2.2.3",o)),e.U.assert(a("1.2.3 - 2.2.3",o)),e.U.assert(!a("0.0.0 - 1.2.3",o)),e.U.assert(!a("1.2.4 - 4.2.3",o)),e.U.assert(!a("0.0.0 - 0.0.1",o))}}(e.semver||(e.semver={}))}(pxt||(pxt={})),function(e){!function(e){function t(t){return e.Util.values(t.byQName).filter((e=>e.attributes.block&&/^{[^:]+:[^}]+}/.test(e.attributes.block))).forEach((e=>{e.attributes.block=e.attributes.block.replace(/^{[^:]+:[^}]+}/,"")})),t}e.assert=e.Util.assert,e.oops=e.Util.oops,e.U=e.Util,e.ON_START_TYPE="pxt-on-start",e.ON_START_COMMENT="on start",e.HANDLER_COMMENT="code goes here",e.TS_STATEMENT_TYPE="typescript_statement",e.TS_DEBUGGER_TYPE="debugger_keyword",e.TS_BREAK_TYPE="break_keyword",e.TS_CONTINUE_TYPE="continue_keyword",e.TS_OUTPUT_TYPE="typescript_expression",e.TS_RETURN_STATEMENT_TYPE="function_return",e.PAUSE_UNTIL_TYPE="pxt_pause_until",e.COLLAPSED_BLOCK="pxt_collapsed_block",e.FUNCTION_DEFINITION_TYPE="function_definition",e.BINARY_JS="binary.js",e.BINARY_ASM="binary.asm",e.BINARY_HEX="binary.hex",e.BINARY_UF2="binary.uf2",e.BINARY_ELF="binary.elf",e.BINARY_PXT64="binary.pxt64",e.BINARY_ESP="binary.bin",e.BINARY_SRCMAP="binary.srcmap",e.NATIVE_TYPE_THUMB="thumb",e.NATIVE_TYPE_VM="vm",e.BuildSourceMapHelpers=function(e,t,n){const i=e=>{const t=e.split("\n").map((e=>e.length)),n=t.reduce((({lens:e,sum:t},n)=>({lens:[...e,t+n+1],sum:t+n+1})),{lens:[],sum:0}).lens;return{posToLineCol:e=>{const i=n.reduce(((t,n,i)=>e<n?t:i+1),0);return[i,t[i]-(n[i]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},r={ts:i(t),py:i(n)},s=e=>e.endPos-e.startPos,o=(t,n)=>{const{startPos:i,endPos:r}=t;return e.filter((e=>e[n].startPos<=i&&r<=e[n].endPos))},a=(e,t)=>{const n=o(e,t);return n.reduce(((e,n)=>s(n[t])<s(e[t])?n:e),n[0])},l={ts:{allOverlaps:e=>o(e,"ts"),smallestOverlap:e=>a(e,"ts")},py:{allOverlaps:e=>o(e,"py"),smallestOverlap:e=>a(e,"py")}},c=(e,t)=>n=>{const[i,o]=(t=>[r[e].lineColToPos(t.line,t.column),t.length])(n),l=a({startPos:i,endPos:i+o},e);if(!l)return;const[c,u]=r[t].posToLineCol(l[t].startPos);return{fileName:`main.${t}`,start:l[t].startPos,length:s(l[t]),line:c,column:u}},u=c("ts","py"),d=c("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},r.ts),l.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},r.py),l.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t){if(!e.usedSymbols||!pxt.appTarget.simulator||!pxt.appTarget.simulator.parts)return[];let n=[];if(Object.keys(e.usedSymbols).forEach((t=>{let i=e.usedSymbols[t];if(i&&i.attributes.parts){let e=i.attributes.parts;if(e){e.split(/[ ,]+/).forEach((e=>{0<e.length&&n.indexOf(e)<0&&n.push(e)}))}}})),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?n=n.filter((t=>-1===e.indexOf(t))):"onlybuiltin"===t&&(n=n.filter((t=>e.indexOf(t)>=0))))}return n.sort(),n=n.reverse(),n},e.buildSimJsInfo=function(t){return{js:t.outfiles[e.BINARY_JS],targetVersion:pxt.appTarget.versions.target,fnArgs:t.usedArguments,parts:e.computeUsedParts(t,"ignorebuiltin"),usedBuiltinParts:e.computeUsedParts(t,"onlybuiltin")}},e.blocksCategory=function(t){const n=t?t.attributes.blockNamespace||t.namespace:void 0;return n?e.Util.capitalize(n.split(".")[0]):void 0},e.getBlocksInfo=function(t,n){var i,o;let a=[];const l={},c={},u={},d={},h={};function p(t,n){const i="get"==t,r="set"==t,o="number"==n.retType,d=i?c:r?l:u,h=`${n.namespace}.${n.retType}`;let p=e.U.lookup(d,h);if(!p){const l=`@${t}@`;let c,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,i=t.match(/^([^,.]*),?([^,.]*)$/);i&&3==i.length&&(c=i[1].trim(),u=i[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=c,c=""))}const f=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${c||""}`,m=`value=${u||""}`;p=d[h]={attributes:{blockId:`${o?n.namespace:h}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:i?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:l,namespace:n.namespace,fileName:n.fileName,qName:`${h}.${l}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:i?e.U.lf("the name of the property to read"):e.U.lf("the name of the property to change"),isEnum:!0,type:"@combined@"},{name:"value",description:r?e.U.lf("the new value of the property"):e.U.lf("the amount by which to change the property"),type:n.retType}].slice(0,i?1:2),retType:i?n.retType:"void",combinedProperties:[]},p.attributes.block=i?e.U.lf("%{0} %property",f):r?e.U.lf("set %{0} %property to %{1}",f,m):e.U.lf("change %{0} %property by %{1}",f,m),s(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:r?`set %${f} %property to %${m}`:`change %${f} %property by %${m}`,s(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then((e=>{p.attributes.block=e,s(p.attributes)}))),a.push(p)}p.combinedProperties.push(n.qName)}for(let n of e.Util.values(t.byQName)){if("ENUM_GET"===n.attributes.shim&&n.attributes.enumName&&n.attributes.blockId){let e=!1;if(d[n.attributes.enumName]&&(console.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(console.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(console.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(console.warn(`Enum block ${n.attributes.blockId} should specify enumInitialMembers`),e=!0),e)continue;const t=parseInt(n.attributes.enumStartValue);d[n.attributes.enumName]={blockId:n.attributes.blockId,name:n.attributes.enumName,memberName:n.attributes.enumMemberName,firstValue:isNaN(t)?void 0:t,isBitMask:n.attributes.enumIsBitMask,isHash:n.attributes.enumIsHash,initialMembers:n.attributes.enumInitialMembers,promptHint:n.attributes.enumPromptHint}}if("KIND_GET"===n.attributes.shim&&n.attributes.blockId){const i=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(h[i]){console.warn(`More than one block defined for kind ${i}`);continue}const r=[];if(t.byQName[i])for(const n of e.Util.values(t.byQName))n.namespace===i&&n.attributes.isKind&&r.push(n.name);h[i]={blockId:n.attributes.blockId,name:i,memberName:n.attributes.kindMemberName||i,initialMembers:r,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||p("get",n),n.isReadOnly||("number"==n.retType&&p("change",n),p("set",n));else if(n.attributes.block&&!n.attributes.fixedInstance&&7!=n.kind&&5!=n.kind&&9!=n.kind&&8!=n.kind){if(n.attributes.blockId||(n.attributes.blockId=n.qName.replace(/\./g,"_")),"true"==n.attributes.block){let t=e.U.uncapitalize(n.name);1!=n.kind&&2!=n.kind||(t+=" %"+n.namespace.toLowerCase());const a=null!==(o=null===(i=n.parameters)||void 0===i?void 0:i.filter((e=>!r(e))))&&void 0!==o?o:[];for(let e of a)t+=" %"+e.name;n.attributes.block=t,s(n.attributes)}a.push(n)}}for(let n of a){let i=e.U.lookup(t.byQName,n.namespace);if(!i)continue;let r=i.attributes,s=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===s[e]&&r[e]&&(s[e]=r[e])}var f;return n&&((f=n).length&&(a=a.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)})))),{apis:t,blocks:a,blocksById:pxt.Util.toDictionary(a,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let r=t.substr(n+1);return r=e.U.snakify(r).toUpperCase(),`${i}.${r}`}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,i){const r=e.Util.userLanguage();if("en"==r)return Promise.resolve(t(n));const o=r.toLowerCase(),a=o+"|jsdoc",l=o+"|block",c=await i.localizationStringsAsync(r);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(c,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==r));return await e.Util.promiseMapAll(u,(async t=>{var i,u,d;const h=t.attributes.useLoc||t.attributes.blockAliasFor,p=h&&n.byQName[h];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const f=(e,n)=>{var i,r;return c[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||p&&(c[p.qName+e]||(null===(r=p.attributes.locs)||void 0===r?void 0:r[n]))},m=f("",a);m&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=m),null===(i=t.parameters)||void 0===i||i.forEach((e=>{const t=`|param|${e.name}`,n=f(t,o+t);n&&(e.description=n)}));const g=c["{id:category}"+e.Util.capitalize(t.qName)];let b=c[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[l]);if(!b&&p){const e=c[`${p.qName}|block`]||(null===(d=p.attributes.locs)||void 0===d?void 0:d[l]);t.attributes.block===(p.attributes._untranslatedBlock||p.attributes.block)&&e&&(b=e)}if(b&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=b,b=await pxt.crowdin.inContextLoadAsync(b)),g)t.attributes.block?t.attributes.block=b||t.attributes.block:t.attributes.block=g,s(t.attributes);else if(t.attributes.block&&b){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(b,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:r,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){s(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId)return pxt.debug(`Parameter ${n.actualName} type or shadow block does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.log(`block has non matching arguments: ${n} vs ${t.attributes.block}`),pxt.reportError("loc.errors","invalid translations",{block:t.attributes.blockId,lang:r}),t.attributes.block=n,s(t.attributes))}}else s(t.attributes);t.attributes._translatedLanguageCode=r})),t(n)},e.emptyExtInfo=function(){let e=pxt.appTarget.compileService;e||(e={});const t=!!e.platformioIni,n="dockermake"==e.buildEngine||"dockercross"==e.buildEngine||"dockerespidf"==e.buildEngine,i={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?i.platformio={dependencies:{}}:n?i.npmDependencies={}:i.yotta={config:{},dependencies:{}},i};const n=["weight","imageLiteral","topblockWeight"],i=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable"];function r(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function s(e){if(e.block){const n=e.block.split("||");e._def=t(o(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(o(n[1]))),n[1]&&!e._expandedDef&&pxt.debug("Unable to parse expanded block def for id: "+e.blockId)}function t(t){return e._shadowOverrides&&t.parameters.forEach((t=>{const n=e._shadowOverrides[t.name];"unset"===n?delete t.shadowBlockId:null!=n&&(t.shadowBlockId=n)})),t}}function o(e){const t=[];let n,i=0;for(;i<e.length;i++){const r=e[i],s=i;let o;switch(r){case"*":case"_":const t=d((e=>e==r)),n="_"===r?2:0;1===t.length?o={kind:1<<n,content:t}:2===t.length?o={kind:2<<n,content:t}:3===t.length?o={kind:3<<n,content:t}:i=s;break;case"`":const a=h("`");if(void 0===a){i=s;break}o={kind:256,content:a};break;case"|":o={kind:32};break;case"\\":i<e.length-1&&(o={kind:16,content:e[1+i++]});break;case"[":const l=h("]");if(void 0!==l&&"("===e[1+i++]){const e=h(")");if(void 0!==e){o={kind:512,content:l,type:e};break}}i=s;break;case"$":case"%":const c=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(c.length>2){i=s;break}let u;if("("===e[i+1]){const e=i;++i,u=h(")"),u||(i=e)}o={kind:"$"===r?1024:64,content:c[0],type:c[1],name:u}}o?(n&&t.push({kind:128,content:n}),n=void 0,t.push(o)):n?n+=r:n=r}n&&t.push({kind:128,content:n});const r=[],s=[];let o=[],l=0,c="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=o[o.length-1];if(15&n)if(m(t[e].content),n&l)if(i&n){o.pop(),l^=n;const e=i&l|n&l;e&&o.push(e)}else p();else l|=n,o.push(n);else 144&n?c+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),r.push(n),s.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),r.push(n),s.push(n)}else 256==n?(m(),u.push({kind:"image",uri:t[e].content})):512==n?(m(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&r.push({kind:"break"})}return f(),{parts:r,parameters:s};function d(t,n=!1){let r="";for(n&&i++;i<e.length&&t(e[i]);)r+=e[i],++i;return r&&i--,r}function h(t){const n=d((e=>e!==t),!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)a(n)?(t.push({content:e,styles:0}),t.push(n),e=""):(e+=n.content,n.endingToken&&(e+=n.endingToken));u=t,e&&u.push({content:e,styles:0}),o=[],l=0}function f(){for(m(),l&&p();u.length;){const e=u.shift();if(a(e))r.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),r.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:c,styles:l,endingToken:e}),c=""}}function a(e){return!!e.kind}let l;e.parseCommentString=function(t){let r={paramDefl:{},callingConvention:0,_source:t},o=!0;for(;o;)o=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,i,s,a,l,c)=>{let u=a?JSON.parse(a):i?a||l||c:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))r.locs||(r.locs={}),r.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))r.locs||(r.locs={}),r.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){r.locs||(r.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);r.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?r.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:r.paramDefl[n.slice(0,n.length-5)]=u,r.explicitDefaults||(r.explicitDefaults=[]),r.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))r._shadowOverrides||(r._shadowOverrides={}),r._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".fieldEditor"))r.paramFieldEditor||(r.paramFieldEditor={}),r.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){r.paramFieldEditorOptions||(r.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);r.paramFieldEditorOptions[e]||(r.paramFieldEditorOptions[e]={}),r.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){r.paramShadowOptions||(r.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);r.paramShadowOptions[e]||(r.paramShadowOptions[e]={}),r.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(r.paramMin||(r.paramMin={}),r.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(r.paramMax||(r.paramMax={}),r.paramMax[n.slice(0,n.length-4)]=u):r[n]=u;return o=!0,"//% "}));for(let e of n)"string"==typeof r[e]&&(r[e]=parseInt(r[e]));for(let e of i)"string"==typeof r[e]&&(r[e]="true"==r[e]||"1"==r[e]);if(r.trackArgs&&(r.trackArgs=r.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),r.enumInitialMembers&&(r.enumInitialMembers=r.enumInitialMembers.split(/[ ,]+/)),r.blockExternalInputs&&!r.inlineInputMode&&(r.inlineInputMode="external"),r.paramHelp={},r.jsDoc="",t=t.replace(/\/\*\*([^]*?)\*\//g,((e,t)=>(t=(t=t.replace(/\n\s*(\*\s*)?/g,"\n")).replace(/^\s*@param\s+(\w+)\s+(.*)$/gm,((e,t,n)=>{if(r.paramHelp[t]=n,!r.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(n);if(e&&e[1]){let n=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(n){let e=n[1]||n[2]||n[3];e||(e=""),e.indexOf(" ")>-1?r.paramDefl[t]=`"${e}"`:r.paramDefl[t]=e}}}return""})),r.jsDoc+=t,""))),r.jsDoc=r.jsDoc.trim(),r.async&&(r.callingConvention=1),r.promise&&(r.callingConvention=2),r.jres&&(r.whenUsed=!0),r.subcategories)try{r.subcategories=JSON.parse(r.subcategories)}catch(e){r.subcategories=void 0}if(r.groups)try{r.groups=JSON.parse(r.groups)}catch(e){r.groups=void 0}if(r.groupIcons)try{r.groupIcons=JSON.parse(r.groupIcons)}catch(e){r.groupIcons=void 0}if(r.groupHelp)try{r.groupHelp=JSON.parse(r.groupHelp)}catch(e){r.groupHelp=void 0}return s(r),r},e.parameterTypeIsArrowFunction=r,e.updateBlockDef=s,e.parseBlockDefinition=o,e.parseChecksumBlock=function(e,t=0){let n=pxt.HF2.read32(e,t);if(133083260!=(2147483647&n))return pxt.log("no checksum block magic"),null;let i=pxt.HF2.read32(e,t+4),r=pxt.HF2.read32(e,t+8);if(3&i)return pxt.log("invalid end marker position"),null;let s=1<<(255&r);if(s!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+s),null;let o={magic:n,endMarkerPos:i,endMarker:r,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:s*pxt.HF2.read16(e,n),length:s*pxt.HF2.read16(e,n+2),checksum:pxt.HF2.read32(e,n+4)};if(!t.length||!t.checksum)break;o.regions.push(t)}return o},function(t){function n(n){let i=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||i(0)!=t.UF2_MAGIC_START0||i(4)!=t.UF2_MAGIC_START1||i(n.length-4)!=t.UF2_MAGIC_END)return null;let r=i(8),s=i(16);s>476&&(s=256);let o=null,a=0,l=0;if(r&t.UF2_FLAG_FILE){let t=n.slice(32+s),r=t.indexOf(0);r>=0&&(t=t.slice(0,r)),o=e.U.fromUTF8Array(t),l=i(28)}return r&t.UF2_FLAG_FAMILY_ID_PRESENT&&(a=i(28)),{flags:r,targetAddr:i(12),payloadSize:s,blockNo:i(20),numBlocks:i(24),fileSize:l,familyId:a,data:n.slice(32,32+s),filename:o}}function i(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function r(e,t,n){e[t]=255&n,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function s(e){return"string"==typeof e&&(e=parseInt(e)),{currBlock:null,currPtr:-1,blocks:[],ptrs:[],filesize:0,familyId:e||0}}function o(e){for(let t=0;t<e.blocks.length;++t)r(e.blocks[t],20,t),r(e.blocks[t],24,e.blocks.length),e.filename&&r(e.blocks[t],28,e.filesize)}function a(n,i,s,o=0){let l=n.currBlock,c=i>>8,u=256-(255&i);if(s.length>u){let e=new Uint8Array(s);for(a(n,i,e.slice(0,u));u<s.length;){let t=Math.min(u+256,s.length);a(n,i+u,e.slice(u,t)),u=t}return}if(c!=n.currPtr){l=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==c){l=n.blocks[e];break}if(!l){l=new Uint8Array(512),n.filename?o|=t.UF2_FLAG_FILE:n.familyId&&(o|=t.UF2_FLAG_FAMILY_ID_PRESENT),r(l,0,t.UF2_MAGIC_START0),r(l,4,t.UF2_MAGIC_START1),r(l,8,o),r(l,12,c<<8),r(l,16,256),r(l,20,n.blocks.length),r(l,28,n.familyId),r(l,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)l[e]=255;n.filename&&e.U.memcpy(l,288,e.U.toUTF8Array(n.filename)),n.blocks.push(l),n.ptrs.push(c)}n.currPtr=c,n.currBlock=l}let d=32+(255&i);for(let e=0;e<s.length;++e)l[d+e]=s[e];n.filesize=Math.max(n.filesize,s.length+i)}t.UF2_MAGIC_START0=171066965,t.UF2_MAGIC_START1=2656915799,t.UF2_MAGIC_END=179400496,t.UF2_FLAG_NONE=0,t.UF2_FLAG_NOFLASH=1,t.UF2_FLAG_FILE=4096,t.UF2_FLAG_FAMILY_ID_PRESENT=8192,t.parseBlock=n,t.parseFile=function(e){let t=[];for(let i=0;i<e.length;i+=512){let r=n(e.slice(i,i+512));r&&t.push(r)}return t},t.toBin=function(e,t){if(e.length<512)return null;let i=-1,r=-1,s=[];for(let o=0;o<e.length;++o){let a=512*o,l=n(e.slice(a,a+512));if(!l)continue;if(t&&l.targetAddr+256>t)break;-1==i&&(i=l.targetAddr,r=i);let c=l.targetAddr-i;c<0||c%4||c>1048576||(c>0&&s.push(new Uint8Array(c)),s.push(e.slice(a+32,a+32+l.payloadSize)),i=l.targetAddr+l.payloadSize)}let o=0;for(let e of s)o+=e.length;if(0==o)return null;let a=new Uint8Array(o),l=0;for(let e of s)for(let t=0;t<e.length;++t)a[l++]=e[t];return{buf:a,start:r}},t.readBytes=function(e,t,n){let r,s=new Uint8Array(n);for(let o=0;o<n;++o,++t)i(r,t)||(r=e.filter((e=>i(e,t)))[0]),r&&(s[o]=r.data[t-r.targetAddr]);return s},t.newBlockFile=s,t.finalizeFile=o,t.concatFiles=function(t){for(let e of t)o(e),e.filename=null;let n=s();n.blocks=e.U.concat(t.map((e=>e.blocks)));for(let e of t)e.blocks=[];return n},t.serializeFile=function(t){o(t);let n="";for(let i of t.blocks)n+=e.Util.uint8ArrayToString(i);return n},t.readBytesFromFile=function t(n,i,r){let s,o=i>>8;if(o==n.currPtr)s=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==o){s=n.blocks[e];break}s&&(n.currPtr=o,n.currBlock=s)}if(!s)return null;let a=new Uint8Array(r),l=Math.min(r,256-(255&i));e.U.memcpy(a,0,s,32+(255&i),l);let c=r-l;if(c>0){let r=t(n,i+l,c);e.U.memcpy(a,l,r)}return a},t.writeBytes=a,t.writeHex=function(e,t){let n="0000";for(let i=0;i<t.length;++i){let r=/:02000004(....)/.exec(t[i]);if(r&&(n=r[1]),r=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[i]),r){let t=parseInt(n+r[1],16),i=r[2],s=[];for(let e=0;e<i.length;e+=2)s.push(parseInt(i[e]+i[e+1],16));a(e,t,s)}}}}(l=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i;!function(e){e[e.IDE=0]="IDE",e[e.Sandbox=1]="Sandbox",e[e.Widget=2]="Widget",e[e.Controller=3]="Controller"}(n=t.EditorLayoutType||(t.EditorLayoutType={}));let r=!1,s=!1;function o(){if(void 0===i){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),o=/nosandbox=1/i.test(window.location.href),a=/controller=1/i.test(window.location.href)&&e.BrowserUtils.isIFrame(),l=/readonly=1/i.test(window.location.href),c=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),u=/noproject=1/i.test(window.location.href);if(i=n.IDE,o?i=n.Widget:a?i=n.Controller:t&&(i=n.Sandbox),a&&l&&(r=!0),a&&u&&(s=!0),c)switch(c[1].toLowerCase()){case"widget":i=n.Widget;break;case"sandbox":i=n.Sandbox;break;case"ide":i=n.IDE}}else i=n.Sandbox;e.debug(`shell: layout type ${n[i]}, readonly ${l()}`)}}function a(){return o(),i==n.Sandbox}function l(){return!e.BrowserUtils.hasWindow()||a()&&!/[?&]edit=1/i.test(window.location.href)||c()&&r}function c(){return o(),i==n.Controller}t.layoutTypeClass=function(){return o(),e.shell.EditorLayoutType[i].toLowerCase()},t.isSandboxMode=a,t.isReadOnly=l,t.isNoProject=function(){return s},t.isControllerMode=c,t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,((e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))}))}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then((e=>e.map((e=>e.project)).filter((e=>!e.deleted))))}deleteProjectAsync(e){return this.getProjectAsync(e).then((e=>{e.deleted=!0,this.saveProjectAsync(e)}))}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then((e=>{var t;return null===(t=e)||void 0===t?void 0:t.project}))}saveProjectAsync(e){return this.db.setAsync(n.projectTable,{id:e.header.id,project:e})}getUserStateAsync(){return this.db.getAsync(n.userTable,"local-user").then((e=>{var t;return null===(t=e)||void 0===t?void 0:t.user}))}saveUserStateAsync(e){return this.db.setAsync(n.userTable,{id:"local-user",user:e})}}n.version=6,n.databaseName="local-skill-map",n.projectTable="projects",n.projectKey="id",n.userTable="users",n.userKey="id",t.IndexedDBWorkspace=n}(e.skillmap||(e.skillmap={}))}(pxt||(pxt={})),function(e){!function(t){t.createStreamAsync=function(t,n){return e.Cloud.privatePostAsync("streams",{target:t,name:n||"data"}).then((e=>e))},t.postPayloadAsync=function(t,n){return e.Util.assert(!!t.privatekey),e.Cloud.privatePostAsync(`${t.id}/data?privatekey=${t.privatekey}`,n)}}(e.streams||(e.streams={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class r{constructor(e){this.el=A(e)}attr(e){return Object.keys(e).forEach((t=>{this.setAttribute(t,e[t])})),this}setAttribute(e,t){return this.el.setAttribute(e,t.toString()),this}setAttributeNS(e,t,n){return this.el.setAttributeNS(e,t,n.toString()),this}id(e){return this.setAttribute("id",e)}setClass(...e){return this.setAttribute("class",e.join(" "))}appendClass(t){return e.BrowserUtils.addClass(this.el,t),this}removeClass(t){e.BrowserUtils.removeClass(this.el,t)}title(e){this.titleElement||(this.titleElement=A("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=r;class s extends r{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new g;case"path":return new y;default:return new u(e)}}(e);return this.el.appendChild(t.el),t}element(e,t){return t(this.draw(e)),this}group(){const e=new o;return this.el.appendChild(e.el),e}appendChild(e){this.el.appendChild(e.el)}onDown(e){return t.events.down(this.el,e),this}onUp(e){return t.events.up(this.el,e),this}onMove(e){return t.events.move(this.el,e),this}onEnter(e){return t.events.enter(this.el,e),this}onLeave(e){return t.events.leave(this.el,e),this}onClick(e){return t.events.click(this.el,e),this}}t.DrawContext=s;t.SVG=class extends s{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new l(this.el)),e(this.defs),this}};class o extends s{constructor(e){super("g"),e&&e.appendChild(this.el)}translate(e,t){return this.left=e,this.top=t,this.updateTransform()}scale(e){return this.scaleFactor=e,this.updateTransform()}def(){return new l(this.el)}style(){return new c(this.el)}updateTransform(){let e="";return null!=this.left&&(e+=`translate(${this.left} ${this.top})`),null!=this.scaleFactor&&(e+=` scale(${this.scaleFactor})`),this.setAttribute("transform",e),this}}t.Group=o;class a extends s{constructor(){super("pattern")}units(e){return this.setAttribute("patternUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}contentUnits(e){return this.setAttribute("patternContentUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}size(e,t){return this.setAttribute("width",e),this.setAttribute("height",t),this}}t.Pattern=a;class l extends r{constructor(e){super("defs"),e.appendChild(this.el)}create(e,t){let n;switch(e){case"path":n=new y;break;case"pattern":n=new a;break;case"radialGradient":n=new x;break;case"linearGradient":n=new w;break;case"clipPath":n=new k;break;default:n=new r(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=l;class c extends r{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=c;class u extends s{at(e,t){return this.setAttribute("x",e),this.setAttribute("y",t),this}moveTo(e,t){return this.at(e,t)}fill(e,t){return this.setAttribute("fill",e),null!=t&&this.opacity(t),this}opacity(e){return this.setAttribute("fill-opacity",e)}stroke(e,t){return this.setAttribute("stroke",e),null!=t&&this.strokeWidth(t),this}strokeWidth(e){return this.setAttribute("stroke-width",e)}strokeOpacity(e){return this.setAttribute("stroke-opacity",e)}clipPath(e){return this.setAttribute("clip-path",e)}}t.Drawable=u;class d extends u{constructor(e){super("text"),null!=e&&this.text(e)}text(e){return this.el.textContent=e,this}fontFamily(e){return this.setAttribute("font-family",e)}fontSize(e,t){return this.setAttribute("font-size",E(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",E(e,n)),0!==t&&this.setAttribute("dy",E(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class h extends u{constructor(){super("rect")}width(e,t=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}corner(e){return this.corners(e,e)}corners(e,t){return this.setAttribute("rx",e),this.setAttribute("ry",t),this}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}}t.Rect=h;class p extends u{constructor(){super("circle")}at(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}radius(e){return this.setAttribute("r",e)}}t.Circle=p;class f extends u{constructor(){super("line")}at(e,t,n,i){return this.from(e,t),null!=n&&null!=i&&this.to(n,i),this}from(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}to(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.Line=f;class m extends u{points(e){return this.setAttribute("points",e)}with(e){return this.points(e.map((({x:e,y:t})=>e+" "+t)).join(","))}}t.PolyElement=m;class g extends m{constructor(){super("polyline")}}t.Polyline=g;class b extends m{constructor(){super("polygon")}}t.Polygon=b;class y extends u{constructor(){super("path"),this.d=new T}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}}t.Path=y;t.Image=class extends u{constructor(){super("image")}src(e){return this.setAttributeNS("http://www.w3.org/1999/xlink","href",e)}width(e,t=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}};class v extends r{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const i=A("stop");return i.setAttribute("offset",e+"%"),null!=t&&i.setAttribute("stop-color",t),null!=n&&i.setAttribute("stop-opacity",n),this.el.appendChild(i),this}}t.Gradient=v;class w extends v{constructor(){super("linearGradient")}start(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}end(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.LinearGradient=w;class x extends v{constructor(){super("radialGradient")}center(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}focus(e,t,n){return this.setAttribute("fx",e),this.setAttribute("fy",t),this.setAttribute("fr",n),this}radius(e){return this.setAttribute("r",e)}}t.RadialGradient=x;class k extends s{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function A(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=k;class T{constructor(){this.ops=[]}clear(){this.ops=[]}moveTo(e,t){return this.op("M",e,t)}moveBy(e,t){return this.op("m",e,t)}lineTo(e,t){return this.op("L",e,t)}lineBy(e,t){return this.op("l",e,t)}cCurveTo(e,t,n,i,r,s){return this.op("C",e,t,n,i,r,s)}cCurveBy(e,t,n,i,r,s){return this.op("c",e,t,n,i,r,s)}qCurveTo(e,t,n,i){return this.op("Q",e,t,n,i)}qCurveBy(e,t,n,i){return this.op("q",e,t,n,i)}sCurveTo(e,t,n,i){return this.op("S",e,t,n,i)}sCurveBy(e,t,n,i){return this.op("s",e,t,n,i)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,i,r,s,o){return this.op("A",e,t,n,i?1:0,r?1:0,s,o)}arcBy(e,t,n,i,r,s,o){return this.op("a",e,t,n,i?1:0,r?1:0,s,o)}close(){return this.op("z")}toAttribute(){return this.ops.map((e=>e.op+" "+e.args.join(" "))).join(" ")}op(e,...t){return this.ops.push({op:e,args:t}),this}}function E(e,t){switch(t){case i.em:return e+"em";case i.ex:return e+"ex";case i.px:return e+"px";case i.in:return e+"in";case i.cm:return e+"cm";case i.mm:return e+"mm";case i.pt:return e+"pt";case i.pc:return e+"pc";case i.percent:return e+"%";default:return e.toString()}}t.PathContext=T}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.isTouchEnabled=t,e.hasPointerEvents=n,e.down=function(e,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",(e=>{i(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{i(!0)})):e.addEventListener("mouseover",(e=>{i(!!(1&e.buttons))}))},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation";class t{constructor(){this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=o(e);return this.takenNames[t.id]=!0,this.takenNames[u(t)]=!0,t.meta.displayName&&t.meta.displayName!==t.id&&(this.takenNames[t.meta.displayName]&&(t.meta.displayName=this.generateNewDisplayName(t.meta.displayName)),this.takenNames[t.meta.displayName]=!0),this.assets.push(t),o(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(o):this.assets.map(o)}update(e,t){let n;if(this.takenNames[e]){l(this.lookupByID(e),t)?n=t:(this.removeByID(e),n=this.add(t),this.notifyListener(t.internalID))}else n=this.add(t);return n}removeByID(e){const t=this.lookupByID(e);this.assets=this.assets.filter((t=>t.id!==e)),delete this.takenNames[e],t&&delete this.takenNames[u(t)],(null==t?void 0:t.meta.displayName)&&delete this.takenNames[null==t?void 0:t.meta.displayName]}getByID(e){const t=this.lookupByID(e);return t&&o(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||u(t)===e)return o(t)}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t;return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={}){for(const t of this.assets)a(t,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter((t=>t.callback!==e))}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&l(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter((e=>!n[e.internalID])))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,r=n?t.before:t.after;e.Util.assert(i.length===r.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),r[e]&&this.assets.push(r[e]),this.notifyListener(i[e].internalID)):(this.assets.push(r[e]),this.notifyListener(r[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[u(t)]=!0,t.meta.displayName&&(t.meta.displayName!==t.id&&e.Util.assert(!this.takenNames[t.meta.displayName]),this.takenNames[t.meta.displayName]=!0)}lookupByID(e){for(const t of this.assets)if(t.id===e)return t;return null}lookupByInternalID(e){for(const t of this.assets)if(t.internalID===e)return t;return null}removeByInternalID(e){this.assets=this.assets.filter((t=>t.internalID!==e))}notifyListener(e){for(const t of this.listeners)t.internalID===e&&t.callback()}generateNewDisplayName(e){e=e.replace(/\d+$/,"");let t=0;for(;this.takenNames[e+t];)++t;return e+t}}function n(t){const n=[];for(const i of Object.keys(t)){const r=t[i];r.mimeType===e.TILEMAP_MIME_TYPE&&n.push(r)}return n}function i(e,t){return`\n helpers._registerFactory("${e}", function(name: string) {\n switch(helpers.stringTrim(name)) {\n`+t.map((e=>e.keys.filter((e=>!!e)).map((e=>` case "${e}":`)).join("\n")+`return ${e.expression};`)).join("\n")+"\n }\n return null;\n })\n"}function r(t){return e.sprite.Bitmap.fromData(t).copy().data()}function s(t,n){const i=atob(t.data),r=e.U.fromHex(i),s=r[1]|r[2]<<8,o=r[3]|r[4]<<8,a={tileWidth:r[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},l=r.slice(5,5+s*o),c=new e.sprite.Tilemap(s,o,0,0,new Uint8ClampedArray(l)),u=r.slice(5+l.length),d=new e.sprite.Bitmap(s,o,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(c,a,d)}function o(e){switch(e.meta=Object.assign({},e.meta),e.type){case"tile":case"image":return Object.assign(Object.assign({},e),{bitmap:r(e.bitmap)});case"animation":return Object.assign(Object.assign({},e),{frames:e.frames.map((e=>r(e)))});case"tilemap":return Object.assign(Object.assign({},e),{data:e.data.cloneData()})}}function a(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1);switch(t.type){case"image":n[i]=t.jresData,t.meta.displayName&&(n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,displayName:t.meta.displayName});break;case"tile":n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};break;case"tilemap":const r=function(t,n,i){const r=t.tilemap.data(),s=new Uint8ClampedArray(5+r.data.length+t.layers.data.length);return s[0]=t.tileset.tileWidth,s[1]=255&r.width,s[2]=r.width>>8&255,s[3]=255&r.height,s[4]=r.height>>8&255,s.set(r.data,5),s.set(t.layers.data,5+r.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(s)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:i}}(t.data,t.id,t.meta.displayName);n[r.id]=r;break;case"animation":n[i]=function(t){return{namespace:t.id.substr(0,t.id.lastIndexOf(".")),id:t.id.substr(t.id.lastIndexOf(".")+1),mimeType:e.ANIMATION_MIME_TYPE,data:e.sprite.encodeAnimationString(t.frames,t.interval),displayName:t.meta.displayName}}(t)}}function l(t,n){if(t==n)return!0;if(t.id!==n.id||t.type!==n.type||!e.U.arrayEquals(t.meta.tags,n.meta.tags)||!e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)||t.meta.displayName!==n.meta.displayName)return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data)}}function c(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap))|(tilemap))\s*(?:`|\(""")([^`"]+)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function u(e){return d(e.type,e.id)}function d(t,n,i=!1){let r;switch(t){case"image":r=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":r=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":r="";break;case"animation":r=e.sprite.ANIMATION_NAMESPACE+"."}if(r)if(n.startsWith(r)){const e=n.substr(r.length);if(-1===e.indexOf("."))return e}else if(!i)return null;return n}function h(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),r=p(i,0),s=p(i,2),o=p(i,4),a=p(i,6),l=Math.ceil(s*o/2);let c=8;const u=[];for(let e=0;e<a;e++){const e=i.slice(c,c+l);u.push({x0:0,y0:0,width:s,height:o,data:e}),c+=l}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:r,frames:u,meta:{displayName:t.displayName}}}function p(e,t){return e[t]|e[t+1]<<8}e.TilemapProject=class{constructor(){this.needsRebuild=!0,this.nextID=0,this.nextInternalID=0,this.committedState={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.state={revision:this.nextID++,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.gallery={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){const i=this.generateNewID("image"),r=new e.sprite.Bitmap(t,n).data(),s={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:r,meta:{},jresData:e.sprite.base64EncodeBitmap(r)};return this.state.images.add(s)}createNewAnimation(t=16,n=16){const i=this.generateNewID("animation"),r=new e.sprite.Bitmap(t,n).data(),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[r],interval:500,meta:{}};return this.state.animations.add(s)}createNewAnimationFromData(e,t=500,n){const i=this.generateNewID("animation"),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(r)}getGalleryTiles(e){return this.extensionTileSets?this.extensionTileSets.map((t=>t.tileSets.find((t=>t.tileWidth===e)))).filter((e=>null==e?void 0:e.tiles.length)):null}getProjectImages(){return this.state.images.getSnapshot()}getProjectTiles(t,n){const i=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===i.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:i}}createNewTile(t,n,i){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const r={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:i},isProjectTile:!0};return this.state.tiles.add(r)}createNewProjectImage(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(i)}updateTile(t){this.onChange();const n=this.resolveProjectTileByInternalID(t.internalID);if(n){if(this.state.tiles.update(n.id,t),n.id!==t.id||!e.sprite.bitmapEquals(n.bitmap,t.bitmap))for(const e of this.getAssets("tilemap"))e.data.tileset.tiles.some((e=>e.internalID===t.internalID))&&(e.data.tileset.tiles=e.data.tileset.tiles.map((e=>e.internalID===t.internalID?t:e)),this.updateTilemap(e.id,e.data));return t}return null}deleteTile(e){this.onChange(),this.state.tiles.removeByID(e)}getProjectTilesetJRes(){const t={};return this.state.tiles.serializeToJRes(t),this.state.tilemaps.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.TILE_NAMESPACE},t}getProjectAssetsJRes(){const t={};return this.state.images.serializeToJRes(t),this.state.animations.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.IMAGES_NAMESPACE},t}getTilemap(e){return this.state.tilemaps.getByID(e)}updateTilemap(e,t){const n=this.state.tilemaps.getByID(e);if(n){this.onChange();const i=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,i),i}return null}createNewTilemap(e,t,n=16,i=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,i),e)}blankTilemap(t,n=16,i=16){const r=new e.sprite.Tilemap(n,i),s=new e.sprite.Bitmap(n,i),o={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(r,o,s.data())}resolveTile(e){return this.lookupAsset("tile",e)}resolveProjectTileByInternalID(e){return this.state.tiles.getSnapshot((t=>t.internalID===e))[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.state.tiles.getSnapshot((e=>e.jresData===n))[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.state.tiles.getByID(n);if(!i){const r=new e.sprite.Bitmap(t,t).data();return i={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:r,jresData:e.sprite.base64EncodeBitmap(r),meta:{},isProjectTile:!0},this.state.tiles.add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.state.tilemaps.add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName:n},data:e}),[n,e]}cloneState(){return{revision:this.state.revision,images:this.state.images.clone(),tilemaps:this.state.tilemaps.clone(),animations:this.state.animations.clone(),tiles:this.state.tiles.clone()}}undo(){if(this.state.revision!==this.committedState.revision&&this.pushUndo(),this.undoStack.length){const e=this.undoStack.pop();this.state.tiles.applyDiff(e.tiles,!0),this.state.images.applyDiff(e.images,!0),this.state.tilemaps.applyDiff(e.tilemaps,!0),this.state.animations.applyDiff(e.animations,!0),this.state.revision=e.beforeRevision,this.redoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}redo(){if(this.redoStack.length){const e=this.redoStack.pop();this.state.tiles.applyDiff(e.tiles),this.state.images.applyDiff(e.images),this.state.tilemaps.applyDiff(e.tilemaps),this.state.animations.applyDiff(e.animations),this.state.revision=e.afterRevision,this.undoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}pushUndo(){this.undoStack.length&&this.committedState.revision===this.state.revision||(this.redoStack=[],this.undoStack.push({beforeRevision:this.committedState.revision,afterRevision:this.state.revision,tiles:this.state.tiles.diff(this.committedState.tiles),images:this.state.images.diff(this.committedState.images),tilemaps:this.state.tilemaps.diff(this.committedState.tilemaps),animations:this.state.animations.diff(this.committedState.animations)}),this.committedState=this.cloneState(),this.cleanupTemporaryAssets())}revision(){return this.state.revision}encodeTilemap(t,n){const i=t.tilemap.data(),r=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return r[0]=t.tileset.tileWidth,r[1]=255&i.width,r[2]=i.width>>8&255,r[3]=255&i.height,r[4]=i.height>>8&255,r.set(i.data,5),r.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(r)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>{switch(e){case"image":return this.state.images.isIDTaken(t)||this.gallery.images.isIDTaken(t);case"tile":return this.state.tiles.isIDTaken(t)||this.gallery.tiles.isIDTaken(t);case"tilemap":return this.state.tilemaps.isIDTaken(t)||this.gallery.tilemaps.isIDTaken(t);case"animation":return this.state.animations.isIDTaken(t)||this.gallery.animations.isIDTaken(t)}},i=d(e,t),r=i&&i!==t;return n(t)||r&&n(i)}isAssetUsed(t,n,i){var r,s,o;if(((null===(s=null===(r=t.meta)||void 0===r?void 0:r.blockIDs)||void 0===s?void 0:s.filter((e=>!i||(null==i?void 0:i.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==i?void 0:i.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const r=e.Util.escapeForRegex(u(t)),s=e.Util.escapeForRegex(null===(o=t.meta)||void 0===o?void 0:o.displayName)||"";let a;switch(t.type){case"tile":a=`myTiles.${r}|assets.tile\`${r}\``,s&&(a+=`|assets.tile\`${s}\``);break;case"tilemap":a=`tilemap\`${r}\``;break;case"animation":a=`assets.animation\`${r}\``,s&&(a+=`|assets.animation\`${s}\``);break;default:a=`assets.image\`${r}\``,s&&(a+=`|assets.image\`${s}\``)}const l=new RegExp(a,"gm");let c;switch(t.type){case"tile":c=`myTiles.${r}|assets.tile("""${r}""")`,s&&(c+=`|assets.tile("""${s}""")`);break;case"tilemap":c=`assets.tilemap("""${r}""")`;break;case"animation":c=`assets.animation("""${r}""")`,s&&(c+=`|assets.animation("""${s}""")`);break;default:c=`assets.image("""${r}""")`,s&&(c+=`|assets.image("""${s}""")`)}const d=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(d))return!0}}return!1}lookupAsset(e,t){switch(e){case"image":return this.state.images.getByID(t)||this.gallery.images.getByID(t);case"tile":return this.state.tiles.getByID(t)||this.gallery.tiles.getByID(t);case"tilemap":return this.state.tilemaps.getByID(t)||this.gallery.tilemaps.getByID(t);case"animation":return this.state.animations.getByID(t)||this.gallery.animations.getByID(t)}}lookupAssetByName(e,t){switch(e){case"image":return this.state.images.getByDisplayName(t);case"tile":return this.state.tiles.getByDisplayName(t);case"tilemap":return this.state.tilemaps.getByDisplayName(t);case"animation":return this.state.animations.getByDisplayName(t)}}getAssets(e){switch(e){case"image":return this.state.images.getSnapshot();case"tile":return this.state.tiles.getSnapshot();case"tilemap":return this.state.tilemaps.getSnapshot();case"animation":return this.state.animations.getSnapshot()}}getGalleryAssets(e){switch(e){case"image":return this.gallery.images.getSnapshot();case"tile":return this.gallery.tiles.getSnapshot();case"tilemap":return this.gallery.tilemaps.getSnapshot();case"animation":return this.gallery.animations.getSnapshot()}}lookupBlockAsset(e,t){let n=e=>{var n,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.indexOf(t))};switch(e){case"image":return this.state.images.getSnapshot(n)[0];case"tile":return this.state.tiles.getSnapshot(n)[0];case"tilemap":return this.state.tilemaps.getSnapshot(n)[0];case"animation":return this.state.animations.getSnapshot(n)[0]}}updateAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.update(e.id,e);case"tile":return this.updateTile(e);case"tilemap":return this.state.tilemaps.update(e.id,e);case"animation":return this.state.animations.update(e.id,e)}}duplicateAsset(e,t){var n;this.onChange();const i=o(e),r=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let s;switch(e.type){case"image":s=this.createNewProjectImage(i.bitmap,r);break;case"tile":s=this.createNewTile(i.bitmap,null,r);break;case"tilemap":const[e,t]=this.createNewTilemapFromData(i.data,r);s=this.getTilemap(e);break;case"animation":s=this.createNewAnimationFromData(i.frames,i.interval,r)}return s}removeAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.removeByID(e.id);case"tile":return this.state.tiles.removeByID(e.id);case"tilemap":return this.state.tilemaps.removeByID(e.id);case"animation":return this.state.animations.removeByID(e.id)}}addChangeListener(e,t){switch(e.type){case"image":this.state.images.addListener(e.internalID,t);break;case"tile":this.state.tiles.addListener(e.internalID,t);break;case"tilemap":this.state.tilemaps.addListener(e.internalID,t);break;case"animation":this.state.animations.addListener(e.internalID,t)}}removeChangeListener(e,t){switch(e){case"image":this.state.images.removeListener(t);break;case"tile":this.state.tiles.removeListener(t);break;case"tilemap":this.state.tilemaps.removeListener(t);break;case"animation":this.state.animations.removeListener(t)}}loadPackage(e){const t=e.sortedDeps();this.extensionTileSets=[];for(const e of t){const t="this"===e.id,n=this.readImages(e.parseJRes(),t);for(const e of n)"tile"===e.type?t?this.state.tiles.add(e):this.gallery.tiles.add(e):"image"===e.type?t?this.state.images.add(e):this.gallery.images.add(e):t?this.state.animations.add(e):this.gallery.animations.add(e)}for(const t of n(e.parseJRes()))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:t.id,meta:{displayName:t.displayName||t.id},data:s(t,(e=>this.resolveTile(e)))});this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,i=!1){t=e.inflateJRes(t);const r=this.readImages(t,!0).filter((e=>"tile"===e.type));let o={};for(const e of r){if(i){const t=this.resolveTileByBitmap(e.bitmap);if(t){o[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(o[e.id]=t.id)}for(const e of n(t))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:s(e,(e=>(o[e]&&(e=o[e]),this.resolveTile(e))))})}loadAssetsJRes(t){t=e.inflateJRes(t);const n=[];for(const i of Object.keys(t)){const r=t[i];if(r.tilemapTile)this.state.tiles.add(this.generateImage(r,"tile"));else if(r.mimeType===e.IMAGE_MIME_TYPE)this.state.images.add(this.generateImage(r,"image"));else if(r.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(r);t?n.push(e):this.state.animations.add(e)}}for(const e of n)this.state.animations.add(this.inflateAnimation(e,this.state.images.getSnapshot()))}removeInactiveBlockAssets(e){function t(t){const n=t.getSnapshot((t=>{var n;return!t.meta.displayName&&(null===(n=t.meta.blockIDs)||void 0===n?void 0:n.some((t=>-1===e.indexOf(t))))})),i=[];for(const t of n)1===t.meta.blockIDs.length?i.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&i.push(t));for(const e of i)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations)}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).data()}}generateAnimation(e){if("json"===e.dataEncoding){let t;try{t=JSON.parse(e.data)}catch(t){console.warn("could not parse json data of '"+e.id+"'")}return[{internalID:this.getNewInternalId(),type:"animation",meta:{displayName:e.displayName},id:e.id,frames:[],frameIds:t.frames,interval:100,flippedHorizontal:t.flippedHorizontal},!0]}return[Object.assign(Object.assign({},h(e)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map((e=>n.find((t=>t.id===e)).bitmap)),t.flippedHorizontal&&(t.frames=t.frames.map((t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()}))),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"))}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const i=n?n+"."+t:t;let r=1;for(;this.isNameTaken(e,i+r);)++r;return i+r}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const i=[],r=[];for(const s of Object.keys(t)){const o=t[s];if(o.tilemapTile){const e=this.generateImage(o,"tile");e.isProjectTile=n,i.push(e)}else if(o.mimeType===e.IMAGE_MIME_TYPE)i.push(this.generateImage(o,"image"));else if(o.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(o);t?r.push(e):i.push(e)}}for(const e of r)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.state.images.getSnapshot((e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)}));for(const t of e)this.state.images.removeByID(t.id)}},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let r="";const o=[],a=[];for(const i of n){if("*"===i)continue;const n=t[i];if(n.tilemapTile&&(r+=" //% fixedInstance jres blockIdentity=images._tile\n",r+=` export const ${i} = image.ofBuffer(hex\`\`);\n`,a.push({keys:[n.displayName,d("tile",i,!0)],expression:i})),n.mimeType===e.TILEMAP_MIME_TYPE){const t=s(n);o.push({keys:[n.displayName,d("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}o.length&&(r+=i("tilemap",o)),a.length&&(r+=i("tile",a));const l=lf("Auto-generated code. Do not edit.");return`// ${l}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${r}\n}\n// ${l}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let r="";const s=[],o=[];for(const i of n){if("*"===i)continue;const n=t[i];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,r=[d("image",i,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),r.push(n.displayName)),s.push({keys:r,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=h(n);o.push({keys:[n.displayName,d("animation",i,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}}const a=lf("Auto-generated code. Do not edit.");return r+=i("image",s),r+=i("animation",o),`// ${a}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${r}\n}\n// ${a}\n`},e.cloneAsset=o,e.assetEquals=l,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:u(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const r=t?'("""':"`",s=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${r}${i}${s}`;case"image":return`assets.image${r}${i}${s}`;case"animation":return`assets.animation${r}${i}${s}`;case"tilemap":return`tilemap${r}${i}${s}`}},e.parseAssetTSReference=c,e.lookupProjectAssetByTSReference=function(e,t){const n=c(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i)}}},e.getDefaultAssetDisplayName=function(e){switch(e){case"image":return lf("myImage");case"tile":return lf("myTile");case"tilemap":return lf("level");case"animation":return lf("myAnim");default:return lf("asset")}},e.getShortIDForAsset=u}(pxt||(pxt={})),function(e){!function(t){t.blockColors={loops:"#107c10",logic:"#006970",math:"#712672",variables:"#A80000",functions:"#005a9e",text:"#996600",arrays:"#A94400",advanced:"#3c3c3c",addpackage:"#717171",search:"#000",debug:"#e03030",default:"#dddddd",topblocks:"#aa8f00",recipes:"#717171"},t.blockIcons={loops:"",logic:"",math:"",variables:"",functions:"",text:"",arrays:"",advancedcollapsed:"",advancedexpanded:"",more:"",addpackage:"",search:"",debug:"",default:"",topblocks:"",recipes:""};let n="";function i(e){const t=function(e,t,n){let i=0,r=0,s=0;if(0==t)i=n,r=n,s=n;else{let o=Math.floor(e/60),a=e/60-o,l=n*(1-t),c=n*(1-t*a),u=n*(1-t*(1-a));switch(o){case 1:i=c,r=n,s=l;break;case 2:i=l,r=n,s=u;break;case 3:i=l,r=c,s=n;break;case 4:i=u,r=l,s=n;break;case 5:i=n,r=l,s=c;break;case 6:case 0:i=n,r=u,s=l}}return[Math.floor(i),Math.floor(r),Math.floor(s)]}(e,.45,165.75);return`#${r(t[0])}${r(t[1])}${r(t[2])}`}function r(e){const t=e.toString(16);return 1==t.length?"0"+t:t}t.appendToolboxIconCss=function(t,i){if(!(n.indexOf(t)>-1))if(1===i.length){const r=e.Util.unicodeToChar(i);n+=`\n .blocklyTreeIcon.${t}::before {\n content: "${r}";\n }\n `}else n+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(i))}")!important;\n width: 30px;\n height: 100%;\n background-size: 20px !important;\n background-repeat: no-repeat !important;\n background-position: 50% 50% !important;\n }\n `},t.getNamespaceColor=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]?e.toolbox.blockColors[t]:""},t.getNamespaceIcon=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockIcons&&e.appTarget.appTheme.blockIcons[t]?e.appTarget.appTheme.blockIcons[t]:e.toolbox.blockIcons[t]?e.toolbox.blockIcons[t]:""},t.advancedTitle=function(){return e.Util.lf("{id:category}Advanced")},t.addPackageTitle=function(){return e.Util.lf("{id:category}Extensions")},t.recipesTitle=function(){return e.Util.lf("{id:category}Tutorials")},t.convertColor=function(e){var t;e=(t=e)?"0x"==t.substring(0,2)?"#"+t.substring(2):t:"#000000";const n=parseInt(e);return isNaN(n)?e:i(n)},t.hueToRgb=i,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let r=0;r<3;r++){let s=parseInt(e.substr(2*r,2),16);s=Math.round(Math.min(Math.max(0,n?s+s*t:s-s*t),255));let o=s.toString(16);i+=("00"+o).substr(o.length)}return i}}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function r(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim}function s(t,i,r){let s=i||n,a=[];if(t.replace(s,(function(e,t,n){n=n.trim();let{header:i,hint:s,requiredBlocks:l}=function(e,t,n){let i,r,s=e=o(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;s=e.replace(t,(function(e,t){return i=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let o=e.match(t);if(o&&o.length>2&&(s=o[1].trim(),i=o[2].trim(),n)){let e=o[2].trim();e=e.replace(/``` *(requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return r=`{\n${n}\n}`,""})),i=e}}return{header:s,hint:i,requiredBlocks:r}}(n,r&&r.explicitHints,r.tutorialCodeValidation);let c={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(c.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(c.showDialog=!0),/@tutorialCompleted/.test(t)&&(c.tutorialCompleted=!0),/@resetDiff/.test(t)&&(c.resetDiff=!0),s&&(c.hintContentMd=s),r.tutorialCodeValidation&&l&&(c.requiredBlockMd=l),a.push(c),""})),0!=t.indexOf("# Not found"))return a;e.debug("tutorial not found")}function o(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|customts)\s*\n([\s\S]*?)\n```/gim,"").trim()}function a(t){if(!t)return;const n=JSON.parse(t);return{[e.TILEMAP_JRES]:n[e.TILEMAP_JRES],[e.TILEMAP_CODE]:n[e.TILEMAP_CODE],[e.IMAGES_JRES]:n[e.IMAGES_JRES],[e.IMAGES_CODE]:n[e.IMAGES_CODE]}}t.parseTutorial=function(t){const{metadata:r,body:l}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},r=t.replace(n,(function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""})),s=i;void 0!==s.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(s.explicitHints=!0);return{metadata:s,body:r}}(t),{steps:c,activities:u}=function(e,t){if(t&&t.activities)return function(e,t){let r=[],o=[];return e.replace(n,(function(e,n,a){let l=o.length;o.push({name:n||lf("Activity {0}",l),step:r.length});let c=s(a,i,t);return c=c.map((e=>(e.activity=l,e))),r=r.concat(c),""})),{steps:r,activities:o}}(e,t);{let n=s(e,null,t);return(!n||n.length<1)&&(n=s(e,i,t)),{steps:n,activities:null}}}(l,r),d=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(l);if(!c)return;const{code:h,templateCode:p,editor:f,language:m,jres:g,assetJson:b,customTs:y,tutorialValidationRulesStr:v}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim;let r,s,o,a,l,c,u=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,(function(t,n,i){switch(n){case"block":case"blocks":case"requiredTutorialBlock":case"filterblocks":if(!d(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!d(e.PYTHON_PROJECT_NAME))return;"python"==n&&(o=n);break;case"typescript":case"ts":case"javascript":case"js":if(!d(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":s=i;break;case"jres":r=i;break;case"assetjson":a=i;break;case"customts":l=i,i="";break;case"tutorialValidationRules":c=i}return u.push("python"==n?`\n${i}\n`:`{\n${i}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:u,templateCode:s,editor:n,language:o,jres:r,assetJson:a,customTs:l,tutorialValidationRulesStr:c};function d(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(l);let w;r.tutorialCodeValidation&&(w=e.Util.jsonTryParse(v),function(t,n){const i=Object.keys(t);for(let r=0;r<i.length;r++){const s={ruleName:i[r],enabled:t[i[r]]?"true":"false",tutorial:n};e.tickEvent("tutorial.validation.setValidationRules",s)}}(w,d)),(!0===r.diffs||!1!==r.diffs&&!0!==r.noDiffs&&(f==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||f!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,r,s){const o=n,a=/^(template|ghost)$/.test(r),l=i.test(s);return s=s.replace(/^\n+/,"").replace(/\n+$/,""),l&&(s=s.replace(i,"")),n=s,!o||l||a?e:`\`\`\`${t[r]}\n${o}\n----------\n${s}\n\`\`\``})):e}e.forEach(((e,r)=>{if((e.resetDiff||t&&t.find((e=>e.step==r)))&&(n=void 0),e.hintContentMd){const t=i(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=i(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(c,u);const x=a(b);return c.forEach((e=>{e.contentMd=o(e.contentMd),e.headerContentMd=o(e.headerContentMd),e.hintContentMd=o(e.hintContentMd),e.requiredBlockMd=o(e.requiredBlockMd)})),{editor:f,title:d,steps:c,activities:u,code:h,templateCode:p,metadata:r,language:m,jres:g,assetFiles:x,customTs:y,tutorialValidationRules:w}},t.getMetadataRegex=r,t.highlight=function(e){let t=e.textContent;if(t=t.replace(/img\s*\(\s*"{3}[\s\da-f.#tngrpoyw]*"{3}\s*\)/g,'img(""" """)'),t=t.replace(/img\s*`[\s\da-f.#tngrpoyw]*`\s*/g,"img` `"),!/@highlight/.test(t))return void(e.textContent=t);e.textContent="";const n=t.split("\n");for(let t=0;t<n.length;++t){t>0&&t<n.length&&e.appendChild(document.createTextNode("\n"));let i=n[t];if(/@highlight/.test(i)){if(i=n[++t],void 0!==i){const t=document.createElement("span");t.className="highlight-line",t.textContent=i,e.appendChild(t)}}else e.appendChild(document.createTextNode(i))}},t.getTutorialOptions=function(t,n,i,r,s){var o;const a=e.tutorial.parseTutorial(t);if(!a)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:a.title||i,tutorialReportId:r,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:a.steps,tutorialActivityInfo:a.activities,tutorialMd:t,tutorialCode:a.code,tutorialRecipe:!!s,templateCode:a.templateCode,autoexpandStep:!(null===(o=a.metadata)||void 0===o?void 0:o.autoexpandOff),metadata:a.metadata,language:a.language,jres:a.jres,assetFiles:a.assetFiles,customTs:a.customTs,tutorialValidationRules:a.tutorialValidationRules},editor:a.editor}},t.parseCachedTutorialInfo=function(t,n){let i=e.Util.jsonTryParse(t);return i?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&i[n]){const t=i[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){const r=(i||t.fileName||"README")+".md";let s;const[o,a,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return s=o&&a&&l?n[`_locales/${o}/${r}`]||n[`_locales/${l}/${r}`]||n[`_locales/${a}/${r}`]:n[`_locales/${o}/${r}`],s=s||n[r],s},t.parseAssetJson=a}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n){const{tutorialStep:i}=t,r=t.tutorialStepInfo[i].requiredBlockMd,s=e.BrowserUtils.getTutorialCodeHash([r]);let o={};return null!=n&&(o=n[s]),o}function i(e,t,n){n.isStrict=!0;const i=Object.keys(e);let r=[],s=[];null!=t&&(r=Object.keys(t));let o=i.length>=r.length;const a=lf("These are the blocks you seem to be missing:");for(let n=0;n<r.length;n++){let i=r[n];(!e[i]||e[i]<t[i])&&(s.push(i),o=!1)}return n.ruleMessage=a,n.ruleStatus=o,n.blockIds=s,n}function r(e,t,n){const i=Object.keys(e),r=Object.keys(null!=t?t:{});let s=i.length>=r.length;for(let t=0;t<r.length;t++){if(!e[r[t]]){s=!1;break}}return n.ruleStatus=s,n}function s(e,t,n){n.isStrict=!0;Object.keys(e);let i=[],r=[];null!=t&&(i=Object.keys(t));let s=!0;const o=lf("You are required to have the following block:");for(let t=0;t<i.length;t++){let n=i[t];e[n]||(r.push(n),s=!1)}return n.ruleMessage=o,n.ruleStatus=s,n.blockIds=r,n}t.validate=async function(t,o,a){let l=function(e){let t=[];if(null!=e){const n=Object.keys(e);for(let i=0;i<n.length;i++){const r=n[i],s={ruleName:r,ruleTurnOn:e[r]};t.push(s)}}return t}(t.tutorialValidationRules);if(l.length>0&&o.length>0){const a=function(e){let t={};for(let n=0;n<e.length;n++)t[e[n]]||(t[e[n]]=0),t[e[n]]=t[e[n]]+1;return t}(o.map((e=>e.type))),{tutorialStepInfo:c,tutorialStep:u}=t,d=(c[u],await function(t,n){return e.BrowserUtils.tutorialInfoDbAsync().then((e=>e.getAsync(t.tutorial,t.tutorialCode).then((e=>(null==e?void 0:e.snippets)?Promise.resolve(e.snippets):Promise.resolve(void 0)))))}(t)),h=function(t,n){const{tutorialStepInfo:i,tutorialStep:r}=t,s=t.tutorialStepInfo[r].hintContentMd;let o="";null!=s&&s.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return o=`{\n${n}\n}`,""}));const a=e.BrowserUtils.getTutorialCodeHash([o]);let l={};null!=n&&(l=n[a]);return l}(t,d);for(let e=0;e<l.length;e++){let o=l[e];const c=l[e].ruleName;if(l[e].ruleTurnOn)switch(c){case"exact":o=i(a,h,o);break;case"atleast":o=r(a,h,o);break;case"required":o=s(a,n(t,d),o)}}}return l}}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){let n;t.flattenDiagnosticMessageText=function(e,t){if("string"==typeof e)return e;{let n=e,i="",r=0;for(;n;){if(r){i+=t;for(let e=0;e<r;e++)i+=" "}i+=n.messageText,r++,n=n.next}return i}},function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES6=2]="ES6",e[e.ES2015=2]="ES2015",e[e.Latest=2]="Latest"}(n=t.ScriptTarget||(t.ScriptTarget={})),t.isIdentifierStart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&a(e,t)},t.isIdentifierPart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return t>=n.ES5?l(e,r):l(e,o)}(e,t)},t.reservedWords=["abstract","any","as","break","case","catch","class","continue","const","constructor","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","is","let","module","namespace","new","null","package","private","protected","public","require","global","return","set","static","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","async","await","of","Math"],t.keywordTypes=["boolean","number","string"],t.escapeIdentifier=function(n){if(!n)return"_";let i=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return i&&e.pxtc.isIdentifierStart(i.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(i)||(i="_"+i),i};const i=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],r=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],s=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],o=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,768,846,864,866,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1155,1158,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1425,1441,1443,1465,1467,1469,1471,1471,1473,1474,1476,1476,1488,1514,1520,1522,1569,1594,1600,1621,1632,1641,1648,1747,1749,1756,1759,1768,1770,1773,1776,1788,1808,1836,1840,1866,1920,1968,2305,2307,2309,2361,2364,2381,2384,2388,2392,2403,2406,2415,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2494,2500,2503,2504,2507,2509,2519,2519,2524,2525,2527,2531,2534,2545,2562,2562,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2649,2652,2654,2654,2662,2676,2689,2691,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2784,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2876,2883,2887,2888,2891,2893,2902,2903,2908,2909,2911,2913,2918,2927,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3006,3010,3014,3016,3018,3021,3031,3031,3047,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3134,3140,3142,3144,3146,3149,3157,3158,3168,3169,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3262,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3297,3302,3311,3330,3331,3333,3340,3342,3344,3346,3368,3370,3385,3390,3395,3398,3400,3402,3405,3415,3415,3424,3425,3430,3439,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3805,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3946,3953,3972,3974,3979,3984,3991,3993,4028,4038,4038,4096,4129,4131,4135,4137,4138,4140,4146,4150,4153,4160,4169,4176,4185,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,4969,4977,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6099,6112,6121,6160,6169,6176,6263,6272,6313,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8319,8319,8400,8412,8417,8417,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12335,12337,12341,12344,12346,12353,12436,12441,12442,12445,12446,12449,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65056,65059,65075,65076,65101,65103,65136,65138,65140,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65381,65470,65474,65479,65482,65487,65490,65495,65498,65500];function a(e,t){return t>=n.ES5?l(e,i):l(e,s)}function l(e,t){if(e<t[0])return!1;let n,i=0,r=t.length;for(;i+1<r;){if(n=i+(r-i)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?r=n:i=n+2}return!1}let c;t.isUnicodeIdentifierStart=a,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(c=t.DiagnosticCategory||(t.DiagnosticCategory={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(){return!!navigator&&!!navigator.bluetooth&&"TextDecoder"in window&&e.appTarget.appTheme.bluetoothUartConsole&&e.appTarget.appTheme.bluetoothUartFilters&&e.appTarget.appTheme.bluetoothUartFilters.length>0}function i(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||i()},t.hasConsole=n,t.hasPartialFlash=i,t.isValidUUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)};class r{constructor(e,t){this.connectionTimeout=2e4,this.connectPromise=void 0,this.id=e,this.aliveToken=t}debug(t){e.debug(`${this.id}: ${t}`)}alivePromise(e){return new Promise(((t,n)=>{this.aliveToken.isCancelled()&&n(new Error),e.then((e=>t(e)),(e=>n(e)))}))}cancelConnect(){this.connectPromise=void 0}createConnectPromise(){return Promise.resolve()}connectAsync(){return this.connectPromise||(this.connectPromise=this.alivePromise(this.createConnectPromise())),e.Util.promiseTimeout(this.connectionTimeout,this.connectPromise,"connection timeout").then((()=>this.aliveToken.throwIfCancelled())).catch((e=>{throw this.connectPromise=void 0,e}))}disconnect(){this.cancelConnect()}kill(){this.disconnect(),this.aliveToken.cancel()}}t.BLERemote=r;class s extends r{constructor(e,t,n){super(e,t.aliveToken),this.device=t,this.autoReconnect=n,this.autoReconnectDelay=1e3,this.disconnectOnAutoReconnect=!1,this.reconnectPromise=void 0,this.failedConnectionServicesVersion=-1,this.handleDisconnected=this.handleDisconnected.bind(this),this.device.device.addEventListener("gattserverdisconnected",this.handleDisconnected)}handleDisconnected(t){this.aliveToken.isCancelled()||(this.disconnect(),this.autoReconnect&&!this.reconnectPromise&&(this.reconnectPromise=e.U.delay(this.autoReconnectDelay).then((()=>this.exponentialBackoffConnectAsync(8,500))).finally((()=>this.reconnectPromise=void 0))))}exponentialBackoffConnectAsync(t,n){return this.debug("retry connect"),this.aliveToken.throwIfCancelled(),this.connectAsync().then((()=>{this.aliveToken.throwIfCancelled(),this.debug("reconnect success"),this.reconnectPromise=void 0})).catch((i=>(this.debug(`reconnect error ${i.message}`),this.aliveToken.throwIfCancelled(),this.device.isPaired?this.autoReconnect?0==t?(this.debug("give up, max tries"),void(this.reconnectPromise=void 0)):this.failedConnectionServicesVersion==this.device.servicesVersion?(this.debug("services haven't changed, giving up"),void(this.reconnectPromise=void 0)):(this.debug(`retry connect ${n}ms... (${t} tries left)`),this.device.connected&&(this.failedConnectionServicesVersion=this.device.servicesVersion),this.disconnectOnAutoReconnect&&this.device.disconnect(),e.U.delay(n).then((()=>this.exponentialBackoffConnectAsync(--t,1.8*n)))):(this.debug("autoreconnect disabled"),void(this.reconnectPromise=void 0)):(this.debug("give up, device unpaired"),void(this.reconnectPromise=void 0)))))}}t.BLEService=s;class o extends s{constructor(e,t,n,i){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=i,this.handleValueChanged=this.handleValueChanged.bind(this)}createConnectPromise(){return this.debug("connecting"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(this.serviceUUID)))).then((e=>(this.debug("service connected"),this.service=e,this.alivePromise(this.service.getCharacteristic(this.txCharacteristicUUID))))).then((e=>(this.debug("tx characteristic connected"),this.txCharacteristic=e,this.txCharacteristic.addEventListener("characteristicvaluechanged",this.handleValueChanged),this.txCharacteristic.startNotifications()))).then((()=>{e.tickEvent("webble.connected",{id:this.id})}))}handlePacket(e){}handleValueChanged(e){const t=e.target.value;this.handlePacket(t)}disconnect(){if(super.disconnect(),this.txCharacteristic&&this.device&&this.device.connected)try{this.txCharacteristic.stopNotifications(),this.txCharacteristic.removeEventListener("characteristicvaluechanged",this.handleValueChanged)}catch(t){e.log(`${this.id}: error ${t.message}`)}this.service=void 0,this.txCharacteristic=void 0}}t.BLETXService=o;class a extends o{constructor(e){super("hf2",e,a.SERVICE_UUID,a.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case a.BLEHF2_FLAG_SERIAL_OUT:case a.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let i="";for(let t=0;t<n;++t)i+=String.fromCharCode(e.getUint8(t+1));i&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:i},"*")}}}a.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",a.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",a.BLEHF2_FLAG_SERIAL_OUT=128,a.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=a;class l extends o{constructor(e){super("uart",e,l.SERVICE_UUID,l.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=(new window.TextDecoder).decode(e);t&&window.postMessage({type:"serial",id:this.device.name||"uart",data:t},"*")}}let c;l.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",l.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=l,function(e){e[e.Idle=1]="Idle",e[e.StatusRequested=2]="StatusRequested",e[e.PairingModeRequested=4]="PairingModeRequested",e[e.RegionDALRequested=8]="RegionDALRequested",e[e.RegionMakeCodeRequested=16]="RegionMakeCodeRequested",e[e.Flash=32]="Flash",e[e.EndOfTransmision=64]="EndOfTransmision",e[e.USBFlashRequired=128]="USBFlashRequired"}(c||(c={}));class u extends s{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=c.Idle,this.disconnectOnAutoReconnect=!0,this.handleCharacteristic=this.handleCharacteristic.bind(this)}clearFlashData(){this.version=0,this.mode=0,this.regions=[],this.chunkDelay=u.CHUNK_MIN_DELAY,this.hex=void 0,this.bin=void 0,this.magicOffset=void 0,this.dalHash=void 0,this.makeCodeHash=void 0,this.flashReject=void 0,this.flashResolve=void 0,this.flashOffset=void 0}createConnectPromise(){return this.debug("connecting to partial flash service"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(u.SERVICE_UUID)))).then((e=>(this.debug("connecting to characteristic"),this.alivePromise(e.getCharacteristic(u.CHARACTERISTIC_UUID))))).then((e=>(this.debug("starting notifications"),this.pfCharacteristic=e,this.pfCharacteristic.startNotifications(),this.pfCharacteristic.addEventListener("characteristicvaluechanged",this.handleCharacteristic),this.state==c.PairingModeRequested?(this.debug("checking pairing mode"),this.autoReconnect=!1,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))):Promise.resolve())))}disconnect(){if(super.disconnect(),this.flashPacketToken&&this.flashPacketToken.cancel(),this.pfCharacteristic&&this.device.connected)try{this.pfCharacteristic.stopNotifications(),this.pfCharacteristic.removeEventListener("characteristicvaluechanged",this.handleCharacteristic)}catch(t){e.log(`ble: partial flash disconnect error ${t.message}`)}this.pfCharacteristic=void 0}findMarker(e,t){if(!this.bin)return-1;for(;e+t.length<this.bin.length;e+=16){let n=!0;for(let i=0;i<t.length;++i)if(t[i]!=this.bin[e+i]){n=!1;break}if(n)return e}return-1}flashAsync(e){return this.hex?(this.debug("flashing already in progress"),Promise.resolve()):(this.device.pauseLog(),this.createFlashPromise(e).finally((()=>this.device.resumeLogOnDisconnection())))}createFlashPromise(t){if(this.hex)return this.debug("flashing already in progress"),Promise.resolve();this.clearFlashData(),this.hex=t;const n=ts.pxtc.UF2.newBlockFile();ts.pxtc.UF2.writeHex(n,this.hex.split(/\r?\n/));const i=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),i).buf,this.debug(`bin bytes ${this.bin.length}`),this.magicOffset=this.findMarker(0,u.MAGIC_MARKER),this.debug(`magic block ${this.magicOffset.toString(16)}`),this.magicOffset<0&&(this.debug("magic block not found, not a valid HEX file"),e.U.userError(lf("Invalid file"))),this.debug("bytes to flash "+(this.bin.length-this.magicOffset));const r=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(r,r+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(r+8,r+16)),this.debug(`DAL hash ${this.dalHash}`),this.debug(`MakeCode hash ${this.makeCodeHash}`),this.connectAsync().then((()=>new Promise(((e,t)=>(this.flashResolve=e,this.flashReject=t,this.debug("check service version"),this.state=c.StatusRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))))))).then((()=>{}),(t=>{e.log(`pf: error ${t.message}`),this.clearFlashData()}))}checkStateTransition(e,t){return!!(this.state&t)||(this.debug(`flash cmd ${e} in state ${this.state.toString(16)} `),this.flashReject(new Error),this.clearFlashData(),!1)}handleCharacteristic(t){this.aliveToken.isCancelled()&&(this.flashReject(new Error),this.clearFlashData());const n=event.target.value,i=new Uint8Array(n.buffer),r=i[0];if(this.state!=c.Idle)switch(r){case u.STATUS:if(!this.checkStateTransition(r,c.StatusRequested|c.PairingModeRequested))return;this.version=i[1],this.mode=i[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=c.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(r,c.RegionDALRequested|c.RegionMakeCodeRequested))return;const t=this.regions[i[1]]={start:i[2]<<24|i[3]<<16|i[4]<<8|i[5],end:i[6]<<24|i[7]<<16|i[8]<<8|i[9],hash:e.Util.toHex(i.slice(10))};if(this.debug(`read region ${i[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),i[1]==u.REGION_DAL){if(t.hash!=this.dalHash)return e.tickEvent("webble.flash.DALrequired"),this.debug("DAL hash does not match, partial flashing not possible"),this.state=c.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=c.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(i[1]==u.REGION_MAKECODE)if(t.start!=this.magicOffset&&(this.debug("magic offset and MakeCode region.start not matching"),e.U.userError(lf("Invalid file"))),t.hash==this.makeCodeHash)e.tickEvent("webble.flash.noop"),this.debug("MakeCode hash matches, same code!"),this.debug("restart application mode"),this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_APPLICATION])).then((()=>{this.state=c.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=c.PairingModeRequested,this.autoReconnect=!0,void this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_PAIRING])).then((()=>{}));this.flashOffset=t.start,this.flashPacketNumber=0,this.debug(`starting to flash from address ${this.flashOffset.toString(16)}`),this.flashNextPacket()}break;case u.FLASH_DATA:if(!this.checkStateTransition(r,c.Flash))return;switch(i[1]){case u.PACKET_OUT_OF_ORDER:this.debug("packet out of order"),this.flashPacketToken.cancel(),this.flashPacketNumber+=4,this.chunkDelay=Math.min(this.chunkDelay+10,u.CHUNK_MAX_DELAY),this.flashNextPacket();break;case u.PACKET_WRITTEN:this.chunkDelay=Math.max(this.chunkDelay-1,u.CHUNK_MIN_DELAY),this.flashOffset+=64,this.flashPacketNumber+=4,this.flashOffset>=this.bin.length?(this.debug("end transmission"),this.state=c.EndOfTransmision,this.pfCharacteristic.writeValue(new Uint8Array([u.END_OF_TRANSMISSION])).finally((()=>{this.flashResolve&&this.flashResolve(),this.clearFlashData()}))):this.flashNextPacket()}break;default:this.debug(`unknown message ${e.Util.toHex(i)}`),this.disconnect()}}flashNextPacket(){this.state=c.Flash,this.flashPacketToken=new e.Util.CancellationToken,this.flashPacketToken.startOperation();const t=this.bin.slice(this.flashOffset,this.flashOffset+64);this.debug(`flashing ${this.flashOffset.toString(16)} / ${this.bin.length.toString(16)} ${(this.flashOffset-this.magicOffset)/(this.bin.length-this.magicOffset)*100>>0}%`);let n=new Uint8Array(20);e.U.delay(this.chunkDelay).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>8&255,n[2]=this.flashOffset>>0&255,n[3]=this.flashPacketNumber;for(let e=0;e<16;e++)n[4+e]=t[e];return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>24&255,n[2]=this.flashOffset>>16&255,n[3]=this.flashPacketNumber+1;for(let e=0;e<16;e++)n[4+e]=t[16+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+2;for(let e=0;e<16;e++)n[4+e]=t[32+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+3;for(let e=0;e<16;e++)n[4+e]=t[48+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>{const t=this.flashOffset,i=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=c.Flash)return Promise.resolve();this.debug("packet transfer deadlock, force restart"),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=-1;for(let e=0;e<16;e++)n[4+e]=0;return this.pfCharacteristic.writeValue(n).then((()=>i()))}));i().catch((e=>{this.flashReject&&(this.flashReject(new Error("failed packet transfer")),this.clearFlashData())}))})).catch((()=>{this.flashPacketToken.resolveCancel()}))}}u.SERVICE_UUID="e97dd91d-251d-470a-a062-fa1922dfa9a8",u.CHARACTERISTIC_UUID="e97d3b10-251d-470a-a062-fa1922dfa9a8",u.REGION_INFO=0,u.FLASH_DATA=1,u.PACKET_OUT_OF_ORDER=170,u.PACKET_WRITTEN=255,u.END_OF_TRANSMISSION=2,u.STATUS=238,u.RESET=255,u.MODE_PAIRING=0,u.MODE_APPLICATION=1,u.REGION_SOFTDEVICE=0,u.REGION_DAL=1,u.REGION_MAKECODE=2,u.MAGIC_MARKER=e.Util.fromHex("708E3B92C615A841C49866C975EE5197"),u.CHUNK_MIN_DELAY=0,u.CHUNK_MAX_DELAY=75,t.PartialFlashingService=u;class d extends r{constructor(t){super("ble",new e.Util.CancellationToken),this.device=void 0,this.services=[],this.pendingResumeLogOnDisconnection=!1,this.servicesVersion=0,this.device=t,this.handleDisconnected=this.handleDisconnected.bind(this),this.handleServiceAdded=this.handleServiceAdded.bind(this),this.handleServiceChanged=this.handleServiceChanged.bind(this),this.handleServiceRemoved=this.handleServiceRemoved.bind(this),this.device.addEventListener("gattserverdisconnected",this.handleDisconnected),this.device.addEventListener("serviceadded",this.handleServiceAdded),this.device.addEventListener("servicechanged",this.handleServiceChanged),this.device.addEventListener("serviceremoved",this.handleServiceRemoved),n()&&(this.services.push(this.uartService=new l(this)),this.services.push(this.hf2Service=new a(this))),i()&&this.services.push(this.partialFlashingService=new u(this)),this.aliveToken.startOperation()}startServices(){this.services.filter((e=>e.autoReconnect)).forEach((e=>e.connectAsync().catch((()=>{}))))}pauseLog(){this.uartService&&(this.uartService.autoReconnect=!1,this.uartService.disconnect()),this.hf2Service&&(this.hf2Service.autoReconnect=!1,this.hf2Service.disconnect())}resumeLogOnDisconnection(){this.pendingResumeLogOnDisconnection=!0}resumeLog(){this.uartService&&(this.uartService.autoReconnect=!0,this.uartService.connectAsync().catch((()=>{}))),this.hf2Service&&(this.hf2Service.autoReconnect=!0,this.hf2Service.connectAsync().catch((()=>{})))}get isPaired(){return this===t.bleDevice}get name(){return this.device.name||"?"}get connected(){return this.device&&this.device.gatt&&this.device.gatt.connected}get gatt(){return this.device.gatt}createConnectPromise(){return this.debug("connecting gatt server"),this.alivePromise(this.device.gatt.connect().then((()=>this.debug("gatt server connected"))))}handleServiceAdded(e){this.debug("service added"),this.servicesVersion++}handleServiceRemoved(e){this.debug("service removed"),this.servicesVersion++}handleServiceChanged(e){this.debug("service changed"),this.servicesVersion++}handleDisconnected(t){this.debug("disconnected"),this.disconnect(),this.pendingResumeLogOnDisconnection&&(this.pendingResumeLogOnDisconnection=!1,e.U.delay(500).then((()=>this.resumeLog())))}disconnect(){if(super.disconnect(),this.services.forEach((e=>e.disconnect())),this.connected){this.debug("disconnect");try{this.device.gatt&&this.device.gatt.connected&&this.device.gatt.disconnect()}catch(e){this.debug(`gatt disconnect error ${e.message}`)}}}}function h(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const r=[];return n()&&(r.push(l.SERVICE_UUID),r.push(a.SERVICE_UUID)),i()&&r.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:r}).then((n=>(e.log(`ble: received device ${n.name}`),t.bleDevice=new d(n),t.bleDevice.startServices(),t.bleDevice.connectAsync())))}t.BLEDevice=d,t.bleDevice=void 0,t.isPaired=function(){return!!t.bleDevice},t.pairAsync=function(){return t.bleDevice&&(t.bleDevice.kill(),t.bleDevice=void 0),h().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,i){e.tickEvent("webble.flash");const r=n.outfiles[ts.pxtc.BINARY_HEX];return h().then((()=>t.bleDevice.partialFlashingService.flashAsync(r))).then((()=>e.tickEvent("webble.flash.success"))).catch((t=>{throw e.tickEvent("webble.fail.fail",{message:t.message}),t}))}}(e.webBluetooth||(e.webBluetooth={}))}(pxt||(pxt={})),function(e){!function(t){class n extends Error{constructor(e){super(e),this.message=e}}t.USBError=n;t.filters=[{classCode:255,subclassCode:42}];let i,r,s=!0;t.setFilters=function(e){s=!1,t.filters=e};class o{constructor(){this.ready=!1,this.connecting=!1,this.readLoopStarted=!1,this.onDeviceConnectionChanged=e=>{},this.onConnectionChanged=()=>{},this.onData=e=>{},this.onError=e=>{},this.onEvent=e=>{},this.enabled=!1,this.handleUSBConnected=this.handleUSBConnected.bind(this),this.handleUSBDisconnected=this.handleUSBDisconnected.bind(this)}enable(){this.enabled||(this.enabled=!0,this.log("registering webusb events"),navigator.usb.addEventListener("disconnect",this.handleUSBDisconnected,!1),navigator.usb.addEventListener("connect",this.handleUSBConnected,!1))}disable(){this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),navigator.usb.removeEventListener("disconnect",this.handleUSBDisconnected),navigator.usb.removeEventListener("connect",this.handleUSBConnected))}disposeAsync(){return this.disable(),Promise.resolve()}handleUSBDisconnected(e){this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!1))}handleUSBConnected(e){const t=e.device;this.log(`device connected ${t.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!0))}clearDev(){this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,this.onConnectionChanged&&this.onConnectionChanged())}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}disconnectAsync(){return this.ready=!1,this.dev?(this.log("close device"),this.dev.close().catch((e=>{})).then((()=>(this.clearDev(),e.U.delay(500))))):Promise.resolve()}reconnectAsync(){return this.log("reconnect"),this.setConnecting(!0),this.disconnectAsync().then(a).then((e=>this.connectAsync(e))).finally((()=>this.setConnecting(!1)))}setConnecting(e){e!=this.connecting&&(this.connecting=e,this.onConnectionChanged&&this.onConnectionChanged())}isConnecting(){return this.connecting}isConnected(){return!!this.dev&&this.ready}async connectAsync(t){if(this.log(`trying to connect (${t.length} devices)`),0==t.length){const e=new Error("Device not found.");throw e.type="devicenotfound",e}this.setConnecting(!0);try{if(this.lastKnownDeviceSerialNumber){const n=t.find((e=>e.serialNumber===this.lastKnownDeviceSerialNumber));n?(this.log("last known device spotted"),t.splice(t.indexOf(n),1),t.unshift(n)):(this.log("delay for last known device"),await e.U.delay(2e3))}for(let e=0;e<t.length;++e){const n=t[e];this.dev=n,this.log(`connect device: ${n.manufacturerName} ${n.productName}`),this.log(`serial number: ${n.serialNumber} ${this.lastKnownDeviceSerialNumber===n.serialNumber?"(last known device)":""} `);try{return void await this.initAsync()}catch(e){this.dev=void 0,this.log(`connection failed, ${e.message}`)}}const n=new Error(e.U.lf("Device in use or not found."));throw n.type="devicelocked",n}finally{this.setConnecting(!1)}}sendPacketAsync(t){return this.dev?(e.Util.assert(t.length<=64),this.epOut?this.dev.transferOut(this.epOut.endpointNumber,t).then((e=>{"ok"!=e.status&&this.error("USB OUT transfer failed")})):this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t).then((e=>{"ok"!=e.status&&this.error("USB CTRL OUT transfer failed")}))):Promise.reject(new Error("Disconnected"))}readLoop(){if(this.readLoopStarted)return;this.readLoopStarted=!0,this.log("start read loop");let t=()=>{this.ready?this.recvPacketAsync().then((n=>{n[0]?(this.onData(n),t()):e.U.delay(500).then(t)}),(n=>{this.dev&&this.onError(n),e.U.delay(300).then(t)})):e.U.delay(300).then(t)};t()}recvPacketAsync(){let e=e=>{"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);return 0==t.length?this.recvPacketAsync():t};return this.dev?this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64).then(e):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64).then(e):Promise.reject(new Error("Disconnected"))}initAsync(){if(!this.dev)return Promise.reject(new Error("Disconnected"));let n=this.dev;return this.log("open device"),n.open().then((()=>(this.log("select configuration"),n.selectConfiguration(1)))).then((()=>{this.log("got "+n.configurations[0].interfaces.length+" interfaces");const i=n.configurations[0].interfaces.filter((e=>{let n=e.alternates[0];for(let e of t.filters)if((null==e.classCode||n.interfaceClass===e.classCode)&&!(null!=e.subclassCode&&n.interfaceSubclass!==e.subclassCode||null!=e.protocolCode&&n.interfaceProtocol!==e.protocolCode)){if(0==n.endpoints.length)return!0;if(2==n.endpoints.length&&n.endpoints.every((e=>64==e.packetSize)))return!0}return!1}));let r=i[i.length-1];return this.log(`${i.length} matching interfaces; picking ${r?"#"+r.interfaceNumber:"n/a"}`),r||this.error("cannot find supported USB interface"),this.altIface=r.alternates[0],this.iface=r,this.altIface.endpoints.length?(this.log("using dedicated endpoints"),this.epIn=this.altIface.endpoints.filter((e=>"in"==e.direction))[0],this.epOut=this.altIface.endpoints.filter((e=>"out"==e.direction))[0],e.Util.assert(64==this.epIn.packetSize),e.Util.assert(64==this.epOut.packetSize)):this.log("using ctrl pipe"),this.log("claim interface"),n.claimInterface(r.interfaceNumber)})).then((()=>{this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,s&&this.readLoop(),this.onConnectionChanged&&this.onConnectionChanged()}))}}async function a(){e.log("webusb: get devices");try{return await navigator.usb.getDevices()||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==r)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(r=!1);if(e.BrowserUtils.isElectron()||e.BrowserUtils.isWinRT())return e.debug("webusb: off, electron or winrt"),e.tickEvent("webusb.off",{reason:"electronwinrt"}),void(r=!1);const i=navigator.usb;if(!i)return e.debug("webusb: off, not impl"),e.tickEvent("webusb.off",{reason:"notimpl"}),void(r=!1);let s=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(s&&parseFloat(s[1])<6.3)return e.debug("webusb: off, older windows version"),e.tickEvent("webusb.off",{reason:"oldwindows"}),void(r=!1);try{await i.getDevices()}catch(t){return e.debug("webusb: off, security exception"),e.tickEvent("webusb.off",{reason:"security"}),void(r=!1)}r=!0}function c(){return void 0===r&&(console.error("checkAvailableAsync not called"),l()),!!r}t.pairAsync=function(){return navigator.usb.requestDevice({filters:t.filters}).then((e=>!!e)).catch((e=>{if("NotFoundError"!=e.name)throw e}))},t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),i||(i=new o),i.enable(),Promise.resolve(i)},t.isEnabled=!1,t.setEnabled=function(e){c()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.isAvailable=c}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function r(e){let t={},i=0,r=new n.PromiseQueue,s=new Promise(((e,n)=>{t.ready=e}));r.enqueue("main",(()=>s));return{opAsync:function(n,s){return r.enqueue("main",(()=>new Promise(((r,o)=>{let a=""+i++;t[a]=e=>{e?e.errorMessage?o(new Error(e.errorMessage)):r(e):o(new Error("no response"))},e({id:a,op:n,arg:s})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function s(t){let n=new Worker(t),i=r((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),i.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},i}t.getWorker=function(e){let t=i[e];return t||(t=i[e]=s(e)),t},t.wrap=r,t.makeWebWorker=s,t.makeWebSocket=function(t,n=null){let i=new WebSocket(t),s=[],o=r((e=>{let t=JSON.stringify(e);s?s.push(t):i.send(t)}));return i.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):o.recvHandler(t)},i.onopen=t=>{e.debug("socket opened");for(let e of s)i.send(e);s=null},i.onclose=t=>{e.debug("socket closed")},i.onerror=t=>{e.debug("socket errored")},o}}(e.worker||(e.worker={}))}(pxt||(pxt={})),function(e){!function(t){function n(){t.apiKey||e.U.userError("YouTube API key missing")}function i(e){if(!e)return"";const t=e.medium||e.high||e.standard||e.default;return(null==t?void 0:t.url)||""}t.apiKey=void 0,t.playlistItemToCodeCard=function(e){return{name:e.snippet.title.replace(/[^-]*-/,"").trim(),description:(t=e.snippet.description,t.split(/\n\s+/,1)[0].trim()),youTubeId:e.snippet.resourceId.videoId,youTubePlaylistId:e.snippet.playlistId,imageUrl:i(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(i){n();const r=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${i}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(r).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(i){n();let r,s=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${i}&key=${t.apiKey}`;r&&(n+=`&pageToken=${r}`);const o=await e.Util.httpGetJsonAsync(n);s=s.concat(o.items),r=o.nextPageToken}while(r);return e.options.debug&&e.debug(JSON.stringify(s,null,2)),s},t.watchUrl=function(e,t){let n;return e?(n=`https://www.youtube.com/watch?v=${e}`,t&&(n+=`&list=${t}`)):t&&(n=`https://www.youtube.com/playlist?list=${t}`),n}}(e.youtube||(e.youtube={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){function n(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>t[+n]))}t.debug=!1,t.lf=n;let i=l("opcode name doesn't match","<name>");class r{constructor(t,n,i,r,s){this.opcode=i,this.mask=r,this.is32bit=s,this.canBeShared=!1,e.assert((i&r)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,(e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e));let o=a(n);this.name=o[0],this.args=o.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return i;let r=this.opcode,s=1,o=0,a=[],c=null,u=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[s++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return l("expecting register name",p);this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return l("expecting number",p);this.ei.isAddSP(this.opcode)?o=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(o=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return l("expecting {",p);for(f=0;"}"!=n[s];){if(p=n[s++],!p)return l("expecting }",n[s-2]);let e=this.ei.registerNo(p);if(null==e)return l("expecting register name",p);if(f&1<<e)return l("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--,","==n[s]&&s++}p=n[s++]}else if(i.isLabel){if(p=p.replace(/^#/,""),/^[+-]?\d+$/.test(p))f=parseInt(p,10),c="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),c="abs"+f;else if(c=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return l("unknown label",p);f=8}if(this.ei.is32bit(this)){u=f,d=p;continue}}else e.oops();if(null==f)return l("didn't understand it",p);if(a.push(f),f=i.encode(f),null==f)return l("argument out of range or mis-aligned",p);e.assert(0==(r&f)),r|=f}else if(h!=p)return l("expecting "+h,p)}return n[s]?l("trailing tokens",n[s]):this.ei.is32bit(this)?this.ei.emit32(r,u,t.bin.normalizeExternalLabel(d)):{stack:o,opcode:r,numArgs:a,labelName:t.bin.normalizeExternalLabel(c)}}toString(){return this.friendlyFmt}}t.Instruction=r;class s{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=a(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=s;class o{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.currLine=new s(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let r=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;r*=n,t=e[2]}}if("-"==t[0]?(r*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return r*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let s=/(.*)>>(\d+)$/.exec(t);if(s){let e=this.parseOneInt(s[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(s[2])}let o=null;if("0"==t[0])if("x"==t[1]||"X"==t[1]){let e=/^0x([a-f0-9]+)$/i.exec(t);e&&(o=parseInt(e[1],16))}else if("b"==t[1]||"B"==t[1]){let e=/^0b([01]+)$/i.exec(t);e&&(o=parseInt(e[1],2))}if(t.indexOf("@")>=0){let i=/^(\w+)@(-?\d+)$/.exec(t);i&&(1!=r&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(i[1])?o=this.ei.wordSize()*this.ei.computeStackOffset(i[1],this.stack-this.stackpointers[i[1]]+parseInt(i[2])):this.directiveError(n("saved stack not found"))),i=/^(.*)@(hi|lo|fn)$/.exec(t),i&&this.looksLikeLabel(i[1])&&(o=this.lookupLabel(i[1],!0),null!=o&&("fn"==i[2]?o=this.ei.toFnPtr(o,this.baseOffset,i[1]):(o>>=1,0<=o&&o<=65535?"hi"==i[2]?o=o>>8&255:"lo"==i[2]?o&=255:e.oops():(this.directiveError(n("@hi/lo out of range")),o=null))))}return null==o&&this.looksLikeLabel(t)&&(o=this.lookupLabel(t,!0),null!=o&&1==this.ei.postProcessRelAddress(this,1)&&(o+=this.baseOffset)),null==o||isNaN(o)?null:o*r}looksLikeLabel(e){return!/^(r\d|pc|sp|lr)$/i.test(e)&&/^[\.a-zA-Z_][\.:\w+]*$/.test(e)}scopedName(e){return"."==e[0]&&this.scope?this.scope+"$"+e:e}lookupLabel(e,t=!1){let i=null,r=this.scopedName(e);return this.labels.hasOwnProperty(r)?(i=this.labels[r],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(r)&&(i=this.equs[r]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let r,s=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(s&&null!=(r=function(e){e=e.replace(/\\\\/g,"\\B").replace(/\\(['\?])/g,((e,t)=>t)).replace(/\\[z0]/g,"\0").replace(/\\x([0-9a-f][0-9a-f])/gi,((e,t)=>"\\u00"+t)).replace(/\\B/g,"\\\\");try{return JSON.parse(e)}catch(e){return null}}(s[2])))if(this.align(2),t)for(let e=0;e<r.length;e++)this.emitShort(r.charCodeAt(e));else for(let e=0;e<r.length+1;e+=2)this.emitShort(i(r,e+1)<<8|i(r,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],r=t[e+1];0<=i&&r<=255&&0<=r&&i<=255?this.emitShort(255&i|(255&r)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach((e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")}))}handleDirective(e){let t,i=e.words,r=()=>{2!=i.length&&this.directiveError(n("expecting one argument"))};switch(i[0]){case".ascii":case".asciz":case".string":this.emitString(e.text);break;case".utf16":this.emitString(e.text,!0);break;case".align":if(r(),t=this.parseOneInt(i[1]),null!=t){if(0==t)return;t<=4?this.align(1<<t):this.directiveError(n("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))}else this.directiveError(n("expecting number"));break;case".balign":if(r(),t=this.parseOneInt(i[1]),null!=t){if(1==t)return;2==t||4==t||8==t||16==t?this.align(t):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":r(),t=this.parseOneInt(i[1]),null!=t?this.align(1<<t):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(i);break;case".hex":this.emitHex(i);break;case".hword":case".short":case".2bytes":this.parseNumbers(i).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(i).forEach((e=>{-2147483648<=e&&e<=4294967295?(this.emitShort(65535&e),this.emitShort(e>>16&65535)):this.directiveError(n("expecting int32"))}));break;case".skip":case".space":this.emitSpace(i);break;case".set":case".equ":/^\w+$/.test(i[1])||this.directiveError(n("expecting name"));const s=this.parseNumbers(i.slice(","==i[2]||"="==i[2]?2:1));1!=s.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[i[1]]&&this.equs[i[1]]!=s[0]&&this.directiveError(n("redefinition of {0}",i[1])),this.equs[i[1]]=s[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),r(),this.baseOffset=this.parseOneInt(i[1]);break;case"@stackmark":r(),this.stackpointers[i[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[i[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[i[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=i[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":r(),this.stack+=this.parseOneInt(i[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{i=i.filter((e=>","!=e)),i.shift();let e=this.parseOneInt(i[1]),t=0;if(t=i[2]?this.parseOneInt(i[2]):4,null==this.lookupLabel(i[0])){for(this.commPtr||(this.commPtr=this.lookupExternalLabel("_pxt_comm_base")||0,this.commPtr||this.directiveError(n("PXT_COMM_BASE not defined")));this.commPtr&t-1;)this.commPtr++;this.labels[this.scopedName(i[0])]=this.commPtr-this.baseOffset,this.commPtr+=e}break}case".file":case".text":case".cpu":case".fpu":case".eabi_attribute":case".code":case".thumb_func":case".type":case".fnstart":case".save":case".size":case".fnend":case".pad":case".globl":case".local":case"@":break;default:/^\.cfi_/.test(i[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),r="",s=t(i).concat(t(i+"s"));s.length>0&&s.forEach((t=>{let i=t.emit(e);r+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)})),this.pushError(n("assembly error"),r)}buildLine(e,t){let n=e=>{let n=new s(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),r=a(i.text)||[];i.words=r;let o=r[0]||"";if(":"==o.charAt(o.length-1)){let t=/^([\.\w]+):$/.exec(r[0]);if(t){if(i.type="label",i.text=t[1]+":",i.words=[t[1]],!(r.length>1))return;r.shift(),i=n(e.replace(/^[^:]*:/,"")),i.words=r,o=r[0]||""}}let l=o.charAt(0);"."==l||"@"==l?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach((e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))}))}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach((t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}))}getSourceMap(){const e={};let t="",n=0,i=0,r=0;function s(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,r-i)),i=0,r=0}return this.lines.forEach(((e,o)=>{const a=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);a&&(s(),t=a[1],n=parseInt(a[2])),"instruction"==e.type&&(i||(i=e.location),r=e.location)})),s(),e}getSource(i,r=1,s=0){let o=0,a=e=>{let t=this.labels[e]||o,n=t-o;return o=t,n},l=this.buf?this.location():0,c=a("_code_end"),u=a("_helpers_end"),d=a("_vtables_end"),h=a("_literals_end"),p=o,f=l+this.baseOffset&16777215;s&&f>s&&e.U.userError(n("program too big by {0} bytes!",f-s));let m=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",f,(100*f/(s=s||131072)).toFixed(1),(s/1024).toFixed(1),s-f),g=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",p,c,u,d,h,l-p)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*c/r)/100,r)+m+"\n"+this.stats+"\n\n",b=!1;return this.lines.forEach(((e,n)=>{if("_stored_program"==e.words[0])return g+='_stored_program: .string "..."\n',void(b=!0);if(b)return void(b=!1);let r=e.text;if(i){if("@stackempty"==e.words[0]&&this.lines[n-1].text==e.text)return;if(r=r.replace(/; WAS: .*/,""),!r.trim())return}t.debug&&("label"!=e.type&&"instruction"!=e.type||(r+=` \t; 0x${(e.location+this.baseOffset).toString(16)}`)),g+=r+"\n"})),g}peepHole(){let e=this.lines.filter((e=>"empty"!=e.type));for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let r=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,r)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,((e,t)=>t+this.baseOffset))),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=o;t.VMFile=class extends o{constructor(e){super(e)}};function a(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function l(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function c(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let s=new r(this,e,t,n,i);return this.instructions.hasOwnProperty(s.name)||(this.instructions[s.name]=[]),this.instructions[s.name].push(s),s},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=l,t.expectError=function(t,n){let i=new o(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=c,t.expect=function(t,n){let i=[],r=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),""))),s=new o(t);s.throwOnError=!0,s.disablePeepHole=!0,s.emit(r),s.errors.length>0&&(console.debug(s.errors[0].message),e.oops("ASMTEST: not expecting errors")),s.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)s.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+c(i[t])+", got: "+c(s.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i=!0;function r(t){let i=new Error(n.lf("Cannot access {0} while offline",t));return i.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(i)))}function s(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function a(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const i=new Date,r=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+r,e.webConfig.cdnUrl+"/api/"+n}function l(e){return o()?(e.url=a(e.url),n.requestAsync(e).catch((t=>c(e,t)))):u(e)}function c(e,n){return 0==n.statusCode?(i&&(i=!1,t.onOffline()),r(e.url)):Promise.reject(n)}function u(i){var s;return i.url=(null===(s=e.webConfig)||void 0===s?void 0:s.isStatic)&&!i.forceLiveEndpoint?e.webConfig.relprefix+i.url:t.apiRoot+i.url,i.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(i.headers||(i.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(i.headers.Authorization=t.localToken):t.accessToken&&(i.headers["x-td-access-token"]=t.accessToken),n.requestAsync(i).catch((e=>c(i,e)))):r(i.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=s,t.useCdnApi=o,t.cdnApiUrl=a,t.apiRequestWithCdnAsync=l,t.privateRequestAsync=u,t.privateGetTextAsync=function(e,t){return u({url:e,headers:t}).then((e=>e.text))},t.privateGetAsync=function(e,t=!1){return u({url:e,forceLiveEndpoint:t}).then((e=>e.json))},t.downloadTargetConfigAsync=function(){if(!t.isOnline())return Promise.resolve(void 0);const n=e.appTarget.versions&&e.appTarget.versions.target,i=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?s(i).then((e=>e?e.json:void 0)):l({url:i}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text",forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.markdownAsync=async function(t,n){const i=e.BrowserUtils.isLocalHostDev()?0:36e5,r=24*i*7;n=n||e.Util.userLanguage();const a=await e.BrowserUtils.translationDbAsync(),c=await a.getAsync(n,t,""),d=async()=>{try{const i=await function(t,n,i){var r;const a=null===(r=e.webConfig)||void 0===r?void 0:r.isStatic,c=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(a){d=t;const e=/\/?docs\//.test(d),n=/\.\w+$/.test(d);if(!e){const e="/"===d[0];d=`docs${e?"":"/"}${d}`}n||(d=`${d}.md`)}else d=`md/${e.appTarget.id}/${t.replace(/^\//,"")}?targetVersion=${encodeURIComponent(c)}`;"en"!=n&&(d+=`${a?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return s(d).then((e=>404==e.statusCode?u({url:d,method:"GET"}).then((e=>({md:e.text,etag:e.headers.etag}))):{md:e.text,etag:void 0}));{const e=i&&!o()?{"If-None-Match":i}:void 0;return l({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==c?void 0:c.etag);return!c||i.md&&c.md!==i.md?(await a.setAsync(n,t,"",i.etag,void 0,i.md),i.md):c.md}catch(e){return""}};if(c){const t=Date.now()-c.time,n=t>i;if(t>r)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),d()),c.md)return c.md}return d()},t.privateDeleteAsync=function(e){return u({url:e,method:"DELETE"}).then((e=>e.json))},t.privatePostAsync=function(e,t,n=!1){return u({url:e,data:t||{},forceLiveEndpoint:n}).then((e=>e.json))},t.isLoggedIn=function(){return!!t.accessToken},t.isNavigatorOnline=d,t.isOnline=function(){return"undefined"!=typeof navigator&&d()&&(i=!0),i},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){const i=e.appTarget;if(!(t&&i.appTheme&&i.cloud&&i.cloud.sharing))return;let r=["makecode.com"];i.appTheme.embedUrl&&r.push(i.appTheme.embedUrl),i.appTheme.shareUrl&&r.push(i.appTheme.shareUrl),r=n.unique(r,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const s=`^((https://)?(?:${r.join("|")})/)?(?:v[0-9]+/)?(api/oembed?url=.*%2F([^&]*)&.*?|([a-z0-9-_]+))$`,o=new RegExp(s,"i").exec(t.trim()),a=o&&(!o[1]||r.indexOf(n.escapeForRegex(o[1].replace(/https:\/\//,"").replace(/\/$/,"")).toLowerCase())>=0)&&(o[3]||o[4])?o[3]?o[3]:o[4]:null;return a&&("_"==a[0]&&13==a.length||23==a.length&&/^[0-9\-]+$/.test(a))?a:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,i){let r=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(c).join(""),s=4,o=0,a=0,l=e=>{o|=e<<a,a==8-n?(r+=c(o),s++,o=0,a=0):a+=n};for(let r=0;r<e;++r){for(let e=0;e<t;++e)l(i(r,e));for(;0!=a;)l(0);if(n>1)for(;3&s;)l(0)}return r;function c(e){return("0"+e.toString(16)).slice(-2)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){function t(e){let t="";switch(e){case 0:t="C5";break;case 1:t="B";break;case 2:t="A";break;case 3:t="G";break;case 4:t="F";break;case 5:t="E";break;case 6:t="D";break;case 7:t="C"}return t}function n(e){let t=-1;switch(e){case"C5":t=0;break;case"B":t=1;break;case"A":t=2;break;case"G":t=3;break;case"F":t=4;break;case"E":t=5;break;case"D":t=6;break;case"C":t=7}return t}e.MelodyArray=class{constructor(e){this.numCols=8,this.numRows=8,this.polyphonic=!1,e&&(this.tempo=e),this.resetMelody()}setTempo(e){this.tempo=e}getArray(){return this.melody}setArray(e){this.melody=e}getColor(e){return 0}getValue(e,t){return this.melody[e][t]}getWidth(){return this.numCols}getHeight(){return this.numRows}updateMelody(e,t){const n=!this.melody[e][t];if(n&&!this.polyphonic)for(let e=0;e<this.numRows;e++)this.melody[e][t]=!1;this.melody[e][t]=n}getStringRepresentation(){let e="",n=new Array(this.numCols),i=0;for(let e=0;e<this.numRows;e++){let r=0;n[e]=[];for(let i=0;i<this.numCols;i++)this.melody[i][e]&&(n[e].push(t(i)),r++);r>i&&(i=r)}if(0==i)return"- - - - - - - - ";for(let t=0;t<i;t++)for(let t=0;t<this.numCols;t++)n[t]&&n[t].length>0?e+=n[t].shift()+" ":e+="- ";return e}parseNotes(e){let t=(e=e.trim()).split(" ");for(let e=0;e<t.length;e++){for(let t=0;t<this.numRows;t++)this.melody[t][e]=!1;"-"!=t[e]&&(this.melody[n(t[e])][e]=!0)}}setPolyphonic(e){this.polyphonic=e}isPolyphonic(){return this.polyphonic}resetMelody(){this.melody=new Array(this.numCols);for(let e=0;e<this.numCols;e++)this.melody[e]=new Array(this.numRows).fill(!1)}},e.rowToNote=t,e.noteToRow=n,e.getColorClass=function(e){let t="melody-default";switch(e){case 0:t="melody-red";break;case 1:t="melody-orange";break;case 2:t="melody-yellow";break;case 3:t="melody-green";break;case 4:t="melody-teal";break;case 5:t="melody-blue";break;case 6:t="melody-purple";break;case 7:t="melody-violet"}return t}}(pxtmelody||(pxtmelody={})),function(e){function t(e,t,n){return function(e,t,n){if(t)for(const n of Object.keys(t))"className"===n?e.setAttribute("class",t[n]+""):e.setAttribute(n,t[n]+"");n&&e.addEventListener("click",n);return e}(document.createElement(e),t,n)}e.MelodyGallery=class{constructor(){this.value=null,this.visible=!1,this.timeouts=[],this.numSamples=e.SampleMelodies.length,this.containerDiv=document.createElement("div"),this.containerDiv.setAttribute("id","melody-editor-gallery-outer"),this.contentDiv=document.createElement("div"),this.contentDiv.setAttribute("id","melody-editor-gallery"),this.itemBackgroundColor="#DCDCDC",this.itemBorderColor="white",this.initStyles(),this.containerDiv.appendChild(this.contentDiv),this.containerDiv.style.display="none",this.contentDiv.addEventListener("animationend",(()=>{this.visible||(this.containerDiv.style.display="none")})),this.contentDiv.addEventListener("wheel",(e=>{e.stopPropagation()}),!0)}getElement(){return this.containerDiv}getValue(){return this.value}show(e){this.pending=e,this.containerDiv.style.display="block",this.buildDom(),this.visible=!0,pxt.BrowserUtils.removeClass(this.contentDiv,"hidden-above"),pxt.BrowserUtils.addClass(this.contentDiv,"shown")}hide(){this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody()}clearDomReferences(){this.contentDiv=null,this.containerDiv=null}layout(e,t,n){this.containerDiv.style.left=e+"px",this.containerDiv.style.top=t+"px",this.containerDiv.style.height=n+"px"}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.buttons=[];for(let e=0;e<t.length;e++)this.mkButton(t[e],e,"255px","45px")}initStyles(){const e=document.createElement("style");e.textContent="\n #melody-editor-gallery {\n margin-top: -100%;\n }\n\n #melody-editor-gallery.hidden-above {\n margin-top: -100%;\n animation: slide-up 0.2s 0s ease;\n }\n\n #melody-editor-gallery.shown {\n margin-top: 0px;\n animation: slide-down 0.2s 0s ease;\n }\n\n @keyframes slide-down {\n 0% {\n margin-top: -100%;\n }\n 100% {\n margin-top: 0px;\n }\n }\n\n @keyframes slide-up {\n 0% {\n margin-top: 0px;\n }\n 100% {\n margin-top: -100%;\n }\n }\n ",this.containerDiv.appendChild(e)}mkButton(e,n,i,r){const s=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),o=t("i",{className:"music icon melody-icon"}),a=t("div",{className:"melody-editor-text"});a.innerText=e.name;const l=this.createColorBlock(e),c=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));c.appendChild(o),c.appendChild(a),c.appendChild(l),s.appendChild(c);const u=t("div",{className:"melody-editor-button right-button",role:"button",title:lf("Preview {0}",e.name)},(()=>this.togglePlay(e,n))),d=t("i",{className:"play icon"});this.buttons[n]=d,u.appendChild(d),s.appendChild(u),this.contentDiv.appendChild(s)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let i=0;switch(e){case"C5":i=523;break;case"B":i=494;break;case"A":i=440;break;case"G":i=392;break;case"F":i=349;break;case"E":i=330;break;case"D":i=294;break;case"C":i=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(i)}),t*this.getDuration(n))),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration(n)))}getDuration(e){return 6e4/e}previewMelody(e){this.stopMelody();let t=e.notes.split(" ");for(let n=0;n<t.length;n++)this.playNote(t[n],n,e.tempo)}togglePlay(e,t){let n=this.buttons[t];pxt.BrowserUtils.containsClass(n,"play icon")?(this.resetPlayIcons(),pxt.BrowserUtils.removeClass(n,"play icon"),pxt.BrowserUtils.addClass(n,"stop icon"),this.previewMelody(e),this.timeouts.push(setTimeout((()=>{pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon")}),e.notes.split(" ").length*this.getDuration(e.tempo)))):(pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon"),this.stopMelody())}stopMelody(){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop()}resetPlayIcons(){for(let e=0;e<this.numSamples;e++){let t=this.buttons[e];if(pxt.BrowserUtils.containsClass(t,"stop icon")){pxt.BrowserUtils.removeClass(t,"stop icon"),pxt.BrowserUtils.addClass(t,"play icon");break}}}createColorBlock(t){let n=document.createElement("div");pxt.BrowserUtils.addClass(n,"melody-color-block");let i=t.notes.split(" ");for(let t=0;t<i.length;t++){let r=e.getColorClass(e.noteToRow(i[t])),s=document.createElement("div");0==t?pxt.BrowserUtils.addClass(s,"left-edge sliver "+r):t==i.length-1?pxt.BrowserUtils.addClass(s,"right-edge sliver "+r):pxt.BrowserUtils.addClass(s,"sliver "+r),n.appendChild(s)}return n}}}(pxtmelody||(pxtmelody={})),function(e){class t{constructor(e,t,n){this.name=e,this.notes=t,this.tempo=n}}e.MelodyInfo=t,e.SampleMelodies=[new t(lf("Scale"),"C5 B A G F E D C",120),new t(lf("Reverse"),"C D E F G A B C5",120),new t(lf("Mystery"),"E B C5 A B G A F",120),new t(lf("Gilroy"),"A F E F D G E F",120),new t(lf("Falling"),"C5 A B G A F G E",120),new t(lf("Hopeful"),"G B A G C5 B A B",120),new t(lf("Tokyo"),"B A G A G F A C5",120),new t(lf("Paris"),"G F G A - F E D",120),new t(lf("Rising"),"E D G F B A C5 B",120),new t(lf("Sitka"),"C5 G B A F A C5 B",120)]}(pxtmelody||(pxtmelody={})),function(e){!function(t){t.browserDownloadAsync=function(t,n,i){let r;return e.winrt.promisify(Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(n,Windows.Storage.CreationCollisionOption.replaceExisting).then((e=>Windows.Storage.FileIO.writeTextAsync(r=e,t))).then((()=>Windows.System.Launcher.launchFileAsync(r))).then((e=>{})))},t.saveOnlyAsync=function(t){const n=e.appTarget.compile.useUF2,i=n?[".uf2"]:[".hex"],r=new Windows.Storage.Pickers.FileSavePicker;return r.suggestedStartLocation=Windows.Storage.Pickers.PickerLocationId.documentsLibrary,r.fileTypeChoices.insert("MakeCode binary file",i),r.suggestedFileName=t.downloadFileBaseName,e.winrt.promisify(r.pickSaveFileAsync().then((i=>{if(i){let r=n?t.outfiles[pxtc.BINARY_UF2]:t.outfiles[pxtc.BINARY_HEX];e.isOutputText()||(r=atob(r));const s=[];return e.Util.stringToUint8Array(r).forEach((e=>s.push(e))),Windows.Storage.FileIO.writeBytesAsync(i,s).then((()=>!0))}return Promise.resolve(!1)})))}}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.onDeviceConnectionChanged=e=>{},this.onConnectionChanged=()=>{},this.onData=e=>{},this.onEvent=e=>{},this.onError=e=>{},this.connecting=!1,this.handleInputReport=this.handleInputReport.bind(this)}disposeAsync(){return Promise.resolve()}error(t){throw new Error(e.U.lf("USB/HID error ({0})",t))}setConnecting(e){this.connecting=e,this.onConnectionChanged&&this.onConnectionChanged()}isConnecting(){return this.connecting}isConnected(){return!!this.dev}reconnectAsync(){return this.disconnectAsync().then((()=>this.initAsync()))}isSwitchingToBootloader(){o=!0,this.dev&&(a=!0)}disconnectAsync(){if(this.dev){const e=this.dev;delete this.dev;try{e.close()}catch(e){}this.onConnectionChanged&&this.onConnectionChanged()}return Promise.resolve()}sendPacketAsync(t){if(!this.dev)return Promise.resolve();const n=[0];for(let e=0;e<Math.max(t.length,64);++e)n.push(t[e]||0);const i=new Windows.Storage.Streams.DataWriter;i.writeBytes(n);const r=i.detachBuffer(),s=this.dev.createOutputReport(0);return s.data=r,e.winrt.promisify(this.dev.sendOutputReportAsync(s).then((e=>{})))}handleInputReport(e){const t=Windows.Storage.Streams.DataReader.fromBuffer(e.report.data),n=[];for(;t.unconsumedBufferLength;)n.push(t.readByte());65==n.length&&0===n[0]&&n.shift(),this.onData(new Uint8Array(n))}initAsync(n=!1){e.Util.assert(!this.dev,"HID interface not properly reseted");const r=Windows.Devices,s=r.HumanInterfaceDevice.HidDevice,o=()=>{const t=new Error(e.U.lf("Device not found"));return t.type="devicenotfound",Promise.reject(t)},a=i.reduce(((e,t)=>e.then((e=>e&&e.length?Promise.resolve(e):r.Enumeration.DeviceInformation.findAllAsync(t,null)))),Promise.resolve(null));let l;return this.setConnecting(!0),a.then((t=>{if(!t||!t[0])return e.debug("no hid device found"),Promise.reject(new Error("no hid device found"));e.debug(`hid enumerate ${t.length} devices`);const n=t[0];return e.debug(`hid connect to ${n.name} (${n.id})`),l=n.id,s.fromIdAsync(n.id,Windows.Storage.FileAccessMode.readWrite)})).then((t=>{if(this.dev=t,!this.dev){e.debug("can't connect to hid device");let t=Windows.Devices.Enumeration.DeviceAccessInformation.createFromId(l).currentStatus;return e.reportError("winrt_device",`could not connect to HID device; device status: ${t}`),Promise.reject(new Error("can't connect to hid device"))}return e.debug(`hid device version ${this.dev.version}`),this.dev.addEventListener("inputreportreceived",this.handleInputReport),Promise.resolve()})).finally((()=>{this.setConnecting(!1)})).catch((e=>n?o():t.bootloaderViaBaud(this).then((()=>this.initAsync(!0))).catch((()=>o()))))}}t.WinRTPacketIO=n,t.packetIO=void 0,t.mkWinRTPacketIOAsync=function(){return e.debug("packetio: mk winrt packetio"),t.packetIO=new n,t.packetIO.initAsync().catch((e=>(t.packetIO=void 0,Promise.reject(e)))).then((()=>t.packetIO))};const i=[],r=[];let s=0,o=!1,a=!1;t.initWinrtHid=function(n,l){const c=Windows.Devices,u=Windows.Devices.Enumeration.DeviceInformation,d=c.HumanInterfaceDevice.HidDevice;e.appTarget&&e.appTarget.compile&&e.appTarget.compile.hidSelectors&&e.appTarget.compile.hidSelectors.forEach((e=>{const t=d.getDeviceSelector(parseInt(e.usagePage),parseInt(e.usageId),parseInt(e.vid),parseInt(e.pid));i.indexOf(t)<0&&i.push(t)})),i.forEach((i=>{const c=u.createWatcher(i,null);c.addEventListener("added",(t=>{e.debug(`new hid device detected: ${t.id}`),o?o=!1:(++s,1===s&&n&&n())})),c.addEventListener("removed",(i=>{e.debug(`hid device closed: ${i.id}`),a?a=!1:(--s,s>0&&n?n():0===s&&l&&(l(),t.packetIO=void 0))})),c.addEventListener("updated",(e=>{})),r.push(c)})),r.filter((e=>!e.status)).forEach((e=>e.start()))}}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){let n,i,r={};function s(t){if(!t)return Promise.resolve([]);const n=Windows.Devices,i=n.SerialCommunication.SerialDevice,r=n.Enumeration.DeviceInformation,s=[];t.forEach((e=>{const t=i.getDeviceSelectorFromUsbVidPid(parseInt(e.vid),parseInt(e.pid));s.push(t)}));return s.reduce(((e,t)=>{let n;return e.then((e=>(n=e,r.findAllAsync(t,null)))).then((e=>{if(n)for(let t=0;t<e.length;++t)n.push(e[t]);else n=e;return Promise.resolve(n)}))}),Promise.resolve(null)).then((t=>t?e.U.promiseMapAll(t,(t=>e.winrt.promisify(i.fromIdAsync(t.id)))):Promise.resolve([])))}function o(t){i&&!i.test(t.name)||(e.debug(`serial port added ${t.name} - ${t.id}`),r[t.id]={info:t},Windows.Devices.SerialCommunication.SerialDevice.fromIdAsync(t.id).then((e=>{r[t.id].device=e,c(t.id)})))}function a(e){delete r[e.id]}function l(e){const t=r[e.id];t&&t.info.update(e)}t.initSerial=function(){const t=!!(e.appTarget.serial&&(e.appTarget.serial.nameFilter||e.appTarget.serial.vendorId&&e.appTarget.serial.productId));if(!(!!e.appTarget.serial&&e.appTarget.serial.log)||!t)return;const r=Windows.Devices.SerialCommunication.SerialDevice;let s;e.appTarget.serial.vendorId&&e.appTarget.serial.productId?s=r.getDeviceSelectorFromUsbVidPid(parseInt(e.appTarget.serial.vendorId),parseInt(e.appTarget.serial.productId)):(i=new RegExp(e.appTarget.serial.nameFilter),s=r.getDeviceSelector()),n=Windows.Devices.Enumeration.DeviceInformation.createWatcher(s,null),n.addEventListener("added",o),n.addEventListener("removed",a),n.addEventListener("updated",l),n.start()},t.suspendSerialAsync=function(){n&&(n.stop(),n.removeEventListener("added",o),n.removeEventListener("removed",a),n.removeEventListener("updated",l),n=void 0);let t=Promise.resolve();return Object.keys(r).forEach((n=>{const i=r[n],s=i.readingOperation;if(s){const n=e.Util.defer();i.cancellingDeferred=n,t=t.then((()=>e.U.promiseTimeout(500,n.promise).catch((t=>{e.reportError("winrt_device",`could not cancel reading operation for a device: ${t.message}`)})))),s.cancel()}})),t.then((()=>{Object.keys(r).forEach((e=>{const t=r[e];if(t.device){t.device.close()}})),r={}}))},t.bootloaderViaBaud=function(t){if(!(e.appTarget&&e.appTarget.compile&&e.appTarget.compile.useUF2&&e.appTarget.simulator&&e.appTarget.simulator.boardDefinition&&e.appTarget.simulator.boardDefinition.bootloaderBaudSwitchInfo))return Promise.reject(new Error("device does not support switching to bootloader via baudrate"));let n;const i=e.appTarget.simulator.boardDefinition.bootloaderBaudSwitchInfo;return s([{vid:i.vid,pid:i.pid,usageId:void 0,usagePage:void 0}]).then((i=>i&&0!==i.length?(n=i,n.length&&t.isSwitchingToBootloader(),n.forEach((e=>{e.baudRate=1200,e.close()})),e.U.delay(1500)):Promise.reject(new Error("no serial devices to switch into bootloader"))))},t.connectSerialDevicesAsync=s;function c(t){let n=r[t];if(!n)return;if(!n.device){let n=Windows.Devices.Enumeration.DeviceAccessInformation.createFromId(t).currentStatus;return void e.reportError("winrt_device",`could not connect to serial device; device status: ${n}`)}const i=Windows.Storage.Streams;n.device.baudRate=115200;let s=n.device.inputStream,o=new i.DataReader(s);o.inputStreamOptions=i.InputStreamOptions.partial;let a={},l=()=>{r[t]&&!n.cancellingDeferred&&(n.readingOperation=o.loadAsync(32),n.readingOperation.then((n=>{let i=o.readString(4*Math.floor(o.unconsumedBufferLength/4));e.Util.bufferSerial(a,i,t),setTimeout((()=>l()),1)}),(e=>{n.readingOperation.operation.status===Windows.Foundation.AsyncStatus.canceled?(o.detachStream(),o.close(),n.cancellingDeferred&&setTimeout((()=>n.cancellingDeferred.resolve()),25)):setTimeout((()=>c(t)),1e3)})))};setTimeout((()=>l()),100)}}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof Windows}function i(){return n()?(l.resolve(null),l.promise.then((e=>Promise.resolve(e&&e.kind===Windows.ApplicationModel.Activation.ActivationKind.file)))):Promise.resolve(!1)}function r(){return n()?Promise.resolve().then((()=>t.packetIO?(e.log("disconnecting packetIO"),t.packetIO.disconnectAsync()):Promise.resolve())).catch((t=>{t.message=`error disconnecting packetIO: ${t.message}`,e.reportException(t)})).then((()=>(e.log("suspending serial"),t.suspendSerialAsync()))).catch((t=>{t.message=`error suspending serial: ${t.message}`,e.reportException(t)})):Promise.resolve()}function s(e){Windows.UI.WebUI.WebUIApplication.removeEventListener("activated",s),l.resolve(e)}function o(t){e.log("suspending");const n=t.suspendingOperation.getDeferral();return r().then((()=>n.complete()),(e=>n.complete())).then()}function a(n){e.log("resuming"),t.packetIO&&(e.log("reconnet pack io"),t.packetIO.reconnectAsync()),t.initSerial()}let l,c;function u(t,n=!1){if(t.kind===Windows.ApplicationModel.Activation.ActivationKind.file){let i=t.files.getAt(0);if(i&&i.isOfType(Windows.Storage.StorageItemTypes.file)){let t=i;Windows.Storage.FileIO.readBufferAsync(t).then((t=>{let n=[],i=Windows.Storage.Streams.DataReader.fromBuffer(t);for(;i.unconsumedBufferLength;)n.push(i.readByte());return i.close(),e.cpp.unpackSourceFromHexAsync(new Uint8Array(n))})).then((e=>c(e,{openHomeIfFailed:n})))}}}e.BrowserUtils.isWinRT=n,t.promisify=function(e){return new Promise(((t,n)=>{e.then((e=>t(e)),(e=>n(e)))}))},t.toArray=function(e){let t=[],n=e.length;for(let i=0;i<n;++i)t.push(e[i]);return t},t.isWindows=function(){return!!navigator&&/Win32/i.test(navigator.platform)},t.isWinRT=n,t.initAsync=function(r){if(!n()||e.BrowserUtils.isIFrame())return Promise.resolve();const l=Windows.UI.Core,d=l.SystemNavigationManager.getForCurrentView(),h=Windows.UI.WebUI.WebUIApplication;return h.addEventListener("suspending",o),h.addEventListener("resuming",a),d.onbackrequested=t=>{e.log("BACK NAVIGATION"),d.appViewBackButtonVisibility=l.AppViewBackButtonVisibility.collapsed,t.handled=!0},t.initSerial(),i().then((()=>{r&&(c=r,h.removeEventListener("activated",s),h.addEventListener("activated",u))}))},t.captureInitialActivation=function(){if(!n())return;l=e.Util.defer(),Windows.UI.WebUI.WebUIApplication.addEventListener("activated",s)},t.loadActivationProject=function(){return l.promise.then((e=>u(e,!0)))},t.hasActivationProjectAsync=i,t.releaseAllDevicesAsync=r}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){var i=e.Util;let r;function s(...e){return e.join("\\")}function o(n){const i=s(r.path,n);return e.debug(`winrt: reading ${i}`),t.promisify(Windows.Storage.StorageFile.getFileFromPathAsync(i).then((e=>Windows.Storage.FileIO.readTextAsync(e))))}function a(n,i,o){const a=s(r.path,n);return e.debug(`winrt: writing ${s(a,i)}`),t.promisify(Windows.Storage.StorageFolder.getFolderFromPathAsync(a)).then((e=>e.createFileAsync(i,Windows.Storage.CreationCollisionOption.replaceExisting))).then((e=>Windows.Storage.FileIO.writeTextAsync(e,o))).then((()=>{}))}function l(e,t=null){let n=new Error(t||"Error "+e);throw n.statusCode=e,n}n.fileApiAsync=function(n,h){if(i.startsWith(n,"pkg/")){let d=n.slice(4);return h?function(n,d){return e.debug(`winrt: writing package at ${n}`),t.promisify(r.createFolderAsync(n,Windows.Storage.CreationCollisionOption.openIfExists)).then((()=>i.promiseMapAll(d.files,(t=>o(s(n,t.name)).then((n=>{if(t.name!=e.SIMSTATE_JSON&&t.name!=e.ASSETS_FILE){if(t.name==e.CONFIG_NAME)try{JSON.parse(t.content).name||(e.log("Trying to save invalid JSON config"),l(410))}catch(t){e.log("Trying to save invalid format JSON config"),l(410)}n!==t.prevContent&&(e.log(`merge error for ${t.name}: previous content changed...`),l(409))}}),(e=>{})))))).then((()=>i.promiseMapAll(d.files,(e=>a(n,e.name,e.content))))).then((()=>a(n,c,JSON.stringify(d.header,null,4)))).then((()=>u(n,!1)))}(d,h):u(d,!0)}if("list"==n)return function(){if(r)return Promise.resolve();const n=Windows.Storage.ApplicationData.current.localFolder;return e.debug("winrt: initializing workspace"),t.promisify(n.createFolderAsync(e.appTarget.id,Windows.Storage.CreationCollisionOption.openIfExists)).then((t=>{r=t,e.debug(`winrt: initialized workspace at ${r.path}`)})).then((()=>{}))}().then(d);throw l(404)};const c=".header.json";function u(n,a){return e.debug(`winrt: reading package under ${n}`),o(s(n,e.CONFIG_NAME)).then((l=>{const u=JSON.parse(l);return i.promiseMapAll(e.allPkgFiles(u),(i=>function(n){const i=s(r.path,n);return e.debug(`winrt: ${i}`),t.promisify(Windows.Storage.StorageFile.getFileFromPathAsync(i).then((e=>e.getBasicPropertiesAsync().then((e=>({name:n,mtime:e.dateModified.getTime()}))))))}(s(n,i)).then((e=>{const t={name:i,mtime:e?e.mtime:null};return null!=e&&a?o(s(n,i)).then((e=>(t.content=e,t))):t})))).then((e=>{const t={path:n,header:null,config:u,files:e};return o(s(n,c)).then((e=>{e&&(t.header=JSON.parse(e))}),(e=>{})).then((()=>t))}))}))}function d(){return t.promisify(r.getFoldersAsync()).then((e=>i.promiseMapAll(e,(e=>u(e.name,!1))))).then((e=>Promise.resolve({pkgs:e})))}function h(){return t.promisify(r.deleteAsync(Windows.Storage.StorageDeleteOption.default).then((()=>{r=void 0})))}n.getProvider=function(e){return{listAsync:e.listAsync,getAsync:e.getAsync,setAsync:e.setAsync,resetAsync:h}}}(t.workspace||(t.workspace={}))}(e.winrt||(e.winrt={}))}(pxt||(pxt={})),function(e){!function(t){let n,i,r,s;!function(e){e[e.Stopped=0]="Stopped",e[e.Pending=1]="Pending",e[e.Starting=2]="Starting",e[e.Running=3]="Running"}(n=t.SimState||(t.SimState={})),t.isBlocks=function(t){return e.U.endsWith(t.name,".blocks")},function(e){e.HeaderOnly="errorListHeader",e.Expanded="errorListExpanded"}(i=t.ErrorListState||(t.ErrorListState={})),function(e){e[e.Hidden=0]="Hidden",e[e.Visible=1]="Visible",e[e.Disabled=2]="Disabled"}(r=t.FilterState||(t.FilterState={})),t.initExtensionsAsync=e=>Promise.resolve({}),t.initFieldExtensionsAsync=e=>Promise.resolve({}),t.HELP_IMAGE_URI="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYiIGhlaWdodD0iMjYiIHZpZXdCb3g9IjAgMCAyNiAyNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTMiIGN5PSIxMyIgcj0iMTMiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNy45NTIgOS4xODQwMkMxNy45NTIgMTAuMjU2IDE3LjgxNiAxMS4wNzIgMTcuNTQ0IDExLjYzMkMxNy4yODggMTIuMTkyIDE2Ljc1MiAxMi43OTIgMTUuOTM2IDEzLjQzMkMxNS4xMiAxNC4wNzIgMTQuNTc2IDE0LjU4NCAxNC4zMDQgMTQuOTY4QzE0LjA0OCAxNS4zMzYgMTMuOTIgMTUuNzM2IDEzLjkyIDE2LjE2OFYxNi45NkgxMS44MDhDMTEuNDI0IDE2LjQ2NCAxMS4yMzIgMTUuODQgMTEuMjMyIDE1LjA4OEMxMS4yMzIgMTQuNjg4IDExLjM4NCAxNC4yODggMTEuNjg4IDEzLjg4OEMxMS45OTIgMTMuNDg4IDEyLjUzNiAxMi45NjggMTMuMzIgMTIuMzI4QzE0LjEwNCAxMS42NzIgMTQuNjI0IDExLjE2OCAxNC44OCAxMC44MTZDMTUuMTM2IDEwLjQ0OCAxNS4yNjQgOS45NjgwMiAxNS4yNjQgOS4zNzYwMkMxNS4yNjQgOC4yMDgwMiAxNC40MTYgNy42MjQwMiAxMi43MiA3LjYyNDAyQzExLjc2IDcuNjI0MDIgMTAuNzUyIDcuNzM2MDIgOS42OTYgNy45NjAwMkw5LjE0NCA4LjA4MDAyTDkgNi4wODgwMkMxMC40ODggNS41NjAwMiAxMS44NCA1LjI5NjAyIDEzLjA1NiA1LjI5NjAyQzE0LjczNiA1LjI5NjAyIDE1Ljk2OCA1LjYwODAyIDE2Ljc1MiA2LjIzMjAyQzE3LjU1MiA2Ljg0MDAyIDE3Ljk1MiA3LjgyNDAyIDE3Ljk1MiA5LjE4NDAyWk0xMS40IDIyVjE4LjY0SDE0LjE4NFYyMkgxMS40WiIgZmlsbD0iIzU5NUU3NCIvPgo8L3N2Zz4K",t.initEditorExtensionsAsync=function(){if(!s&&(s=Promise.resolve(),e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.extendFieldEditors)){const t={};s=s.then((()=>e.BrowserUtils.loadBlocklyAsync())).then((()=>e.BrowserUtils.loadScriptAsync("fieldeditors.js"))).then((()=>e.editor.initFieldExtensionsAsync(t))).then((t=>{t.fieldEditors&&t.fieldEditors.forEach((t=>{e.blocks.registerFieldEditor(t.selector,t.editor,t.validator)}))}))}return s}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n={};function i(e,t,n,i){e.response&&window.parent.postMessage({type:e.type,id:e.id,resp:t,success:n,error:i},"*")}function r(t){return new Promise(((i,r)=>{const s=e.Util.clone(t);s.id=ts.pxtc.Util.guidGen(),t.response&&(n[s.id]={resolve:i,reject:r}),window.parent.postMessage(s,"*"),t.response||i(void 0)}))}t.bindEditorMessages=function(t){const r=(e.appTarget.appTheme.allowParentController||e.shell.isControllerMode())&&e.BrowserUtils.isIFrame(),s=e.appTarget.appTheme.allowPackageExtensions,o=e.appTarget.appTheme.allowSimulatorTelemetry;(r||s||o)&&window.addEventListener("message",(a=>{const l=a.data;if(!l||!/^pxt(host|editor|pkgext|sim)$/.test(l.type))return!1;if("pxtpkgext"===l.type&&s)t().then((e=>{e.handleExtensionRequest(l)}));else if("pxtsim"===l.type&&o){const t=l;"event"===t.action&&(t.category||t.message?e.reportError(t.category,t.message,t.data):e.tickEvent(t.tick,t.data))}else if(r){let r,s=Promise.resolve();if("pxthost"==l.type){const t=n[l.id];t?s=s.then((()=>t.resolve(l))):e.debug(`pxthost: unknown request ${l.id}`)}else"pxteditor"==l.type&&(s=s.then((()=>t().then((t=>{const n=l;switch(e.debug(`pxteditor: ${n.action}`),n.action.toLowerCase()){case"switchjavascript":return Promise.resolve().then((()=>t.openJavaScript()));case"switchpython":return Promise.resolve().then((()=>t.openPython()));case"switchblocks":return Promise.resolve().then((()=>t.openBlocks()));case"startsimulator":return Promise.resolve().then((()=>t.startSimulator()));case"restartsimulator":return Promise.resolve().then((()=>t.restartSimulator()));case"hidesimulator":return Promise.resolve().then((()=>t.collapseSimulator()));case"showsimulator":return Promise.resolve().then((()=>t.expandSimulator()));case"closeflyout":return Promise.resolve().then((()=>t.closeFlyout()));case"unloadproject":return Promise.resolve().then((()=>t.unloadProjectAsync()));case"saveproject":return t.saveProjectAsync();case"redo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasRedo()&&e.redo()}));case"undo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasUndo()&&e.undo()}));case"setscale":{const e=l;return Promise.resolve().then((()=>t.editor.setScale(e.scale)))}case"stopsimulator":{const e=l;return Promise.resolve().then((()=>t.stopSimulator(e.unload)))}case"newproject":{const e=l;return Promise.resolve().then((()=>t.newProject(e.options)))}case"importproject":{const e=l;return Promise.resolve().then((()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar})))}case"openheader":{const e=l;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const n=l;let i,r=n.path;return/^([jt]s|py|blocks?):/i.test(r)&&(i=/^py:/i.test(r)?e.PYTHON_PROJECT_NAME:/^[jt]s:/i.test(r)?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME,r=r.substr(r.indexOf(":")+1)),Promise.resolve().then((()=>t.startActivity({activity:n.activityType,path:r,title:n.title,editor:i,previousProjectHeaderId:n.previousProjectHeaderId,carryoverPreviousCode:n.carryoverPreviousCode})))}case"importtutorial":{const e=l;return Promise.resolve().then((()=>t.importTutorialAsync(e.markdown)))}case"proxytosim":{const e=l;return Promise.resolve().then((()=>t.proxySimulatorMessage(e.content)))}case"renderblocks":{const e=l;return Promise.resolve().then((()=>t.renderBlocksAsync(e))).then((e=>e.xml.then((e=>{r=e.xml}))))}case"renderpython":{const e=l;return Promise.resolve().then((()=>t.renderPythonAsync(e))).then((e=>{r=e.python}))}case"toggletrace":{const e=l;return Promise.resolve().then((()=>t.toggleTrace(e.intervalSpeed)))}case"settracestate":{const e=l;return Promise.resolve().then((()=>t.setTrace(e.enabled,e.intervalSpeed)))}case"setsimulatorfullscreen":{const e=l;return Promise.resolve().then((()=>t.setSimulatorFullScreen(e.enabled)))}case"togglehighcontrast":return Promise.resolve().then((()=>t.toggleHighContrast()));case"togglegreenscreen":return Promise.resolve().then((()=>t.toggleGreenScreen()));case"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync();case"info":return Promise.resolve().then((()=>{r={versions:e.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:e.appTarget.appTheme.availableLocales}}));case"shareproject":{const e=l;return t.anonymousPublishHeaderByIdAsync(e.headerId).then((e=>{r=e}))}case"savelocalprojectstocloud":{const e=l;return t.saveLocalProjectsToCloudAsync(e.headerIds).then((e=>{r={headerIdMap:e}}))}case"requestprojectcloudstatus":{const e=l;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=l;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=l;if("no-blocks"===e.restriction)throw console.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}}return Promise.resolve()})))));s.then((()=>i(l,r,!0,void 0)),(e=>i(l,r,!1,e)))}return!0}),!1)},t.enableControllerAnalytics=function(){if(!e.appTarget.appTheme.allowParentController||!e.BrowserUtils.isIFrame())return;const t=e.tickEvent;e.tickEvent=function(e,n){t&&t(e,n),r({type:"pxthost",action:"event",tick:e,response:!1,data:n})};const n=e.reportException;e.reportException=function(e,t){n&&n(e,t);try{r({type:"pxthost",action:"event",tick:"error",message:e.message,response:!1,data:t})}catch(e){}};const i=e.reportError;e.reportError=function(e,t,n){i&&i(e,t,n),r({type:"pxthost",action:"event",tick:"error",category:e,message:t,data:n})}},t.shouldPostHostMessages=function(){return e.appTarget.appTheme.allowParentController&&e.BrowserUtils.isIFrame()},t.postHostMessageAsync=r}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e){return`experiments-${"object"==typeof e?e.id:e}`}function i(){const t=e.savedAppTheme(),n={},i=r();return i.forEach((e=>{const i=s(e);t[e.id]=!!i,i&&(n[e.id]=i?1:0)})),i.length&&Object.keys(n).length&&(e.tickEvent("experiments.loaded",n),e.reloadAppTargetVariant()),e.appTarget.appTheme}function r(){const t=e.appTarget.appTheme.experiments;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"snippetBuilder",name:lf("Snippet Builder"),description:lf("Try out the new snippet dialogs.")},{id:"experimentalHw",name:lf("Experimental Hardware"),description:lf("Enable support for hardware marked 'experimental' in the hardware seletion dialog")},{id:"checkForHwVariantWebUSB",name:lf("Detect Hardware with WebUSB"),description:lf("When compiling, use WebUSB to detect hardware configuration.")},{id:"githubEditor",name:lf("GitHub editor"),description:lf("Review, commit and push to GitHub."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6419",enableOnline:!0},{id:"githubCompiledJs",name:lf("GitHub Pages JavaScript"),description:lf("Commit compiled javascript when creating a release"),enableOnline:!0},{id:"blocksCollapsing",name:lf("Collapse blocks"),description:lf("Collapse and expand functions or event blocks")},{id:"tutorialBlocksDiff",name:lf("Tutorial Block Diffs"),description:lf("Automatially render blocks diff in tutorials")},{id:"openProjectNewTab",name:lf("Open in New Tab"),description:lf("Open an editor in a new tab.")},{id:"openProjectNewDependentTab",name:lf("Open in New Connected Tab"),description:lf("Open connected editors in different browser tabs.")},{id:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")}].filter((n=>t.indexOf(n.id)>-1&&!(e.BrowserUtils.isPxtElectron()&&n.enableOnline))):[]}function s(t){return!!e.storage.getLocal(n(t))}function o(t,r){r!=s(t)&&(r?e.storage.setLocal(n(t),"1"):e.storage.removeLocal(n(t)),i())}t.syncTheme=i,t.all=r,t.clear=function(){r().forEach((t=>e.storage.removeLocal(n(t)))),i()},t.someEnabled=function(){return r().some((e=>s(e)))},t.isEnabled=s,t.toggle=function(e){o(e,!s(e))},t.state=function(){const e={};return r().forEach((t=>e[t.id]=s(t))),JSON.stringify(e)},t.setState=o}(t.experiments||(t.experiments={}))}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){function n(t){const n=e.appTarget.appTheme.invertedMonaco,i=!(!e.appTarget.appTheme.monacoFieldEditors||!e.appTarget.appTheme.monacoFieldEditors.length),r=e.BrowserUtils.isAndroid();let s=monaco.editor.create(t,{model:null,ariaLabel:e.Util.lf("JavaScript editor"),fontFamily:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:i,glyphMargin:i||e.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:n?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!r,comments:!r,strings:!r},acceptSuggestionOnCommitCharacter:!r,acceptSuggestionOnEnter:r?"off":"on",accessibilitySupport:r?"off":"on"});return s.layout(),s}t.syncModels=function(e,t,n,i){if(i)return;let r=monaco.languages.typescript.typescriptDefaults.getExtraLibs(),s={};e.sortedDeps().forEach((e=>{e.getFiles().forEach((i=>{let r=e.id+"/"+i;if(/\.(ts)$/.test(i)&&r!=n){if(!monaco.languages.typescript.typescriptDefaults.getExtraLibs()[r]){let n=e.readFile(i)||"\n";t[r]=monaco.languages.typescript.typescriptDefaults.addExtraLib(n,r)}s[r]="1"}}))})),Object.keys(r).filter((e=>/\.(ts)$/.test(e)&&!s[e])).forEach((e=>{t[e].dispose()}))},t.initMonacoAsync=function(t){return new Promise(((i,r)=>{if("object"==typeof window.monaco)return void i(n(t));let s=window.MonacoPaths,o=()=>{let r=window.require;r.config({paths:s}),r(["vs/editor/editor.main"],(()=>{monaco.languages.register({id:"asm",extensions:[".asm"]}),monaco.languages.setMonarchTokensProvider("asm",{tokenPostfix:"",keywords:["movs","mov","adds","add","adcs","adr","subs","sbcs","sub","rsbs","muls","cmp","cmn","ands","eors","orrs","bics","mvns","tst","lsls","lsrs","asrs","rors","ldr","ldrh","ldrb","ldrsh","ldrsb","ldm","str","strh","strb","stm","push","pop","cbz","cbnz","b","bl","bx","blx","sxth","sxtb","uxth","uxtb","rev","rev16","revsh","svc","cpsid","cpsie","setend","bkpt","nop","sev","wfe","wfi","yield","beq","bne","bcs","bhs","bcc","blo","bmi","bpl","bvs","bvc","bhi","bls","bge","blt","bgt","ble","bal","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc","sp","lr"],typeKeywords:[".startaddr",".hex",".short",".space",".section",".string",".byte"],operators:[],symbols:/[:\*]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/(\.)?[a-z_$\.][\w$]*/,{cases:{"@typeKeywords":"keyword","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/@\s*[a-zA-Z_\$][\w\$]*/,{token:"annotation"}],[/(#|(0[xX]))?[0-9a-fA-F]+/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/'[^\\']'/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],comment:[],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",next:"@pop"}]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/;.*$/,"comment"]]}}),monaco.languages.typescript&&(monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSyntaxValidation:!0,noSemanticValidation:!0}),monaco.languages.typescript.typescriptDefaults.setWorkerOptions({customWorkerPath:e.webConfig.typeScriptWorkerJs}),monaco.languages.typescript.typescriptDefaults.setCompilerOptions({allowUnreachableCode:!0,noImplicitAny:!0,allowJs:!1,allowUnusedLabels:!0,target:monaco.languages.typescript.ScriptTarget.ES5,outDir:"built",rootDir:".",noLib:!0,mouseWheelZoom:!1})),i(n(t))}))};if(window.require)o();else{let e=document.createElement("script");e.type="text/javascript",e.src=s["vs/loader"],e.addEventListener("load",o),document.body.appendChild(e)}}))},t.createEditor=n}(e.vs||(e.vs={}))}(pxt||(pxt={})),function(e){!function(t){t.freshHeader=function(t,n){return{target:e.appTarget.id,targetVersion:e.appTarget.versions.target,name:t,meta:{},editor:e.JAVASCRIPT_PROJECT_NAME,pubId:"",pubCurrent:!1,_rev:null,id:e.U.guidGen(),recentUse:n,modificationTime:n,cloudUserId:null,cloudCurrent:!1,cloudVersion:null,cloudLastSyncTime:0,isDeleted:!1}}}(e.workspace||(e.workspace={}))}(pxt||(pxt={})),function(e){!function(e){const t={};e.registerMonacoFieldEditor=function(e,n){t[e]=n},e.getMonacoFieldEditor=function(e){return t[e]}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){t.MonacoReactFieldEditor=class{getId(){return"image-editor"}showEditorAsync(t,n,i){return this.fileType=t,this.editrange=n,this.host=i,this.initAsync().then((()=>{const t=this.textToValue(i.getText(n));return t?(this.fv=e.react.getFieldEditorView(this.getFieldEditorId(),t,this.getOptions()),this.fv.onHide((()=>{this.onClosed()})),this.fv.show(),new Promise(((e,t)=>{this.resolver=e,this.rejecter=t}))):Promise.resolve(null)}))}onClosed(){this.resolver&&(this.resolver({range:this.editrange,replacement:this.resultToText(this.fv.getResult())}),this.editrange=void 0,this.resolver=void 0,this.rejecter=void 0)}dispose(){this.onClosed()}initAsync(){return Promise.resolve()}textToValue(e){return null}resultToText(e){return e+""}getFieldEditorId(){return""}getOptions(){return null}}}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="image-editor";class i extends t.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`");const n=e.parseAssetTSReference(t);if(n){const{type:t,name:i}=n,r=i.trim(),s=e.react.getTilemapProject();this.isAsset=!0;const o=s.lookupAssetByName("image",r);if(o)return o;{const t=s.createNewImage();return r&&!s.isNameTaken("image",r)&&e.validateAssetName(r)&&(t.meta.displayName=r),t}}return{type:"image",id:"",internalID:0,bitmap:e.sprite.imageLiteralToBitmap(t).data(),meta:{},jresData:""}}resultToText(t){var n;if(null===(n=t.meta)||void 0===n?void 0:n.displayName){const n=e.react.getTilemapProject();return t=this.isAsset||n.lookupAsset(t.type,t.id)?n.updateAsset(t):n.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,e.getTSReferenceForAsset(t,this.isPython)}return e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript")}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}t.MonacoSpriteEditor=i,t.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:i},t.registerMonacoFieldEditor(n,t.spriteEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(t){const n="tilemap-editor";class i extends t.MonacoReactFieldEditor{textToValue(t){const n=this.readTilemap(t),i=e.react.getTilemapProject();return e.sprite.addMissingTilemapTilesAndReferences(i,n),n}readTilemap(t){const n=e.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(e){return{type:"tilemap",id:"",internalID:0,meta:{},data:e}}(e.sprite.decodeTilemap(t,"typescript",n))}catch(e){}return null}this.isTilemapLiteral=!0;const i=/^\s*(tilemap(?:8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),r=(i[2]||i[3]||"").trim();let s,o;if(this.tilemapLiteral=i[1],r){let e=ts.pxtc.escapeIdentifier(r);s=n.getTilemap(e)}if(!s){let e=16;"tilemap8"===this.tilemapLiteral?e=8:"tilemap32"===this.tilemapLiteral&&(e=32);const[t]=n.createNewTilemap(o,e,16,16);s=n.getTilemap(t),o=t}return s}resultToText(t){const n=e.react.getTilemapProject();return n.pushUndo(),e.sprite.updateTilemapReferencesFromResult(n,t),this.isTilemapLiteral?(n.updateAsset(t),e.getTSReferenceForAsset(t,"python"===this.fileType)):e.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const e=this.editrange.getStartPosition();let t,n=this.editrange.getEndPosition(),i=1;for(;;){t=new monaco.Range(n.lineNumber,n.column,n.lineNumber+1,0);const r=this.host.getText(t);for(let t=0;t<r.length;t++)if("("===r.charAt(t))i++;else if(")"===r.charAt(t)&&(i--,0===i)){const i=new monaco.Position(n.lineNumber,n.column+t+2);return monaco.Range.fromPositions(e,i)}if(n=t.getEndPosition(),n.lineNumber>e.lineNumber+20)return null}}}t.MonacoTilemapEditor=i,t.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:i},t.registerMonacoFieldEditor(n,t.tilemapEditorDefinition)}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",i="orange";const r=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function s(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let i=[];const r=(e,t,i,r)=>{let s=[];for(let t=0;t<e.numberOfPins;t++){let r,o=e.pinDefinitions[t];if("string"==typeof o.target)r=o.target;else{let e=o.target.pinInstantiationIdx;if(!i||void 0===i[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=i[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,c=Math.round(l/e.visual.pinDistance),u=l-c*e.visual.pinDistance,d=n.xOffset+a.x,h=Math.round(d/e.visual.pinDistance),p={partRelativeRowIdx:c,partRelativeColIdx:h,xOffset:d-h*e.visual.pinDistance,yOffset:u};s.push({def:o,loc:a,target:r,bbFit:p})}return{name:t,def:e,pins:s,partParams:r||{},bbFit:n}},s=e.instantiations||[];return e.instantiation&&s.push(e.instantiation),s.forEach((n=>{if("singleton"===n.kind)i.push(r(e,t));else if("function"===n.kind){let s=n,a=s.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let c=Object.keys(l);if(!c||!c.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);c.forEach((n=>{const l=n.split(",");if(l.length!=s.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let c=[],u={};l.forEach(((e,t)=>{let n=s.argumentRoles[t];if(void 0!==n.partParameter&&(u[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,i=o(e);c[t]=i}})),i.push(r(e,t,c,u))}))}})),i.filter((e=>!!e))}computePartDimensions(t,n){let i=t.visual.pinLocations,r=t.pinDefinitions,o=t.numberOfPins;e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(r.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,c,u,d=i.map(((e,t)=>{return n={idx:t},i=e,o=r[t],s(s(n,i),o);var n,i,o})).filter((e=>"-Z"===e.orientation)),h=d.length>0,p=t.visual.pinDistance;if(h){let e=d[0],n=Math.ceil(e.x/p),i=Math.ceil(e.y/p);a=n*p-e.x,l=i*p-e.y,c=Math.ceil((a+t.visual.width)/p)+1,u=Math.ceil((l+t.visual.height)/p)+1}else c=Math.ceil(t.visual.width/p),u=Math.ceil(t.visual.height/p),a=c*p-t.visual.width,l=u*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:u,colCount:c}}allocColumns(t){let n=t.length;let i=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);i<=0&&console.log("Not enough breadboard space!");let r=Math.floor(i/(n-1+2)),s=i-r*(n-1),o=Math.floor(s/2),a=(Math.ceil(s/2),1+o);return t.map((e=>{let t=a;return a+=e.colCount+r,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let i=this.allocColumns(t.map((e=>e.bbFit))),r=t.map((e=>{let t=n-e.bbFit.rowCount,i=Math.floor(t/2);return i>4&&(i=4),i<1&&(i=1),i}));return t.map(((e,t)=>{let n=r[t];return s({startColumnIdx:i[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(r){let o=[],l=r.pins.map(((s,l)=>{let c,u,d=s.target,h=r.startColumnIdx+s.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(h),f=r.startRowIdx+s.bbFit.partRelativeRowIdx;if(f>=7&&(f-=2),a(s.def)){c={type:"breadboard",row:f<5?"j":"a",col:p,style:s.def.style}}else{c={type:"breadboard",row:e.visuals.getRowName(f),col:p,xOffset:s.bbFit.xOffset/r.def.visual.pinDistance,yOffset:s.bbFit.yOffset/r.def.visual.pinDistance,style:s.def.style}}return u="ground"===d?t:"threeVolt"===d?n:"fiveVolt"===d?i:"number"==typeof s.def.colorGroup?o[s.def.colorGroup]?o[s.def.colorGroup]:o[s.def.colorGroup]=this.nextColor():this.nextColor(),{start:c,end:d,color:u,pinIdx:l}}));return s(r,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let i=this.opts.getBBCoord(n.referenceBBPin),r=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));r[0]&&r[1]||console.debug(`No more available "${t}" locations!`);let s,o=0==e.visuals.findClosestCoordIdx(i,r);o?"ground"===t?s=this.availablePowerPins.top.ground:"threeVolt"===t?s=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(s=this.availablePowerPins.top.fiveVolt):"ground"===t?s=this.availablePowerPins.bottom.ground:"threeVolt"===t?s=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(s=this.availablePowerPins.bottom.fiveVolt);let a=s.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(i,a),c=s[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),c}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,i=this.opts.boardDef.gpioPinMap[n]||n;return i?{type:"dalboard",pin:i}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let r=this.getBoardGroundPin(),s=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},c={type:"breadboard",row:"-",col:"50"},u={type:"breadboard",row:"-",col:"25"};let d,h;this.opts.boardDef.attachPowerOnRight?(d=c,h=u):(d=a,h=l);let p=[],f=[],m=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:this.allocLocation("ground",{referenceBBPin:h}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:t}),e.bottomThreeVolt&&e.bottomGround?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:this.allocLocation("threeVolt",{referenceBBPin:h}),color:n}):e.bottomFiveVolt&&e.bottomGround&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:this.allocLocation("fiveVolt",{referenceBBPin:h}),color:i}),e.topThreeVolt?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:s},color:n}):e.bottomThreeVolt&&f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:s},color:i}),e.topFiveVolt&&!e.topThreeVolt?m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:i});let g=[];p.length>0&&g.push({wireIndices:p.map(((e,t)=>t))});let b=p.length;return f.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b))}),m.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b+f.length))}),{wires:p.concat(f).concat(m),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let i=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(i=i.map(((e,n)=>{if(e)return e;const r=i[1-n];return this.allocLocation(t[n],{referenceBBPin:r})})),i[0]&&i[1])return{start:i[0],end:i[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let i=t.startRowIdx+n.bbFit.partRelativeRowIdx;i>=7&&(i-=2);let r=e.visuals.getRowName(i),s=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:r,col:e.visuals.getColumnName(s)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,i)=>{let r=t[i],s=this.allocPartIRs(e.def,e.name,r);n=n.concat(s)}));const i=this.placeParts(n).map((e=>this.allocWireIRs(e))),s=i.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),i=t.map((e=>"threeVolt"===e)),s=t.map((e=>"fiveVolt"===e)),o=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=r(n),l=r(i),c=r(s),u=r(o);return{topGround:a&&!u,topThreeVolt:l&&!u,topFiveVolt:c&&!u,bottomGround:a&&u,bottomThreeVolt:l&&u,bottomFiveVolt:c&&u,singleGround:a,singleThreeVolt:l,singleFiveVolt:c}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(s);const o=this.allocPowerWires(this.powerUsage),a=i.map(((e,t)=>{const n=this.allocPart(e),i=e.wires.map((e=>this.allocWire(e)));if(i.some((e=>!e)))return;const r=[];e.wires.forEach(((e,t)=>{r[e.pinIdx]=t}));return{part:n,wires:i,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>r[e]))})))}})).filter((e=>!!e)),l=[o].concat(a).filter((e=>e.assembly&&e.assembly.length)),c=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:c}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,i,r){this.name=e,this.path=t,this.sourceReference=n,i&&(this.origin=i),r&&(this.adapterData=r)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,i=0,r=0){this.id=e,this.source=n,this.line=i,this.column=r,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,i,r){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof r&&(this.namedVariables=r),"number"==typeof i&&(this.indexedVariables=i)}};e.Breakpoint=class{constructor(e,t,n,i){this.verified=e;const r=this;"number"==typeof t&&(r.line=t),"number"==typeof n&&(r.column=n),i&&(r.source=i)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,i,r){const s={command:t};if(n&&Object.keys(n).length>0&&(s.arguments=n),this.send("request",s),r){this._pendingRequests[s.seq]=r;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[s.seq];n&&(delete this._pendingRequests[s.seq],n(new e.Response(s,"timeout")))}),i)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=i;class r extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,i){let s;"number"==typeof t?(s={id:t,format:n},i&&(s.variables=i),s.showUser=!0):s=t,e.success=!1,r.formatPII(s.format,!0,s.variables),e.body||(e.body={}),e.body.error=s,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,(function(e,i){return t&&i.length>0&&"_"!==i[0]?e:n[i]&&n.hasOwnProperty(i)?n[i]:e}))}}r._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,i=arguments[1],r=i>>0,s=r<0?Math.max(n+r,0):Math.min(r,n),o=arguments[2],a=void 0===o?n:o>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;s<l;)t[s]=e,s++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const i=arguments[1];let r=0;for(;r<n;){const n=t[r];if(e.call(i,n,r,t))return n;r++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const i=t(e),r=t(n);let s=0;for(;i[s]===r[s]&&(s++,s!==i.length&&s!==r.length););const o=i.slice(s),a=r.slice(s);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},i=e.runtime.currFrame;for(;null!=i;)n.breakpointIds.push(i.lastBrkId),i=i.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let i=e.RefObject.toDebugString(t),r=i.startsWith("[")?"array":i;return{id:t.id,preview:i,hasFields:null!==t.fields||i.startsWith("["),type:r}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(e,n,r,s){return function(e,r){const o={};for(let i of Object.keys(e))/^__/.test(i)||!/___\d+$/.test(i)||s&&-1===s.indexOf(i)||(o[i]=t(e[i],n));if(e.fields&&r)for(let s of r)s=s.substring(s.lastIndexOf(".")+1),o[s]=t(i(e.vtable.iface[s],e),n);if(e.fields)for(let i of Object.keys(e.fields).filter((e=>!e.startsWith("_"))))o[i]=t(e.fields[i],n);else Array.isArray(e.data)&&e.data.forEach(((e,i)=>{o[i]=t(e,n)}));return o}(e,r)}function i(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function r(e,i){let r=e.fn?e.fn.info:null;if(r){let s={thisParam:t(e.argL,i),params:[]};if(r.argumentNames){const n=r.argumentNames;s.params=n.map(((n,r)=>({name:n,value:t(e["arg"+r],i)})))}return{locals:n(e,i),funcInfo:r,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:s}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let i;if(n)for(const[e,r]of n)r.line<=t.line&&r.endLine>=t.line&&(i=[e,r]);return i?(i[1].verified=!0,i):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,i){const r=e.runtime.environmentGlobals;if(!Object.keys(r).length)return;const s=n.environmentGlobals={};Object.keys(r).forEach((n=>s[n]=t(e.runtime.environmentGlobals[n],i)))},e.getBreakpointMsg=function(t,i,s){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:i,globals:n(e.runtime.globals,o,void 0,s),stackframes:[]};for(;null!=t;){let e=r(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class s extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,i,r,s){this.breakpoints=r,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:i,boardDefinition:s})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const i=[];n.breakpoints.forEach((r=>{if(this.breakpoints){const[s,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),r);t.body.breakpoints.push(o),o.verified&&i.push(s)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(i),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:s.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",s.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",s.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(s.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(s.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}s.THREAD_ID=1,e.SimDebugSession=s;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const i=this.nextId();this._vars[i]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:i,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const i=t[n];let r,s=0;null===i?r="null":void 0===i?r="undefined":"object"==typeof i?(r="(object)",s=this.nextId(),this._vars[s]=this.getVariableValues(i)):r=i.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:r,variablesReference:s})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){function t(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}let n;function i(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function s(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}e.print=t,function(n){function r(n){n.origin;let r=n.data||{},s=r.type;if(s)switch(s){case"run":l(r);break;case"instructions":e.instructions.renderInstructions(r);break;case"stop":a();break;case"mute":c(r.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":t();break;case"recorder":!function(e){if(!o)return;switch(e.action){case"start":o.startRecording(e.width);break;case"stop":o.stopRecording()}}(r);break;case"screenshot":e.Runtime.postScreenshotAsync(r);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(r);break;case"pxteditor":break;case"debugger":o&&o.handleDebuggerMsg(r);break;case"simulator":let n=r;switch(n.command){case"focus":i("simulator.focus",{timestamp:n.timestamp});break;case"blur":i("simulator.blur",{timestamp:n.timestamp})}default:!function(e){if(!o||o.dead)return;o.board.receiveMessage(e)}(r)}}let o;function a(){o&&(o.kill(),o.board&&o.board.kill())}function l(t){a(),t.mute&&c(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);o=n,n.board.initAsync(t).then((()=>{n===o&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function c(t){e.AudioContextManager.mute(t)}n.start=function(){window.addEventListener("message",r,!1),n.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&s()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:n.frameid})},n.stop=a,n.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=i,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=s}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,i=.95,[r,s]=[816*i,1056*i],o=r-86.4,a=s-86.4,[l,c]=[1,1],u=24,d=o/c-48*c,h=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+u}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function p(t,n){let i=document.createElementNS("http://www.w3.org/2000/svg","svg"),r={l:0,t:0,w:0,h:0},s=document.createElementNS("http://www.w3.org/2000/svg","svg");i.appendChild(s),s.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};r.w=t.w,r.h=t.h;let a=e=>{r.h*=e,r.w*=e,o.width=r.w,o.height=r.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<r.w?a(n.cmpWidth/r.w):n.cmpHeight&&n.cmpHeight<r.h&&a(n.cmpHeight/r.h),e.svg.hydrate(s,o);let l=r.l,c=r.t,u=r.w,d=r.h,h=e=>{if(e<r.l){let t=r.l-e;r.l=e,r.w+=t}},p=e=>{let t=r.l+r.w;if(t<e){let n=e-t;r.w+=n}},f=e=>{if(e<r.t){let t=r.t-e;r.t=e,r.h+=t}},m=e=>{let t=r.t+r.h;if(t<e){let n=e-t;r.h+=n}},[g,b]=[-.3,.3];const y=[1.4,1];if(n&&n.top){let t=n.topSize,r=t/y[0],s=t/y[1],[o,a]=[l+u/2,c-3-s/2],d=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(d,"cmp-lbl"),i.appendChild(d);let m=r*n.top.length;f(a-s/2),h(o-m/2),p(o+m/2)}if(n&&n.bot){let t=n.botSize,r=t/y[0],s=t/y[1],[o,a]=[l+u/2,c+d+3+s/2],f=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(f,"cmp-lbl"),i.appendChild(f);let v=r*n.bot.length;m(a+s/2),h(o-v/2),p(o+v/2)}if(n&&n.right){let t=n.rightSize,r=t/y[1],s=t/y[0]*n.right.length,[o,a]=[l+u+5+s/2,c+d/2],h=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(h,"cmp-lbl"),i.appendChild(h),f(a-r/2),p(o+s/2),m(a+r/2)}if(n&&n.left){let t=n.leftSize,r=t/y[1],s=t/y[0]*n.left.length,[o,a]=[l-5-s/2,c+d/2],u=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(u,"cmp-lbl"),i.appendChild(u),f(a-r/2),h(o-s/2),m(a+r/2)}let v={viewBox:`${r.l} ${r.t} ${r.w} ${r.h}`,width:1.7*r.w,height:1.7*r.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(i,v);let w=document.createElement("div");return w.appendChild(i),w}function f(t,n){let i,r=e.runtime.board;if("wire"==t)i=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){i=(0,r.builtinPartVisuals[n.builtIn])([0,0])}else i=e.visuals.mkGenericPartSVG(n)}return p(i,n)}function m(t,n,i=!1){const r={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:i,partsList:[]};let s=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:r.boardDef.visual,boardDef:r.boardDef,wireframe:r.wireframe}),r),o=s.getView();return e.U.addClass(o,"board-svg"),s}function g(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function b(t){let i=g();var r;let s=p((r=t.boardDef,e.visuals.mkBoardView({visual:r.visual,boardDef:r}).getView()),{left:n(1),leftSize:30,cmpScale:.17});i.appendChild(s);let o=p(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return i.appendChild(o),t.allCmps.forEach((t=>{let r=1;"buttonpair"===t.visual.builtIn&&(r=2);let s=f(t.visual,{left:n(r),leftSize:30,cmpScale:.3});e.U.addClass(s,"partslist-cmp"),i.appendChild(s)})),t.allWireColors.forEach((r=>{let s=t.colorToWires[r].length,o=t.boardDef.pinStyles[r]||"female",a=f("wire",{left:n(s),leftSize:20,wireClr:r,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),i.appendChild(a)})),i}function y(t,n){let i=g(),r=m(n,465,!0);!function(t,n,i){let r=t.getView();n>0&&e.U.addClass(r,"grayed");for(let r=0;r<=n;r++){let s=i.stepToCmps[r];s&&s.forEach((i=>{let s=t.addPart(i);r===n&&(i.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(s.element,"notgrayed"))}));let o=i.stepToWires[r];o&&o.forEach((e=>{let i=t.addWire(e);i&&r===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(i))}))}}(r,t,n),i.appendChild(r.getView());let s=document.createElement("div");e.U.addClass(s,"panel-num-outer"),e.U.addClass(s,"noselect"),i.appendChild(s);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",s.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),i.appendChild(a);let l=n.stepToWires[t]||[],c=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let i=!1;"dalboard"==t.end.type&&(i="croc"==n.boardDef.pinStyles[t.end.pin]);let r=f("wire",{top:c(t.end),topSize:10,bot:c(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:i});e.U.addClass(r,"cmp-div"),a.appendChild(r)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,i)=>{let r;if(n){let{row:e,col:t}=n;r=`(${e},${t})`}else r="";let s=1.5;"buttonpair"===t.visual.builtIn&&(s*=.5);let o=f(t.visual,{top:r,topSize:10,cmpHeight:50,cmpScale:s});e.U.addClass(o,"cmp-div"),a.appendChild(o)}))})),i}function v(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const i={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(i),e.runtime.board=null,e.initCurrentRuntime(i);let r=document.createElement("style");r.textContent+=h,document.head.appendChild(r);const s=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),i=[],r=[],s=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,o)=>{e.part&&t&&(r[s+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(i[s+o]=e.wireIndices.map((e=>n[e])))})),s+=e.assembly.length}));let o=s-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),c={},u=[];return l.forEach((e=>{c[e.color]||(c[e.color]=[],u.push(e.color)),c[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:i,stepToCmps:r,allWires:l,allCmps:a,lastStep:o,colorToWires:c,allWireColors:u}}({boardDef:n.boardDef,partDefs:s,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=m(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=b(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=v,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",v(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,i,r,s,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class c{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=c;class u{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=u;class d extends c{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=d;class h extends c{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=h,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new h;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let i=e.getResume();i(t instanceof h?new u(t.func,t.fields,n):new u(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const i=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},r=e=>i(""+Math.round(e),6),s=(e,n)=>{i(Math.round(n)+"",8),t+=" /",r(e),t+=" =",r(n/e)};for(let i of e.split(/\n/)){if(!i)continue;if(!/^\d/.test(i))continue;const e=i.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),o=e[2],a=25,t+=o.length>=a?o:(o+" ").slice(0,a);const c=parseInt(e[0]),u=parseInt(e[1]);s(c,u),t+=" |",s(c-l.stops,u-l.us),t+=" ~";const d=parseInt(e[3]);r(d),l.meds.length>10&&l.meds.shift(),l.meds.push(d);const h=l.meds.slice();h.sort(((e,t)=>e-t));const p=h[h.length>>1];t+=" ~~",r(p),l.stops=c,l.us=u,t+="\n"}var o,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends c{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class f extends c{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=c.toAny(t.val)})),e}}function m(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=f,e.dumpLivePointers=m,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(i=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(r=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){m()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let i=e.getConfig(t);return null==i?n:i},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function i(e,t){if(t+="",e instanceof d){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function r(e,t,n){if(t+="",e instanceof d){return void(e.fields[t]=n)}let i=e.findIdx(t);i<0?e.data.push({key:t,val:n}):e.data[i].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,i){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=i,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new f},n.mapGet=function(e,t){return i(e,n.mapKeyNames[t])},n.mapSet=function(e,t,i){return r(e,n.mapKeyNames[t],i)},n.mapGetByString=i,n.mapDeleteByString=function(e,t){e instanceof f||n.panic(923);let i=e.findIdx(t);return i>=0&&e.data.splice(i,1),!0},n.mapSetGeneric=r,n.mapGetGeneric=i,n.mapSetByString=r,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof f)for(let e of t.data)n.push(e.key);return n}}(s=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new d;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=s.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){s.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let i=e.RefObject.toDebugString(this.data[n]);if(t.length+i.length>100){0==n&&(t+=i.substr(0,100)),t+="...";break}t+=i}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,i,r,s,o,a,l,c;e.RefCollection=t,function(n){function i(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function r(t,n,i){return e.pxtrt.nullCheck(t),t.indexOf(n,i)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=i,n.insertAt=function(t,n,i){e.pxtrt.nullCheck(t),t.insertAt(n,i)},n.setAt=function(t,n,i){e.pxtrt.nullCheck(t),t.setAt(n,i)},n.indexOf=r,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let s=r(t,n,0);return s>=0?(i(t,s),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const i=Math.pow(10,t++);n=Math.round(e*i+Number.EPSILON)/i}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(i=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(r=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return i.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(s=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(i.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,i){return e.pxtrt.nullCheck(t),t.slice(n,n+i)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,i)},t.lastIndexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,i)},t.includes=function(t,n,i){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,i)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class u extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return c.toHex(this)}}e.RefBuffer=u,function(t){let n;function i(t){let i=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),r=!1;i<0&&(r=!0,i=-i);let s=!1;return i>=10&&(s=!0,i/=10),{size:i,signed:r,swap:s,isFloat:t>=n.Float32LE}}function r(e){return new u(new Uint8Array(e))}function s(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function o(e,t){return s(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){s(e,t)&&(a(e),e.data[t]=n)}function c(e,t,n=0,i=-1){n<0||n>e.data.length||(i<0&&(i=e.data.length),i=Math.min(i,e.data.length-n),a(e),e.data.fill(t,n,n+i))}function d(e,t,n,i,r){if(n.buffer===e.buffer)d(e,t,n.slice(i,i+r),0,r);else for(let s=0;s<r;++s)e[t+s]=n[i+s]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let r=i(t);if(r.isFloat){let t=e.data.buffer.slice(n,n+r.size);if(r.swap){new Uint8Array(t).reverse()}return 4==r.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let s=0;for(let t=0;t<r.size;++t){s<<=8;let i=r.swap?n+t:n+r.size-t-1;s|=e.data[i]}if(r.signed){let e=32-8*r.size;s=s<<e>>e}else s>>>=0;return s},t.setNumber=function(e,t,n,r){let s=i(t);if(s.isFloat){let t=new Uint8Array(s.size);4==s.size?new Float32Array(t.buffer)[0]=r:new Float64Array(t.buffer)[0]=r,s.swap&&t.reverse();for(let i=0;i<s.size;++i)e.data[n+i]=t[i]}else for(let t=0;t<s.size;++t){let i=s.swap?n+s.size-t-1:n+t;e.data[i]=255&r,r>>=8}},t.createBuffer=r,t.createBufferFromHex=function(e){let t=r(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=c,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new u(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.data.length;++i)n+=t[e.data[i]>>4],n+=t[15&e.data[i]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const h=-2147483648;t.shift=function(e,t,n,i){i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h||0!=i&&0!=t&&t!=h&&(t<=-i||t>=i?c(e,0):(a(e),t<0?(t=-t,d(e.data,n+t,e.data,n,i-t),e.data.fill(0,n,n+t)):(i-=t,d(e.data,n,e.data,n+t,i),e.data.fill(0,n+i,n+i+t))))},t.rotate=function(e,t,n,i){if(i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h)return;a(e),t<0&&(t+=i<<8),(t%=i)<0&&(t+=i);let r=e.data,s=t,o=0,l=s,c=i;for(;o!=l;){let e=r[o+n];r[o+++n]=r[l+n],r[l+++n]=e,l==c?l=s:o==s&&(s=l)}},t.write=function(e,t,n,i=0,r=-1){r<0&&(r=n.data.length),i<0||t<0||t>e.data.length||(r=Math.min(n.data.length-i,e.data.length-t))<0||(a(e),d(e.data,t,n.data,i,r))}}(c=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,s){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(s);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",i=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;a=i}else a=":x"==s?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==s?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==s?a=1==o?"":"s":":q"==s?a=i(a):":jq"==s?a=r(a):":uri"==s?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==s?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==s&&(a=(100*o).toFixed(1).toString()+"%"),a}))}function i(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function r(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...i){let r=t[e]||e;return r=r.replace(/^\{(id|loc):[^\}]+\}/g,""),n(r,i)},e.fmt_va=n,e.htmlEscape=i,e.jsStringQuote=r}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,U,pxtcore;!function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let i;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return i||(i="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*i()};const r=Promise.resolve();async function s(e,t,n){let i=0;const r=[],s=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,r=t[e];s[e]=await n(r)}})();r.push(e)}try{await Promise.all(r)}catch(e){throw i=t.length,e}return s}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function c(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){r.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return s(1,e,t)},e.promisePoolAsync=s,e.promiseTimeout=async function(e,t,n){let i,r;const s=new Promise(((t,s)=>{r=t,i=setTimeout((()=>{r=void 0,clearTimeout(i),s(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,s]).then((e=>(r&&(clearTimeout(i),r()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let r=e.charCodeAt(i);if(r<=127)n+=e.charAt(i);else if(r<=2047)n+=String.fromCharCode(192|r>>6,128|63&r);else{if(!t&&55296<=r&&r<=56319){let t=e.charCodeAt(++i);isNaN(t)||(r=65536+(r-55296<<10)+(t-56320))}n+=r<=65535?String.fromCharCode(224|r>>12,128|r>>6&63,128|63&r):String.fromCharCode(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let r=t(e);i.hasOwnProperty(r)||(i[r]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}poke(){this.lock=!0;let e=this.events;return this.events=[],U.promiseMapAllSeries(e,(e=>U.promiseMapAllSeries(this.handlers,(t=>this.runtime.runFiberAsync(t,...this.valueToArgs?this.valueToArgs(e):[e]))))).then((()=>this.events.length>0?this.poke():(this.lock=!1,this._addRemoveLog.forEach((e=>{e.log===LogType.BackAdd?this.addHandler(e.act):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act)})),this._addRemoveLog=[],Promise.resolve())))}get handlers(){return this._handlers}setHandler(e){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet}):this._handlers=[e]}addHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackAdd});else{-1==this._handlers.indexOf(e)&&this._handlers.push(e)}}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove});else{let t=this._handlers.indexOf(e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let i=0;for(;e.hasOwnProperty("arg"+i);)i++;const r=e;for(let e=i;e>0;e--)r["arg"+e]=r["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,i){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=i}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let i=Date.now();return i-lastYield>=20&&(lastYield=i,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),5),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,i){let r={};__this.loopLock=r,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=i;const{msg:s,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(s,o),Runtime.postMessage(s),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==r),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,i){if(setupResume(t,n),"<main>"===i.functionName||"main.ts"===i.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let i;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(i=pxsim.dumpHeap(e,dbgHeap,n.fields))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:i})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:i}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,i),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let i=1;for(;e.hasOwnProperty("arg"+i);)n["arg"+(i-1)]=e["arg"+i],i++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let i=r=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>i(r)));pxsim.runtime=__this;let s=Date.now();if(s-n>3&&(lastYield=s),U.assert(e.pc==t),r instanceof pxsim.FnWrapper){let t=r,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},i={};return __this.loopLock=i,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===i),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=r,loop(e)};return i}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,i){return new Promise(((r,s)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(r),pxtcore.runAction(e,[t,n,i])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function i(t,n,r=null){if(!(n instanceof pxsim.RefObject))return;const s=n;if(s.gcIsStatic())return;const o=e[s.id];if(o)return void(r&&o.pointers.push([r,t]));const a={obj:s,path:null,pointers:[[r,t]]};e[s.id]=a,s.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&i(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))i(e.replace(/___\d+$/,""),this.globals[e]);const r=this.otherFrames.slice();this.currFrame&&r.indexOf(this.currFrame)<0&&r.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const r=n[t];r instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),i(e+"."+t,r))}if(n.caps)for(let t of n.caps)i(e+".cap",t)}}const s=Object.keys(e).map((t=>e[t]));s.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,i]of e.pointers){if(null==n)return void(e.path=i);o(n);const r=n.path+"."+i;(!t||t.length>r.length)&&(t=r)}e.path=t};s.forEach(o);const a=[t];for(const e of s){const i=e.obj.gcSize(),r=e.obj.gcKey();n.hasOwnProperty(r)||a.push(n[r]={count:0,size:0,name:r});const s=n[r];s.size+=i,s.count++,t.size+=i,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const c=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=c(4*e.size)+c(e.count)+" "+e.name+"\n";const u=e=>c(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,d=s.slice(0,20).map(u).join("\n");let h="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,i=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);h=s.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!i(e.obj))).map(u).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+d+"\n\nNew Objects:\n"+h}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;return(t?t.screenshotAsync().catch((e=>{console.debug("screenshot failed")})):Promise.resolve(void 0)).then((t=>Runtime.postMessage({type:"screenshot",data:t,delay:e&&e.delay})))}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{if(this.recordingLastImageData&&t&&this.recordingLastImageData.data.byteLength==t.data.byteLength){const e=this.recordingLastImageData.data,n=t.data,i=e.byteLength;let r=0;for(r=0;r<i&&e[r]==n[r];++r);if(r==i)return}this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e})}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let i=t.lastFewPtr++;i>=t.lastFew.length&&(i=0,t.lastFewPtr=1),t.lastFew[i]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),i=new TimeoutScheduled(-1,e,t,n);return i.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(i);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(i),i.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}}pxsim.Runtime=Runtime;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const i="pxtdriver";e.SimulatorDriver=class{constructor(n,i={}){this.container=n,this.options=i,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),i.parentOrigin&&this._allowedOrigins.push(i.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const r=null==i?void 0:i.messageSimulators;r&&Object.keys(r).map((e=>r[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:i,width:e})}stopRecording(){this.postMessage({type:"recorder",source:i,action:"stop"})}setFrameState(n){const i=n.nextElementSibling,r=i.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:i.style.display="",i.className="",r.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?i.style.display="none":(i.style.display="",i.className="videoplay xicon icon"),r.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),i.style.display="none",r.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const i=this.loanedIFrame();return i&&!t&&n.unshift(i),n}getSimUrl(){const e=this.options.simUrl||(window.pxtConfig||{}).simUrl||`${location.origin}/sim/simulator.html`;try{return new URL(e)}catch(t){return new URL(e,location.origin)}}postMessage(t,n,i){var r;if(this.hwdbg)return void this.hwdbg.postMessage(t);const s=this.dependentEditors();let o=this.simFrames();i&&(o=o.filter((e=>e.id===i)));const a=t;if(n&&(null==a?void 0:a.broadcast)){const i=!!(null===(r=this._currentRuntime)||void 0===r?void 0:r.single),a=window.parent&&window.parent!==window.window?window.parent:window.opener;if(this.options.nestedEditorSim&&a){if(n!==a){const e=this.options.parentOrigin||window.location.origin;a.postMessage(t,e)}}else if(s)s.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!i){const n="messagepacket"===t.type&&t.channel,i=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(i){let t=o.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const r=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&i.localHostUrl||i.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||""));let s=this.createFrame(r);this.container.appendChild(s),t=s.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(s,"simmsg"),e.U.addClass(s,"simmsg"+n),i.permanent&&(t.dataset.permanent="true"),this.startFrame(t),o=this.simFrames()}}else{const e=o.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),o=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<o.length;++e){const i=o[e];if((!n||i.contentWindow!=n)&&(i.contentWindow&&(this.postMessageCore(i,t),"recorder"==t.type&&"start"==t.action)))break}}postMessageCore(t,n){var i,r,s,o;if(t.contentWindow.postMessage(n,t.dataset.origin),e.U.isLocalHostDev()&&(null===(r=null===(i=pxt)||void 0===i?void 0:i.appTarget)||void 0===r?void 0:r.id))try{t.contentWindow.postMessage(n,`https://trg-${null===(o=null===(s=pxt)||void 0===s?void 0:s.appTarget)||void 0===o?void 0:o.id}.userpxt.io/---simulator`)}catch(e){}}createFrame(n){const i=document.createElement("div");i.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";const s=(n||this.getSimUrl())+"#"+r.id;r.src=s,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(s).origin||"*",i.appendChild(r);const o=document.createElement("i");o.className="videoplay xicon icon",o.style.display="none",o.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),i.appendChild(o);const a=document.createElement("div");return a.className="ui active loader",o.style.display="none",i.appendChild(a),this._runOptions&&this.applyAspectRatioToFrame(r),i}preload(e){this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.clearDebugger(),this.postMessage({type:"stop",source:i}),this.setState(n?t.Starting:t.Stopped),e&&this.unload()}suspend(){this.postMessage({type:"stop",source:i}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:i,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:i})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,i,r,s;let o=t;if(void 0===o){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(o=t)}if(void 0===o){const t=e.dataset.messagechannel;if(t){const e=null===(r=null===(i=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===i?void 0:i[t])||void 0===r?void 0:r.aspectRatio;e&&(o=e)}}void 0===o&&(o=(null===(s=this._runOptions)||void 0===s?void 0:s.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/o+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}run(e,t={}){this._runOptions=t,this.runId=this.nextId(),this._currentRuntime={type:"run",source:i,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies},this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){if(!this._currentRuntime||!e.contentWindow)return!1;const t=JSON.parse(JSON.stringify(this._currentRuntime));return t.frameCounter=++this.frameCounter,t.options={theme:this.themes[this.nextFrameId++%this.themes.length]},t.id=`${t.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=t.id,e.id!==this.debuggingFrame&&(t.traceDisabled=!0,t.breakOnStart=!1),this.postMessageCore(e,t),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleMessage(e,n){switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&(this.startFrame(n),this.options.revealElement&&this.options.revealElement(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,i=document.getElementById(n);if(i){const n=e;if(n.runtimeid==i.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,i=document.getElementById(n);i&&(i.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(i));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let r;switch(e){case n.Resume:r="resume",this.setState(t.Running);break;case n.StepInto:r="stepinto",this.setState(t.Running);break;case n.StepOut:r="stepout",this.setState(t.Running);break;case n.StepOver:r="stepover",this.setState(t.Running);break;case n.Pause:r="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:r,source:i})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const i=e;if(this.state==t.Running){if(i.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(i);let e=i.exceptionMessage+"\n";for(let t of i.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}i.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const i=e.req_seq;if(i){const{resolve:t}=this.debuggerResolvers[i];t&&(delete this.debuggerResolvers[i],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((i,r)=>{const s=this.debuggerSeq++;this.debuggerResolvers[s.toString()]={resolve:i,reject:r},this.postDebuggerMessage(e,t,s,n)}))}postDebuggerMessage(e,t={},n,r){const s=JSON.parse(JSON.stringify(t));s.type="debugger",s.subtype=e,s.source=i,n&&(s.seq=n),this.postMessage(s,void 0,r)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,i,r=!1){let s=(i?"back":"fore")+":"+t+":"+n;return!this.queues[s]&&r&&(this.queues[s]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[s]}listen(e,t,n){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let i=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?i.addHandler(n):i.setHandler(n),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let i=[this.start(0,0,n)];return 0==e&&0==t||(t&&i.push(this.start(0,t,n)),e&&i.push(this.start(e,0,n)),e&&t&&i.push(this.start(e,t,n))),i}queue(t,n,i=null){if(e.runtime.pausedOnBreakpoint)return;const r=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;r&&(t=this.notifyID);let s=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(s,(e=>e?e.push(i,r):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function i(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,i,r,s,o=0,a=!1;function l(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),n}function c(){T(0),o=0,s&&s.pause()}function u(){c(),x()}function d(e,t){e.gain.value&&e.gain.setTargetAtTime(0,l().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.mute=function(e){a=e,u();const t=l();!e&&t&&"suspended"===t.state&&t.resume()},t.stopAll=u,t.stop=function(){c(),function(){if(r){try{d(r,i)}catch(e){}r=void 0,i=void 0}}()},t.frequency=function(){return o};const h=[null,"triangle","sawtooth","sine"];let p,f,m=[],g=[];function b(e,t){let n,i=h[e];if(i){let e=l().createOscillator();return e.type=i,e.frequency.value=t,e}if(4==e)n=function(){if(!f){const e=131072;f=l().createBuffer(1,e,l().sampleRate);const t=f.getChannelData(0);let n=251771520;for(let i=0;i<e;i+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[i]=1,t[i+1]=1,t[i+2]=-1,t[i+3]=-1):(t[i]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0)}return f}();else if(5==e)n=function(){if(!p){const e=1e5;p=l().createBuffer(1,e,l().sampleRate);const t=p.getChannelData(0);let n=251771520;for(let i=0;i<e;i++)n^=n<<13,n^=n>>17,n^=n<<5,t[i]=(1023&n)/512-1}return p}();else if(11<=e&&e<=15)n=function(e){if(!g[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),i=n.getChannelData(0);for(let n=0;n<t;n++)i[n]=n<e/100*t?1:-1;g[e]=n}return g[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!m[e]){const t=1024,n=l().createBuffer(1,t,l().sampleRate),i=n.getChannelData(0),r=[770763591,3356908179],s=[15,31,63];for(let n=0;n<t;n+=4){let t,o=n/4;o&=s[e-4],t=0!=(r[o>>5]&1<<(31&o)),t?(i[n]=1,i[n+1]=1,i[n+2]=-1,i[n+3]=-1):(i[n]=0,i[n+1]=0,i[n+2]=0,i[n+3]=0)}m[e]=n}return m[e]}(e-16+4)}let r=l().createBufferSource();r.buffer=n,r.loop=!0;return 4==e||16<=e&&e<=18?r.playbackRate.value=t/(l().sampleRate/4):5!=e&&(r.playbackRate.value=t/(l().sampleRate/1024)),r}const y=[];class v{mute(){this.gain?d(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=y.indexOf(this);e>=0&&y.splice(e,1),this.mute()}}let w=1;function x(){for(w++;y.length;)y[0].remove()}function k(t){const i=w;let r=l(),s=0,o=new v,c=-1,u=-1,d=0;y.length>5&&y[0].remove(),y.push(o);const h=(e,t)=>e/1024/4*(t?.5:1),p=()=>{o.mute(),d=0,c=-1,u=-1},f=()=>{if(s>=t.data.length||!t.data[s])return e.U.delay(d).then(p);const m=t.data[s],g=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+2),y=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+4),v=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+6),x=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+8),k=e.BufferMethods.getNumber(t,e.BufferMethods.NumberFormat.UInt16LE,s+10),A=11<=m&&m<=15,T=4==m||16<=m&&m<=18,E=h(v,A),C=h(x,A);if(!r||i!=w)return e.U.delay(y);if(c!=m||u!=g||g!=k){if(o.generator)return e.U.delay(d).then((()=>(p(),f())));if(o.generator=a?null:b(m,g),!o.generator)return e.U.delay(y);if(c=m,u=g,o.gain=r.createGain(),o.gain.gain.value=0,o.gain.gain.setTargetAtTime(E,n.currentTime,.015),k!=g)if(null!=o.generator.frequency){o.generator.frequency.linearRampToValueAtTime(k,r.currentTime+(d+y)/1e3)}else if(null!=o.generator.playbackRate){const e=T?4:1024;o.generator.playbackRate.linearRampToValueAtTime(k/(l().sampleRate/e),r.currentTime+(d+y)/1e3)}o.generator.connect(o.gain),o.gain.connect(r.destination),o.generator.start()}s+=12,o.gain.gain.setValueAtTime(E,r.currentTime+d/1e3),d+=y;const S=0!==C&&y>50?(d-50)/1e3:(d-10)/1e3;return o.gain.gain.linearRampToValueAtTime(C,r.currentTime+S),f()};return f().then((()=>o.remove()))}function A(e,t){if(e<0)return;o=e;let n=l();if(n){t=Math.max(0,Math.min(1,t));try{i||(i=n.createOscillator(),r=n.createGain(),r.gain.value=0,i.type="triangle",i.connect(r),r.connect(n.destination),i.start(0)),T(t)}catch(e){return i=void 0,void(r=void 0)}i.frequency.value=e,T(t)}}function T(e){(null==r?void 0:r.gain)&&r.gain.setTargetAtTime(a?0:e,n.currentTime,.015)}t.muteAllChannels=x,t.queuePlayInstructions=function(t,n){const i=w;e.U.delay(t).then((()=>i!=w?Promise.resolve():k(n)))},t.playInstructionsAsync=k,t.tone=A,t.setCurrentToneGain=T,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const i="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n}(e.data));s=new Audio(i),a&&(s.volume=0),s.onended=()=>n(),s.onpause=()=>n(),s.onerror=()=>n(),s.play()})):Promise.resolve()};t.playPCMBufferStreamAsync=function(e,t,n=.3,i){return new Promise((r=>{let s=[],o=l().currentTime,c=!1;function u(){const t=i&&i();for(;!c&&s.length<3&&!t;){const t=e();if(!t||!t.length){c=!0;break}d(t)}c&&0===s.length&&(h.remove(),r&&r(),r=void 0)}function d(e){const n=l().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const i=l().createBufferSource();s.push(i),i.connect(h.gain),i.buffer=n,i.addEventListener("ended",(()=>{s.shift().disconnect(),u()})),i.start(o),o+=n.duration}const h=new v;h.gain=l().createGain(),h.gain.gain.value=0,a||h.gain.gain.setValueAtTime(n,l().currentTime),h.gain.connect(l().destination),y.length>5&&y[0].remove(),y.push(h),u()}))},t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,i=15&t[0],r=t[1]||0,s=(o=r,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?c():9==n&&(A(s,1),9==i&&setTimeout((()=>c()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=i,e.pointerEvents=i()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function i(e,t){let n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,i]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==i.x&&0==i.y,"el1 and el2 x,y offsets not supported");let r=(t,n,i)=>e.svg.hydrate(t,{x:n,y:i}),s=(t,n,i)=>e.svg.hydrate(t,{width:`${n}px`,height:`${i}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,c=n.h*a;s(n.el,l,c);let u=1*i.w,d=1*i.h;s(i.el,u,d);let[h,p,f,m]=t.margin,g=t.middleMargin,b=Math.max(l,u),y=p+(b-l)/2,v=h;r(n.el,y,v);let w=p+(b-u)/2,x=v+c+g;r(i.el,w,x);let k=[v,v+c,x,x+d],A=p+b+m,T=h+c+g+d+f,E=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${A} ${T}`,class:"sim-bb"});((t,n,i)=>{n&&e.svg.hydrate(t,{width:n}),i&&e.svg.hydrate(t,{height:i})})(E,t.maxWidth,t.maxHeight),r(E,0,0);let C=e.svg.child(E,"g");return E.appendChild(n.el),E.appendChild(i.el),{under:C,over:e.svg.child(E,"g"),host:E,edges:k,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+y,n*a+v]},toHostCoord2:e=>{let[t,n]=e;return[1*t+w,1*n+x]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let i=n(t.imageUnitDist,t.targetUnitDist),r=i(t.width),s=i(t.height),o=e.svg.elt("image",{width:r,height:s});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:r,h:s,x:0,y:0}},t.findDistSqrd=i,t.findClosestCoordIdx=function(e,t){return t.map((t=>i(e,t))).reduce(((e,t,n,i)=>t<i[e]?n:e),0)},t.mkTxt=function(t,n,i,r,s,o,a){let l=e.svg.elt("text");a=a||.3;const c=(o=o||-.33333)*i*s.length,u=a*i;return e.svg.hydrate(l,{style:`font-size:${i}px;`,transform:`translate(${t} ${n}) rotate(${r}) translate(${c} ${u})`}),e.U.addClass(l,"noselect"),l.textContent=s,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,i,[r,s,o]=e,[a,l,c]=[r/255,s/255,o/255],u=Math.min(a,l,c),d=Math.max(a,l,c),h=d-u,p=d+u;return i=p/2*100,0===h?n=t=0:(d===a?t=(l-c)/h%6*60:d===l?t=60*((c-a)/h+2):d===c&&(t=60*((a-l)/h+4)),n=i>50?h/(2-p)*100:h/p*100),[Math.floor(t),Math.floor(n),Math.floor(i)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function i(e,n,i){let r={class:e,d:n};i&&(r.title=i);let s=t.elt("path");return t.hydrate(s,r),s}function r(e,n=!1){let i=t.elt("linearGradient");t.hydrate(i,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(i,"stop",{offset:"0%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"});return i}function s(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,i){e.setAttribute("transform",`translate(${t},${n}) rotate(${i+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let i in n)"title"==i?t.title(e,n[i]):e.setAttributeNS(null,i,n[i])},n.elt=function(e,n){let i=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(i,n),i},n.child=function(e,n,i){let r=t.elt(n,i);return e.appendChild(r),r},n.mkPath=i,n.path=function(e,t,n,r){let s=i(t,n,r);return e.appendChild(s),s},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let i=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(i=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!i||(i=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,i,r,s){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,i&&i(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!o||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{o=!1,r&&r(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{o=!1,r&&r(e)}),!1),t.addEventListener("keydown",(e=>{o=!1,s&&s(e)}))},n.mkLinearGradient=r,n.linearGradient=function(e,t,n=!1){let i=r(t,n);return e.appendChild(i),i},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let i=t.parentElement;i&&(i.removeChild(t),i.appendChild(t))},n.mkTitle=s,n.title=function(e,t){let n=s(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,i){this.parts=[],this.boardView=n,this.opts=i,i.boardDef.pinStyles||(i.boardDef.pinStyles={}),this.state=i.state;let r=i.partsList,s=0<r.length||i.forceBreadboardLayout;if(s){this.breadboard=new t.Breadboard({wireframe:i.wireframe});const n=i.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:i.maxWidth,maxHeight:i.maxHeight}),a=o.under,l=o.over;this.view=o.host;const c=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,c,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const u=e.allocateDefinitions({boardDef:i.boardDef,partDefs:i.partDefs,fnArgs:i.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:r});u.partsAndWires.length||i.forceBreadboardLayout?(this.addAll(u),u.requiresBreadboard||i.forceBreadboardRender?u.hideBreadboard&&this.breadboard&&this.breadboard.hide():s=!1):s=!1}if(!s){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),i.maxWidth&&e.svg.hydrate(this.view,{width:i.maxWidth}),i.maxHeight&&e.svg.hydrate(this.view,{height:i.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.cloneNode(!0);t.setAttribute("width",this.view.width.baseVal.value+""),t.setAttribute("height",this.view.height.baseVal.value+"");const n=(new XMLSerializer).serializeToString(t),i="data:image/svg+xml,"+encodeURIComponent(n.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const r=document.createElement("img");r.onload=()=>{const n=document.createElement("canvas");n.width=r.width,n.height=r.height,e>0?(n.width=e,n.height=r.height*e/r.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const i=n.getContext("2d");i.drawImage(r,0,0,n.width,n.height),t(i.getImageData(0,0,n.width,n.height))},r.onerror=e=>{console.log(e),t(void 0)},r.src=i}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let i=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],r=this.state.builtinParts[e];i=t(),i.init(this.state.bus,r,this.view,n.params)}else{let e=n.visual;i=new t.GenericPart(e)}this.parts.push(i),this.partGroup.appendChild(i.element),i.overElement&&this.partOverGroup.appendChild(i.overElement),i.defs&&i.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=i.style||"";let r=n.startColumnIdx,s=n.startRowIdx,o={type:"breadboard",row:t.getRowName(s),col:t.getColumnName(r),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);i.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(i.element,l),e.U.addClass(i.element,"sim-cmp"),i.updateTheme(),i.updateState(),i}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,i=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));i&&n.forEach((t=>e.wires.push(this.addWire(t))));let r=t.part;!r||n&&!i||e.parts.push(this.addPart(r))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,i="#DD4BA0",r=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${i};\n stroke:${i};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${i};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const s=[4,4],o=t.BREADBOARD_MID_ROWS+s.length,a=25,l=[4,9,14,19],c=a+l.length,u=n*(t.BREADBOARD_MID_COLS+3),d=n*(o+4+5.5),h=2/3,p=d*h,f=.16666666666666669*d,m=(t.BREADBOARD_MID_COLS-1)*n,g=(u-m)/2,b=f+(p-(o-1)*n)/2,y=(c-1)*n,v=(u-y)/2,w=(f-15)/2,x=v,k=w+f+p,A=25.5,T=12,E=1.05,C=-90,S="abcdefghij".split("").reverse();function I(e){return`${e+1}`}function P(e){return S[e]}function U(t){let n=t.xOffset||0,i=t.yOffset||0,r=[],s=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],c=(e,t)=>{let n,i=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),i+=1;return i},u=0,d=l(t.rowIdxsWithGap);for(let h=0;h<t.rowCount;h++){let p=0,f=l(t.colIdxsWithGap),m=i+h*t.pinDist+u*t.pinDist,g=h+a;for(let i=0;i<t.colCount;i++){let a=n+i*t.pinDist+p*t.pinDist,l=i+o;const u=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:m}:{x:a-.5*t.w,y:m-.5*t.h}),s.appendChild(t.el),t.el);let d=u(t.mkPin()),h=u(t.mkHoverPin()),b=t.getRowName(g),y=t.getColName(l),v=t.getGroupName?t.getGroupName(g,l):null,w={el:d,hoverEl:h,cx:a,cy:m,row:b,col:y,group:v};r.push(w),p+=c(f,l)}u+=c(d,g)}return{g:s,allPins:r}}function _(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function N(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function O(n,i,r,s,o,a,l){let c=t.mkTxt(n,i,r,s,o);e.U.addClass(c,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(c,t)));let u=t.mkTxt(n,i,1.3*r,s,o);return e.U.addClass(u,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(u,t))),{el:c,hoverEl:u,txt:o,group:a}}t.getColumnName=I,t.getRowName=P,t.mkGrid=U;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let i=n[t];return i||null}getCoord(e){let{row:t,col:i,xOffset:r,yOffset:s}=e,o=this.getPin(t,i);if(!o)return null;let a=(r||0)*n,l=(s||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${u} ${d}`,class:"sim-bb",width:u+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=r,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:u,height:d,rx:4.5,ry:4.5});let i="sim-bb-channel-grad",o=e.svg.elt("linearGradient");e.svg.hydrate(o,{id:i,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(o);e.svg.child(o,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(o,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"100%",style:"stop-color: #AAA;"});const c=(t,n,r)=>{let s=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${r||""}`,y:t-n/2,width:u,height:n});return s.setAttribute("fill",`url(#${i})`),s};c(f+p/2,15,"sim-bb-mid-channel"),c(f,.75,"sim-bb-sml-channel"),c(f+p,.75,"sim-bb-sml-channel");const h=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${I(n)}`,m=e=>0===e?"-":"+",S=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${m(e)}${n}`};let D=U({xOffset:g,yOffset:b,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:_,mkHoverPin:N,getRowName:P,getColName:I,getGroupName:h,rowIdxsWithGap:s});D.g;this.allPins=this.allPins.concat(D.allPins);let R=U({xOffset:x,yOffset:k,rowCount:2,colCount:a,pinDist:n,mkPin:_,mkHoverPin:N,getRowName:m,getColName:I,getGroupName:S,colIdxsWithGap:l});R.g;this.allPins=this.allPins.concat(R.allPins);let M=U({xOffset:v,yOffset:w,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:_,mkHoverPin:N,getRowName:m,getColName:I,getGroupName:S,colIdxsWithGap:l.map((e=>e+a))});M.g;this.allPins=this.allPins.concat(M.allPins),this.allPins.forEach((t=>{let{el:n,row:i,col:r,hoverEl:s}=t,o=`(${i},${r})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(s,{title:o})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const L=(e,t,n,i,r,s)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return O(a+n,l+i,10.5,-90,r,s)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=I(e),i=0,r=L(P(i),n,0,-15,n,h(i,e));this.allLabels.push(r);let s=t.BREADBOARD_MID_ROWS-1,o=L(P(s),n,0,15,n,h(s,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=P(e),i=L(n,I(0),-15,0,n);this.allLabels.push(i);let r=L(n,I(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(r)}let B=[O(13.05,f+p+T,30,C,"-",S(0,0),["sim-bb-blue"]),O(12,f+p+f-T,A,C,"+",S(1,0),["sim-bb-red"]),O(u-T+E,f+p+T,30,C,"-",S(0,24),["sim-bb-blue"]),O(u-T,f+p+f-T,A,C,"+",S(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(B);let F=[O(13.05,12,30,C,"-",S(0,a),["sim-bb-blue"]),O(12,f-T,A,C,"+",S(1,a),["sim-bb-red"]),O(u-T+E,12,30,C,"-",S(0,49),["sim-bb-blue"]),O(u-T,f-T,A,C,"+",S(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(F);let $={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;($[n]=$[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:i}=e,r=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),s=r[n]||(r[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?B.filter((t=>t.group==e.group)).forEach((e=>s.push(e))):F.filter((t=>t.group==e.group)).forEach((e=>s.push(e)))}else{$[t].forEach((e=>s.push(e))),$[n].forEach((e=>s.push(e)))}}));const j=y+22.5,H=(j-y)/2,V=(t,n,i,r)=>{let s=e.svg.elt("rect");return e.svg.hydrate(s,{class:`sim-bb-bar ${r}`,x:t,y:n-1.5,width:j,height:3}),{el:s,group:i}};let G=[V(x-H,k-9,S(0,49),"sim-bb-blue"),V(x-H,k+n+9,S(1,49),"sim-bb-red"),V(v-H,w-9,S(0,0),"sim-bb-blue"),V(v-H,w+n+9,S(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(G),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let z=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),W=z.map((t=>e.svg.elt("g")));W.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),W.forEach(((t,n)=>e.U.addClass(t,`group-${z[n]}`)));let q={};z.forEach(((e,t)=>q[e]=W[t]));let J={};this.allPins.forEach(((e,t)=>{let n=e.group;(J[n]||(J[n]=[])).push(e)})),z.forEach((t=>{let n=J[t],[i,r]=[n.map((e=>e.cx)),n.map((e=>e.cy))],s=e=>e.reduce(((e,t)=>e<t?e:t)),o=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,c,u]=[s(i),o(i),s(r),o(r)],d=e.svg.elt("rect"),h=Math.max(l-a,1e-4),p=Math.max(u-c,1e-4);e.svg.hydrate(d,{x:a,y:c,width:h,height:p}),e.U.addClass(d,"sim-bb-group-wire"),q[t].appendChild(d)})),this.allPins.forEach((e=>{let t=q[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let Y=e.svg.elt("g");e.svg.hydrate(Y,{class:"sim-bb-group-misc"}),W.push(Y),this.allLabels.forEach((e=>{if(e.group){let t=q[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Y.appendChild(e.el),Y.appendChild(e.hoverEl)})),W.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:u,h:d}}highlightLoc(t){let{row:n,col:i}=t,r=this.rowColToPin[n][i],{cx:s,cy:o}=r;this.rowColToLbls[n][i].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,i=1.5*n,r=.66666*t.PIN_DIST,s=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,c=a.wireframe&&l.outlineImage?l.outlineImage:l.image,u=t.mkImageSVG({image:c,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),d=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=u.w,this.height=u.h;let h=u.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(h),this.background=h,e.svg.hydrate(h,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("circle"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map(((n,i)=>{let r=d(n.x)+t.PIN_DIST/2,s=d(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:r,yOffset:s,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:m,mkHoverPin:l.useCrocClips?f:g,getRowName:()=>`${i+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),y=[];b.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),y.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const v=(e,n,i,r,s)=>{let o,a;if("below"===s){a=e,o=n+12+.25*i*r.length}else{a=e,o=n-11-.32*i*r.length}return t.mkTxt(a,o,i,-90,r)};this.allLabels=this.allPins.map(((t,r)=>{let s=y[r];return((t,r,s,o)=>{let a=v(t,r,n,s,o);e.U.addClass(a,"sim-board-pin-lbl");let l=v(t,r,i,s,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:s}})(t.cx,t.cy,t.col,s.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,i,r){let s=e.svg.elt("rect");return e.svg.hydrate(s,{x:t,y:n,width:i,height:r,class:"gray-cover"}),s}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),i=this.findPin(t);n&&i&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(i.el,"highlight"),e.U.addClass(i.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let i=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(i)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,i=.7;function r(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let s;function o(t,n,i,r){const s=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,c]=n,u=c-a,d=[o,a+u*i],h=[l,c-u*i],p=e.svg.mkPath("sim-bb-wire",`M${s(t)} C${s(d)} ${s(h)} ${s(n)}`);return e.U.addClass(p,`wire-stroke-${r}`),p}function a(t,n,i){const r=e=>`${e[0]}, ${e[1]}`;let s=e.svg.mkPath("sim-bb-wire",`M${r(t)} L${r(n)}`);return e.U.addClass(s,`wire-stroke-${i}`),s}function l(i,r){const s=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=i[0],l=i[1],c=n/2+s/2;return e.svg.hydrate(o,{cx:a,cy:l,r:c,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${r}`),o.style["stroke-width"]=`${s}px`,o}function c(n,i,r){let s=.24*t.PIN_DIST,o=10*s,a=2*s,l=6*s,c=s;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),x=l,k=c,A=d-k/2,T=h+p*(g/2+x/2)-x/2;return e.svg.hydrate(w,{x:A,y:T,width:k,height:x,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,T),w:b+2*u,h:g+x}}function u(n,i,r){let s=.24*t.PIN_DIST;const o=4*s,a=10*s,l=3.5*s,c=3.5*s,u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("polygon"),g=a,b=o,y=d-b/2,v=h-g/2;const w=i?.15:.3,x=i?.7:1-.7,k=i?.3:.15;e.svg.hydrate(m,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([y+b*w,v],[y+b*(1-w),v],[y+b,v+g*x],[y+b*(1-k),v+g],[y+b*k,v+g],[y,v+g*x])}),e.svg.hydrate(m,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let A=e.svg.elt("rect"),T=l,E=c,C=d-E/2,S=h+p*(g/2+T/2)-T/2;return e.svg.hydrate(A,{x:C,y:S,width:E,height:T,class:"sim-bb-wire-bare-end"}),f.appendChild(A),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,S),w:b+2*u,h:g+T}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(s=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,i,r=!1){let s,o=e.svg.elt("g"),[a,l]=n,d=[a-15,l-50],h=[a+15,l+50];i=t.mapWireColor(i),s=r?u(d,!0,i):c(d,!0,i);let p=function(t,n,i){const r=e=>`${e[0]}, ${e[1]}`;let[s,o]=t,[a,l]=n,c=l-o,u=[s,o+.8*c],d=[a,l-.8*c],h=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(u)} ${r(d)} ${r(n)}`);return h.style.stroke=i,{el:h,x:Math.min(s,a),y:Math.min(o,l),w:Math.abs(s-a),h:Math.abs(o-l)}}(d,h,i),f=c(h,!1,i);o.appendChild(p.el),o.appendChild(s.el),o.appendChild(f.el);let m=Math.min(s.x,f.x),g=Math.max(s.x+s.w,f.x+f.w),b=Math.min(s.y,f.y);return{el:o,x:m,y:b,w:g-m,h:Math.max(s.y+s.h,f.y+f.h)-b}};t.WireFactory=class{constructor(e,n,i,r,s,o){this.nextWireId=0,this.styleEl=r,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=i,this.getLocCoord=s,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]<n&&(n=e[i],t=i);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,s,c){let u=[],d=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const h=e=>{const n=t.PIN_DIST/2;let i,r=this.closestEdge(e);return i=r-e[1]<0?r-n:r+n,[e[0],i]};let p=this.nextWireId++,f=r(c),m=l(n,f),g=l(s,f),b=e.svg.child(d,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(m),b.appendChild(g);let y=this.closestEdgeIdx(n),v=this.closestEdgeIdx(s);if(y==v){let e=a(n,s,f);d.appendChild(e),u.push(e)}else{let t,r,l=h(n),c=h(s),m=a(n,l,f),g=a(s,c,f);!(1!=y&&2!=y||1!=v&&2!=v)?(t=o(l,c,i,f),r=o(l,c,i,f)):(t=a(l,c,f),r=a(l,c,f)),e.U.addClass(r,"sim-bb-wire-hover"),d.appendChild(m),u.push(m),d.appendChild(g),u.push(g),this.underboard.appendChild(t),u.push(t),d.appendChild(r),u.push(r);let w=`sim-bb-wire-id-${p}`;const x=t=>e.U.addClass(t,w);x(b),x(r),this.styleEl.textContent+=`\n .${w}:hover ~ .${w}.sim-bb-wire-hover {\n visibility: visible;\n }`}let w=`\n .wire-stroke-${f} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${f} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=w,{endG:b,end1:m,end2:g,wires:u}}drawWireWithCrocs(n,s,c,d=!1){let h=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const f=e=>{const n=t.PIN_DIST/2;let i,r=this.closestEdge(e);return i=r-e[1]<0?r-n:r+n,[e[0],i]};let m=this.nextWireId++,g=r(c),b=l(n,g),y=s,[v,w]=s;s=[v,w+40],[v,w]=s;let x,k=[v,w+-17];x=d?function(n,i,r){let s=.24*t.PIN_DIST,o=4*s,a=1.2*s,l=10*s,c=s;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h+10-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),x=l,k=c,A=d-k/2,T=h+10+p*(g/2+x/2)-x/2;return e.svg.hydrate(w,{x:A,y:T,width:k,height:x,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,T),w:b+2*u,h:g+x}}(k,!0):u(k,!0);let A=x.el,T=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});T.appendChild(b);let E=this.closestEdgeIdx(n),C=this.closestEdgeIdx(y);if(E==C){let e=a(n,s,g);p.appendChild(e),h.push(e)}else{let t,r,l=f(n),c=a(n,l,g);!(1!=E&&2!=E||1!=C&&2!=C)?(t=o(l,s,i,g),r=o(l,s,i,g)):(t=a(l,s,g),r=a(l,s,g)),e.U.addClass(r,"sim-bb-wire-hover"),p.appendChild(c),h.push(c),this.underboard.appendChild(t),h.push(t);let u=`sim-bb-wire-id-${m}`;const d=t=>e.U.addClass(t,u);d(T),d(r),this.styleEl.textContent+=`\n .${u}:hover ~ .${u}.sim-bb-wire-hover {\n visibility: visible;\n }`}T.appendChild(A);let S=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=S,{endG:T,end1:b,end2:A,wires:h}}checkWire(e,t){let n=this.getLocCoord(e),i=this.getLocCoord(t);return!!n&&!!i}addWire(e,t,n){let i=this.getLocCoord(e),r=this.getLocCoord(t);if(!i||!r)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let s,o=this.getPinStyle(t);return s="dalboard"==t.type&&"croc"==o?this.drawWireWithCrocs(i,r,n):this.drawWire(i,r,n),s}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));
|