O,5>OO){QYO,5>OO5iQ!LYO,5>QOOQQ,5>S,5>SO!8VQWO,5>SOOQQ,5>U,5>UO!8VQWO,5>UOOQQ,5>W,5>WO!8[Q`O,59rOOOS-E;p-E;pOOQ!LS1G/]1G/]O!8aQbO,5>_O'dQYO,5>_OOQO,5>d,5>dO!8kQYO'#HsOOQO-E;q-E;qO!8xQWO,5?`O!9QQbO,5?`O!9XQWO,5?jOOQ!LS1G/c1G/cO!9aQpO'#DTOOQO'#Iv'#IvO){QYO'#IvO!:OQpO'#IvO!:mQpO'#DcO!;OQ&jO'#DcO!=ZQYO'#DcO!=bQWO'#IuO!=jQWO,59|O!=oQWO'#EaO!=}QWO'#JQO!>VQWO,5:zO!>mQ&jO'#DcO){QYO,5?kO!>wQWO'#HxOOQO-E;v-E;vO!9XQWO,5?jOOQ!LQ1G0e1G0eO!@TQ&jO'#D|OOQ!LS,5:e,5:eO){QYO,5:eOITQWO,5:eO!@[QWO,5:eO:^QWO,5:uO!,rQpO,5:uO!,zQ#tO,5:uO5vQ#tO,5:uOOQ!LS1G/n1G/nOOQ!LS1G0O1G0OOOQ!LQ'#EV'#EVO){QYO,5?hO!@gQ!LYO,5?hO!@xQ!LYO,5?hO!APQWO,5?gO!AXQWO'#HzO!APQWO,5?gOOQ!LQ1G0d1G0dO7VQWO,5?gOOQ!LS1G0b1G0bO!AsQ!LdO1G0bO!BdQ!LbO,5:rOOQ!LS'#Fq'#FqO!CQQ!LdO'#IoOGTQYO1G0bO!EPQ#tO'#IwO!EZQWO,5:WO!E`QbO'#IxO){QYO'#IxO!EjQWO,5:]OOQ!LS'#DT'#DTOOQ!LS1G0k1G0kO!EoQWO1G0kO!HQQ!LdO1G0mO!HXQ!LdO1G0mO!JlQ!LdO1G0mO!JsQ!LdO1G0mO!LzQ!LdO1G0mO!M_Q!LdO1G0mO#!OQ!LdO1G0mO#!VQ!LdO1G0mO#$jQ!LdO1G0mO#$qQ!LdO1G0mO#&fQ!LdO1G0mO#)`Q7^O'#ChO#+ZQ7^O1G0}O#-UQ7^O'#IsOOQ!LS1G1T1G1TO#-iQ!LdO,5>iOOQ!LQ-E;{-E;{O#.YQ!LdO1G0mOOQ!LS1G0m1G0mO#0[Q!LdO1G1QO#0{QpO,5;sO#1QQpO,5;tO#1VQpO'#F[O#1kQWO'#FZOOQO'#JU'#JUOOQO'#H{'#H{O#1pQpO1G1]OOQ!LS1G1]1G1]OOOO1G1f1G1fO#2OQ7^O'#IrO#2YQWO,5;}OLXQYO,5;}OOOO-E;z-E;zOOQ!LS1G1Y1G1YOOQ!LS,5VQ&jO'#GhOOQQ1G2l1G2lO!&wQ&jO'#IWO!0OQ`O1G2oOOQQ1G2o1G2oOOQQ,5=Y,5=YO#>_Q#tO,5=[O5qQWO,5=[O#5YQWO,5=_O5_QWO,5=_O!,rQpO,5=_O!,zQ#tO,5=_O5vQ#tO,5=_O#>pQWO'#J_O#>{QWO,5=`OOQQ1G.j1G.jO#?QQ!LYO1G.jO#?]QWO1G.jO#?bQWO1G.jO5iQ!LYO1G.jO#?jQbO,5?|O#?tQWO,5?|O#@PQYO,5=gO#@WQWO,5=gO7VQWO,5?|OOQQ1G3P1G3PO`QYO1G3POOQQ1G3V1G3VOOQQ1G3X1G3XO:XQWO1G3ZO#@]QYO1G3]O#DWQYO'#H[OOQQ1G3`1G3`O:^QWO1G3fO#DeQWO1G3fO5iQ!LYO1G3jOOQQ1G3l1G3lOOQ!LQ'#Fx'#FxO5iQ!LYO1G3nO5iQ!LYO1G3pOOOS1G/^1G/^O#DmQ`O,5_O#EPQWO1G4zO#EXQWO1G5UO#EaQWO,5?bOLXQYO,5:{O7VQWO,5:{O:^QWO,59}OLXQYO,59}O!,rQpO,59}O#EfQ7^O,59}OOQO,5:{,5:{O#EpQ&jO'#HtO#FWQWO,5?aOOQ!LS1G/h1G/hO#F`Q&jO'#HyO#FtQWO,5?lOOQ!LQ1G0f1G0fO!;OQ&jO,59}O#F|QbO1G5VO7VQWO,5>dOOQ!LQ'#ES'#ESO#GWQ!LrO'#ETO!?{Q&jO'#D}OOQO'#Hw'#HwO#GrQ&jO,5:hOOQ!LS,5:h,5:hO#GyQ&jO'#D}O#H[Q&jO'#D}O#HcQ&jO'#EYO#HfQ&jO'#ETO#HsQ&jO'#ETO!?{Q&jO'#ETO#IWQWO1G0PO#I]Q`O1G0POOQ!LS1G0P1G0PO){QYO1G0POITQWO1G0POOQ!LS1G0a1G0aO:^QWO1G0aO!,rQpO1G0aO!,zQ#tO1G0aO#IdQ!LdO1G5SO){QYO1G5SO#ItQ!LYO1G5SO#JVQWO1G5RO7VQWO,5>fOOQO,5>f,5>fO#J_QWO,5>fOOQO-E;x-E;xO#JVQWO1G5RO#JmQ!LdO,59jO#LlQ!LdO,5k,5>kO$(]QWO,5>kOOQ!LS1G2P1G2PP$(bQWO'#IPPOQ!LS-E;}-E;}O$)RQ#tO1G2[O$)tQ#tO1G2^O$*OQ#tO1G2`OOQ!LS1G1x1G1xO$*VQWO'#IOO$*eQWO,5?sO$*eQWO,5?sO$*mQWO,5?sO$*xQWO,5?sOOQO1G1z1G1zO$+WQ#tO1G1yO$+hQWO'#IQO$+xQWO,5?tOITQWO,5?tO$,QQ`O,5?tOOQ!LS1G1}1G1}O5iQ!LYO,5n,5>nOOQO-Ev,5>vOOQO-Ep,5>pOOQ!LQ-Er,5>rOOQO-E`,5>`OOQO-E;r-E;rOOQO,5>e,5>eOOQO-E;w-E;wO!,rQpO1G/iO:^QWO,5:iOOQO,5:o,5:oO){QYO,5:oO$9pQ!LYO,5:oO$9{Q!LYO,5:oO!,rQpO,5:iOOQO-E;u-E;uOOQ!LS1G0S1G0SO!?{Q&jO,5:iO$:ZQ&jO,5:iO$:lQ!LrO,5:oO$;WQ&jO,5:iO!?{Q&jO,5:oOOQO,5:t,5:tO$;_Q&jO,5:oO$;lQ!LYO,5:oOOQ!LS7+%k7+%kO#IWQWO7+%kO#I]Q`O7+%kOOQ!LS7+%{7+%{O:^QWO7+%{O!,rQpO7+%{O$lQ!LdO1G2^O$@nQ!LdO1G1yO$BvQ#tO,5>aOOQO-E;s-E;sO$CQQbO,5>bO){QYO,5>bOOQO-E;t-E;tO$C[QWO1G5OO$CdQ7^O1G0bO$EkQ7^O1G0mO$ErQ7^O1G0mO$GsQ7^O1G0mO$GzQ7^O1G0mO$IoQ7^O1G0mO$JSQ7^O1G0mO$LaQ7^O1G0mO$LhQ7^O1G0mO$NiQ7^O1G0mO$NpQ7^O1G0mO%!eQ7^O1G0mO%!xQ!LdO<iOOOO7+'T7+'TOOOS1G/R1G/ROOQ!LS1G4V1G4VOJdQWO7+'zO%'rQWO,5>jO5qQWO,5>jOOQO-E;|-E;|O%(QQWO1G5_O%(QQWO1G5_O%(YQWO1G5_O%(eQ`O,5>lO%(oQWO,5>lOITQWO,5>lOOQO-Eu,5>uO%,RQWO,5>uO%,WQWO,5>uOOQO-EtOOQO-ERQ#tO<cQWO1G4UO%>nQWO1G4UO%>|QWO7+*yO%>|QWO7+*yOITQWO1G4WO%?UQ`O1G4WO%?`QWO7+*zOOQO7+'o7+'oO5iQ!LYO7+'oOOQO7+'n7+'nO$,[QWO7+'pO%?hQ`O7+'pOOQO7+'t7+'tO5iQ!LYO7+'nO$,[QWO7+'oO%?oQWO7+'pOITQWO7+'pO#5TQWO7+'oO%?tQ#tO<oOOQO-EqOOQO-E{AN>{OOQOAN>uAN>uO%0}Q!LdOAN>{O:^QWOAN>uO){QYOAN>{O!,rQpOAN>uO&(PQ!LYOAN>{O&([Q7^O<^O!O&OO~Ox&RO!W&]O!X&UO!Y&UO'[$bO~O]&SOk&SO!Q&VO'e&PO!S'iP!S'tP~P@aO!O'qX!R'qX!]'qX!c'qX'n'qX~O!{'qX#W#PX!S'qX~PAYO!{&^O!O'sX!R'sX~O!R&_O!O'rX~O!O&bO~O!{#eO~PAYOS&fO!T&cO!o&eO'Z$`O~Oc&kO!d$XO'Z$`O~Ou$nO!d$mO~O!S&lO~P`Ou!{Ov!{Ox!|O!b!yO!d!zO'dQOP!faZ!faj!fa!R!fa!a!fa!j!fa#[!fa#]!fa#^!fa#_!fa#`!fa#a!fa#b!fa#c!fa#e!fa#g!fa#i!fa#j!fa'n!fa'u!fa'v!fa~O_!fa'U!fa!O!fa!c!fan!fa!T!fa%Q!fa!]!fa~PCcO!c&mO~O!]!wO!{&oO'n&nO!R'pX_'pX'U'pX~O!c'pX~PE{O!R&sO!c'oX~O!c&uO~Ox$tO!T$uO#V&vO'Z$`O~OPTOQTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!TSO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O'Z9YO'dQO'mYO'zaO~O]#qOh$OOj#rOk#qOl#qOq$POs9lOx#xO!T#yO!_:oO!d#vO#V9rO#t$TO$_9nO$a9pO$d$UO'Z&zO'd#sO~O#W&|O~O]#qOh$OOj#rOk#qOl#qOq$POs$QOx#xO!T#yO!_$VO!d#vO#V$WO#t$TO$_$RO$a$SO$d$UO'Z&zO'd#sO~O'_'kP~PJdO!Q'QO!c'lP~P){O'e'SO'mYO~OP9VOQ9VO]cOb:mOc!jOhcOj9VOkcOlcOq9VOs9VOxRO{cO|cO}cO!T!bO!_9XO!dUO!g9VO!h9VO!i9VO!j9VO!k9VO!n!iO#t!lO#x^O'Z'bO'dQO'mYO'z:kO~O!d!zO~O!R#bO_$]a'U$]a!c$]a!O$]a!T$]a%Q$]a!]$]a~O#d'iO~PITO!]'kO!T'wX#w'wX#z'wX$R'wX~Ou'lO~P! POu'lO!T'wX#w'wX#z'wX$R'wX~O!T'nO#w'rO#z'mO$R'sO~O!Q'vO~PLXO#z#fO$R'yO~Ou$eXx$eX!b$eX'n$eX'u$eX'v$eX~OSfX!RfX!{fX'_fX'_$eX~P!!iOk'{O~OR'|O'S'}O'T(PO~Ou(ROx(SO'n#[O'u(UO'v(WO~O'_(QO~P!#rO'_(ZO~O]#qOh$OOj#rOk#qOl#qOq$POs9lOx#xO!T#yO!_:oO!d#vO#V9rO#t$TO$_9nO$a9pO$d$UO'd#sO~O!Q(_O'Z([O!c'{P~P!$aO#W(aO~O!Q(eO'Z(bO!O'|P~P!$aO_(nOj(sOx(kO!W(qO!X(jO!Y(jO!d(hO!x(rO$w(mO'[$bO'e(gO~O!S(pO~P!&XO!b!yOu'cXx'cX'n'cX'u'cX'v'cX!R'cX!{'cX~O'_'cX#m'cX~P!'TOS(vO!{(uO!R'bX'_'bX~O!R(wO'_'aX~O'Z(yO~O!d)OO~O'Z&zO~O!d(hO~Ox$tO!Q!rO!T$uO#U!uO#V!rO'Z$`O!c'oP~O!]!wO#W)SO~OP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO#j#ZO'dQO'n#[O'u!}O'v#OO~O_!^a!R!^a'U!^a!O!^a!c!^an!^a!T!^a%Q!^a!]!^a~P!)fOS)[O!T&cO!o)ZO%Q)YO'`$cO~O'Z$zO'_'aP~O!])_O!T'^X_'^X'U'^X~O!d$XO'`$cO~O!d$XO'Z$`O'`$cO~O!]!wO#W&|O~O])jO%R)kO'Z)gO!S(TP~O!R)lO^(SX~O'e'SO~OZ)pO~O^)qO~O!T$kO'Z$`O'[$bO^(SP~Ox$tO!Q)vO!R&_O!T$uO'Z$`O!O'rP~O]&YOk&YO!Q)wO'e'SO!S'tP~O!R)xO_(PX'U(PX~O!{)|O'`$cO~OS*PO!T#yO'`$cO~O!T*RO~Ou*TO!TSO~O!n*YO~Oc*_O~O'Z(yO!S(RP~Oc$iO~O%RtO'Z$zO~P8tOZ*eO^*dO~OPTOQTO]cObnOcmOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!nlO#x^O%PqO'dQO'mYO'zaO~O!T!bO#t!lO'Z9YO~P!1RO^*dO_$[O'U$[O~O_*iO#d*kO%T*kO%U*kO~P){O!d%_O~O%t*pO~O!T*rO~O&U*uO&V*tOP&SaQ&SaX&Sa]&Sa_&Sab&Sac&Sah&Saj&Sak&Sal&Saq&Sas&Sax&Sa{&Sa|&Sa}&Sa!T&Sa!_&Sa!d&Sa!g&Sa!h&Sa!i&Sa!j&Sa!k&Sa!n&Sa#d&Sa#t&Sa#x&Sa%P&Sa%R&Sa%T&Sa%U&Sa%X&Sa%Z&Sa%^&Sa%_&Sa%a&Sa%n&Sa%t&Sa%v&Sa%x&Sa%z&Sa%}&Sa&T&Sa&X&Sa&Z&Sa&]&Sa&_&Sa&a&Sa'Q&Sa'Z&Sa'd&Sa'm&Sa'z&Sa!S&Sa%{&Sa`&Sa&Q&Sa~O'Z*xO~On*{O~O!O&ga!R&ga~P!)fO!Q+PO!O&gX!R&gX~P){O!R%yO!O'ha~O!O'ha~P>^O!R&_O!O'ra~O!RwX!R!ZX!SwX!S!ZX!]wX!]!ZX!d!ZX!{wX'`!ZX~O!]+UO!{+TO!R#TX!R'jX!S#TX!S'jX!]'jX!d'jX'`'jX~O!]+WO!d$XO'`$cO!R!VX!S!VX~O]&QOk&QOx&RO'e(gO~OP9VOQ9VO]cOb:mOc!jOhcOj9VOkcOlcOq9VOs9VOxRO{cO|cO}cO!T!bO!_9XO!dUO!g9VO!h9VO!i9VO!j9VO!k9VO!n!iO#t!lO#x^O'dQO'mYO'z:kO~O'Z9vO~P!;^O!R+[O!S'iX~O!S+^O~O!]+UO!{+TO!R#TX!S#TX~O!R+_O!S'tX~O!S+aO~O]&QOk&QOx&RO'[$bO'e(gO~O!X+bO!Y+bO~P!>[Ox$tO!Q+dO!T$uO'Z$`O!O&lX!R&lX~O_+hO!W+kO!X+gO!Y+gO!r+oO!s+mO!t+nO!u+lO!x+pO'[$bO'e(gO'm+eO~O!S+jO~P!?]OS+uO!T&cO!o+tO~O!{+{O!R'pa!c'pa_'pa'U'pa~O!]!wO~P!@gO!R&sO!c'oa~Ox$tO!Q,OO!T$uO#U,QO#V,OO'Z$`O!R&nX!c&nX~O_#Oi!R#Oi'U#Oi!O#Oi!c#Oin#Oi!T#Oi%Q#Oi!]#Oi~P!)fO#W!za!R!za!c!za!{!za!T!za_!za'U!za!O!za~P!#rO#W'cXP'cXZ'cX_'cXj'cXv'cX!a'cX!d'cX!j'cX#['cX#]'cX#^'cX#_'cX#`'cX#a'cX#b'cX#c'cX#e'cX#g'cX#i'cX#j'cX'U'cX'd'cX!c'cX!O'cX!T'cXn'cX%Q'cX!]'cX~P!'TO!R,ZO'_'kX~P!#rO'_,]O~O!R,^O!c'lX~P!)fO!c,aO~O!O,bO~OP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'dQOZ#Zi_#Zij#Zi!R#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'U#Zi'n#Zi'u#Zi'v#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O#[#Zi~P!EtO#[#PO~P!EtOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO'dQOZ#Zi_#Zi!R#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'U#Zi'n#Zi'u#Zi'v#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~Oj#Zi~P!H`Oj#RO~P!H`OP#^Oj#ROu!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO'dQO_#Zi!R#Zi#e#Zi#g#Zi#i#Zi#j#Zi'U#Zi'n#Zi'u#Zi'v#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P!JzOZ#dO!a#TO#a#TO#b#TO#c#TO~P!JzOP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO'dQO_#Zi!R#Zi#g#Zi#i#Zi#j#Zi'U#Zi'n#Zi'v#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'u#Zi~P!MrO'u!}O~P!MrOP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO'dQO'u!}O_#Zi!R#Zi#i#Zi#j#Zi'U#Zi'n#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'v#Zi~P#!^O'v#OO~P#!^OP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO'dQO'u!}O'v#OO~O_#Zi!R#Zi#j#Zi'U#Zi'n#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P#$xOP[XZ[Xj[Xu[Xv[Xx[X!a[X!b[X!d[X!j[X!{[X#WdX#[[X#][X#^[X#_[X#`[X#a[X#b[X#c[X#e[X#g[X#i[X#j[X#o[X'd[X'n[X'u[X'v[X!R[X!S[X~O#m[X~P#']OP#^OZ9jOj9_Ou!{Ov!{Ox!|O!a9aO!b!yO!d!zO!j#^O#[9]O#]9^O#^9^O#_9^O#`9`O#a9aO#b9aO#c9aO#e9bO#g9dO#i9fO#j9gO'dQO'n#[O'u!}O'v#OO~O#m,dO~P#)gOP'gXZ'gXj'gXu'gXv'gXx'gX!a'gX!b'gX!d'gX!j'gX#['gX#]'gX#^'gX#_'gX#`'gX#a'gX#b'gX#e'gX#g'gX#i'gX#j'gX'd'gX'n'gX'u'gX'v'gX!R'gX~O!{9kO#o9kO#c'gX#m'gX!S'gX~P#+bO_&qa!R&qa'U&qa!c&qan&qa!O&qa!T&qa%Q&qa!]&qa~P!)fOP#ZiZ#Zi_#Zij#Ziv#Zi!R#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'U#Zi'd#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P!#rO_#ni!R#ni'U#ni!O#ni!c#nin#ni!T#ni%Q#ni!]#ni~P!)fO#z,fO~O#z,gO~O!]'kO!{,hO!T$OX#w$OX#z$OX$R$OX~O!Q,iO~O!T'nO#w,kO#z'mO$R,lO~O!R9hO!S'fX~P#)gO!S,mO~O$R,oO~OR'|O'S'}O'T,rO~O],uOk,uO!O,vO~O!RdX!]dX!cdX!c$eX'ndX~P!!iO!c,|O~P!#rO!R,}O!]!wO'n&nO!c'{X~O!c-SO~O!O$eX!R$eX!]$lX~P!!iO!R-UO!O'|X~P!#rO!]-WO~O!O-YO~O!Q(_O'Z$`O!c'{P~Oj-^O!]!wO!d$XO'`$cO'n&nO~O!])_O~O!S-dO~P!&XO!X-eO!Y-eO'[$bO'e(gO~Ox-gO'e(gO~O!x-hO~O'Z$zO!R&vX'_&vX~O!R(wO'_'aa~Ou-mOv-mOx-nO'nra'ura'vra!Rra!{ra~O'_ra#mra~P#6fOu(ROx(SO'n$^a'u$^a'v$^a!R$^a!{$^a~O'_$^a#m$^a~P#7[Ou(ROx(SO'n$`a'u$`a'v$`a!R$`a!{$`a~O'_$`a#m$`a~P#7}O]-oO~O#W-pO~O'_$na!R$na#m$na!{$na~P!#rO#W-sO~OS-|O!T&cO!o-{O%Q-zO~O'_-}O~O]#qOj#rOk#qOl#qOq$POs9lOx#xO!T#yO!_:oO!d#vO#V9rO#t$TO$_9nO$a9pO$d$UO'd#sO~Oh.PO'Z.OO~P#9tO!])_O!T'^a_'^a'U'^a~O#W.VO~OZ[X!RdX!SdX~O!R.WO!S(TX~O!S.YO~OZ.ZO~O].]O'Z)gO~O!T$kO'Z$`O^'OX!R'OX~O!R)lO^(Sa~O!c.`O~P!)fO].bO~OZ.cO~O^.dO~OS-|O!T&cO!o-{O%Q-zO'`$cO~O!R)xO_(Pa'U(Pa~O!{.jO~OS.mO!T#yO~O'e'SO!S(QP~OS.wO!T.sO!o.vO%Q.uO'`$cO~OZ/RO!R/PO!S(RX~O!S/SO~O^/UO_$[O'U$[O~O]/VO~O]/WO'Z(yO~O#c/XO%r/YO~P0zO!{#eO#c/XO%r/YO~O_/ZO~P){O_/]O~O%{/aOP%yiQ%yiX%yi]%yi_%yib%yic%yih%yij%yik%yil%yiq%yis%yix%yi{%yi|%yi}%yi!T%yi!_%yi!d%yi!g%yi!h%yi!i%yi!j%yi!k%yi!n%yi#d%yi#t%yi#x%yi%P%yi%R%yi%T%yi%U%yi%X%yi%Z%yi%^%yi%_%yi%a%yi%n%yi%t%yi%v%yi%x%yi%z%yi%}%yi&T%yi&X%yi&Z%yi&]%yi&_%yi&a%yi'Q%yi'Z%yi'd%yi'm%yi'z%yi!S%yi`%yi&Q%yi~O`/gO!S/eO&Q/fO~P`O!TSO!d/jO~O!R#bOn$]a~O!O&gi!R&gi~P!)fO!R%yO!O'hi~O!R&_O!O'ri~O!O/nO~O!R!Va!S!Va~P#)gO]&QOk&QO!Q/tO'e(gO!R&hX!S&hX~P@aO!R+[O!S'ia~O]&YOk&YO!Q)wO'e'SO!R&mX!S&mX~O!R+_O!S'ta~O!O'si!R'si~P!)fO_$[O!]!wO!d$XO!j0OO!{/|O'U$[O'`$cO'n&nO~O!S0RO~P!?]O!X0SO!Y0SO'[$bO'e(gO'm+eO~O!W0TO~P#GyO!TSO!W0TO!u0VO!x0WO~P#GyO!W0TO!s0YO!t0YO!u0VO!x0WO~P#GyO!T&cO~O!T&cO~P!#rO!R'pi!c'pi_'pi'U'pi~P!)fO!{0cO!R'pi!c'pi_'pi'U'pi~O!R&sO!c'oi~Ox$tO!T$uO#V0eO'Z$`O~O#WraPraZra_rajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra'Ura'dra!cra!Ora!Tranra%Qra!]ra~P#6fO#W$^aP$^aZ$^a_$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a'U$^a'd$^a!c$^a!O$^a!T$^an$^a%Q$^a!]$^a~P#7[O#W$`aP$`aZ$`a_$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a'U$`a'd$`a!c$`a!O$`a!T$`an$`a%Q$`a!]$`a~P#7}O#W$naP$naZ$na_$naj$nav$na!R$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na'U$na'd$na!c$na!O$na!T$na!{$nan$na%Q$na!]$na~P!#rO_#Oq!R#Oq'U#Oq!O#Oq!c#Oqn#Oq!T#Oq%Q#Oq!]#Oq~P!)fO!R&iX'_&iX~PJdO!R,ZO'_'ka~O!Q0mO!R&jX!c&jX~P){O!R,^O!c'la~O!R,^O!c'la~P!)fO#m!fa!S!fa~PCcO#m!^a!R!^a!S!^a~P#)gO!T1QO#x^O$P1RO~O!S1VO~On1WO~P!#rO_$Yq!R$Yq'U$Yq!O$Yq!c$Yqn$Yq!T$Yq%Q$Yq!]$Yq~P!)fO!O1XO~O],uOk,uO~Ou(ROx(SO'v(WO'n$xi'u$xi!R$xi!{$xi~O'_$xi#m$xi~P$(jOu(ROx(SO'n$zi'u$zi'v$zi!R$zi!{$zi~O'_$zi#m$zi~P$)]O#m1YO~P!#rO!Q1[O'Z$`O!R&rX!c&rX~O!R,}O!c'{a~O!R,}O!]!wO!c'{a~O!R,}O!]!wO'n&nO!c'{a~O'_$gi!R$gi#m$gi!{$gi~P!#rO!Q1cO'Z(bO!O&tX!R&tX~P!$aO!R-UO!O'|a~O!R-UO!O'|a~P!#rO!]!wO~O!]!wO#c1mO~Oj1qO!]!wO'n&nO~O!R'bi'_'bi~P!#rO!{1tO!R'bi'_'bi~P!#rO!c1wO~O_$Zq!R$Zq'U$Zq!O$Zq!c$Zqn$Zq!T$Zq%Q$Zq!]$Zq~P!)fO!R1{O!T'}X~P!#rO!T&cO%Q2OO~O!T&cO%Q2OO~P!#rO!T$eX$u[X_$eX'U$eX~P!!iO$u2SOugXxgX!TgX'ngX'ugX'vgX_gX'UgX~O$u2SO~O]2YO%R2ZO'Z)gO!R&}X!S&}X~O!R.WO!S(Ta~OZ2_O~O^2`O~O]2cO~OS2eO!T&cO!o2dO%Q2OO~O_$[O'U$[O~P!#rO!T#yO~P!#rO!R2jO!{2lO!S(QX~O!S2mO~Ox(kO!W2vO!X2oO!Y2oO!r2uO!s2tO!t2tO!x2sO'[$bO'e(gO'm+eO~O!S2rO~P$1nOS2}O!T.sO!o2|O%Q2{O~OS2}O!T.sO!o2|O%Q2{O'`$cO~O'Z(yO!R&|X!S&|X~O!R/PO!S(Ra~O]3XO'e3WO~O]3YO~O^3[O~O!c3_O~P){O_3aO~O_3aO~P){O#c3cO%r3dO~PE{O`/gO!S3hO&Q/fO~P`O!]3jO~O&V3kOP&SqQ&SqX&Sq]&Sq_&Sqb&Sqc&Sqh&Sqj&Sqk&Sql&Sqq&Sqs&Sqx&Sq{&Sq|&Sq}&Sq!T&Sq!_&Sq!d&Sq!g&Sq!h&Sq!i&Sq!j&Sq!k&Sq!n&Sq#d&Sq#t&Sq#x&Sq%P&Sq%R&Sq%T&Sq%U&Sq%X&Sq%Z&Sq%^&Sq%_&Sq%a&Sq%n&Sq%t&Sq%v&Sq%x&Sq%z&Sq%}&Sq&T&Sq&X&Sq&Z&Sq&]&Sq&_&Sq&a&Sq'Q&Sq'Z&Sq'd&Sq'm&Sq'z&Sq!S&Sq%{&Sq`&Sq&Q&Sq~O!R#Ti!S#Ti~P#)gO!{3mO!R#Ti!S#Ti~O!R!Vi!S!Vi~P#)gO_$[O!{3tO'U$[O~O_$[O!]!wO!{3tO'U$[O~O!X3xO!Y3xO'[$bO'e(gO'm+eO~O_$[O!]!wO!d$XO!j3yO!{3tO'U$[O'`$cO'n&nO~O!W3zO~P$:ZO!W3zO!u3}O!x4OO~P$:ZO_$[O!]!wO!j3yO!{3tO'U$[O'n&nO~O!R'pq!c'pq_'pq'U'pq~P!)fO!R&sO!c'oq~O#W$xiP$xiZ$xi_$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi'U$xi'd$xi!c$xi!O$xi!T$xin$xi%Q$xi!]$xi~P$(jO#W$ziP$ziZ$zi_$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi'U$zi'd$zi!c$zi!O$zi!T$zin$zi%Q$zi!]$zi~P$)]O#W$giP$giZ$gi_$gij$giv$gi!R$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi'U$gi'd$gi!c$gi!O$gi!T$gi!{$gin$gi%Q$gi!]$gi~P!#rO!R&ia'_&ia~P!#rO!R&ja!c&ja~P!)fO!R,^O!c'li~O#m#Oi!R#Oi!S#Oi~P#)gOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'dQOZ#Zij#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'n#Zi'u#Zi'v#Zi!R#Zi!S#Zi~O#[#Zi~P$CqO#[9]O~P$CqOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9]O#]9^O#^9^O#_9^O'dQOZ#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'n#Zi'u#Zi'v#Zi!R#Zi!S#Zi~Oj#Zi~P$EyOj9_O~P$EyOP#^Oj9_Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9]O#]9^O#^9^O#_9^O#`9`O'dQO#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'n#Zi'u#Zi'v#Zi!R#Zi!S#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P$HROZ9jO!a9aO#a9aO#b9aO#c9aO~P$HROP#^OZ9jOj9_Ou!{Ov!{Ox!|O!a9aO!b!yO!d!zO!j#^O#[9]O#]9^O#^9^O#_9^O#`9`O#a9aO#b9aO#c9aO#e9bO'dQO#g#Zi#i#Zi#j#Zi#m#Zi'n#Zi'v#Zi!R#Zi!S#Zi~O'u#Zi~P$JgO'u!}O~P$JgOP#^OZ9jOj9_Ou!{Ov!{Ox!|O!a9aO!b!yO!d!zO!j#^O#[9]O#]9^O#^9^O#_9^O#`9`O#a9aO#b9aO#c9aO#e9bO#g9dO'dQO'u!}O#i#Zi#j#Zi#m#Zi'n#Zi!R#Zi!S#Zi~O'v#Zi~P$LoO'v#OO~P$LoOP#^OZ9jOj9_Ou!{Ov!{Ox!|O!a9aO!b!yO!d!zO!j#^O#[9]O#]9^O#^9^O#_9^O#`9`O#a9aO#b9aO#c9aO#e9bO#g9dO#i9fO'dQO'u!}O'v#OO~O#j#Zi#m#Zi'n#Zi!R#Zi!S#Zi~P$NwO_#ky!R#ky'U#ky!O#ky!c#kyn#ky!T#ky%Q#ky!]#ky~P!)fOP#ZiZ#Zij#Ziv#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'd#Zi!R#Zi!S#Zi~P!#rO!b!yOP'cXZ'cXj'cXu'cXv'cXx'cX!a'cX!d'cX!j'cX#['cX#]'cX#^'cX#_'cX#`'cX#a'cX#b'cX#c'cX#e'cX#g'cX#i'cX#j'cX#m'cX'd'cX'n'cX'u'cX'v'cX!R'cX!S'cX~O#m#ni!R#ni!S#ni~P#)gO!S4`O~O!R&qa!S&qa~P#)gO!]!wO'n&nO!R&ra!c&ra~O!R,}O!c'{i~O!R,}O!]!wO!c'{i~O!O&ta!R&ta~P!#rO!]4gO~O!R-UO!O'|i~P!#rO!R-UO!O'|i~O!O4mO~O!]!wO#c4sO~Oj4tO!]!wO'n&nO~O!O4vO~O'_$iq!R$iq#m$iq!{$iq~P!#rO_$Zy!R$Zy'U$Zy!O$Zy!c$Zyn$Zy!T$Zy%Q$Zy!]$Zy~P!)fO!R1{O!T'}a~O!T&cO%Q4{O~O!T&cO%Q4{O~P!#rO_#Oy!R#Oy'U#Oy!O#Oy!c#Oyn#Oy!T#Oy%Q#Oy!]#Oy~P!)fOZ5OO~O]5QO'Z)gO~O!R.WO!S(Ti~O]5TO~O^5UO~O'e'SO!R&yX!S&yX~O!R2jO!S(Qa~O!S5cO~P$1nOx-gO'e(gO'm+eO~O!W5fO!X5eO!Y5eO!x0WO'[$bO'e(gO'm+eO~O!s5gO!t5gO~P%-iO!X5eO!Y5eO'[$bO'e(gO'm+eO~O!T.sO~O!T.sO%Q5iO~O!T.sO%Q5iO~P!#rOS5nO!T.sO!o5mO%Q5iO~OZ5sO!R&|a!S&|a~O!R/PO!S(Ri~O]5vO~O!c5wO~O!c5xO~O!c5yO~O!c5yO~P){O_5{O~O!]6OO~O!c6QO~O!R'si!S'si~P#)gO_$[O'U$[O~P!)fO_$[O!{6VO'U$[O~O_$[O!]!wO!{6VO'U$[O~O!X6[O!Y6[O'[$bO'e(gO'm+eO~O_$[O!]!wO!j6]O!{6VO'U$[O'n&nO~O!d$XO'`$cO~P%2TO!W6^O~P%1rO!R'py!c'py_'py'U'py~P!)fO#W$iqP$iqZ$iq_$iqj$iqv$iq!R$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq'U$iq'd$iq!c$iq!O$iq!T$iq!{$iqn$iq%Q$iq!]$iq~P!#rO!R&ji!c&ji~P!)fO#m#Oq!R#Oq!S#Oq~P#)gOu-mOv-mOx-nOPraZrajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra#mra'dra'nra'ura'vra!Rra!Sra~Ou(ROx(SOP$^aZ$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a#m$^a'd$^a'n$^a'u$^a'v$^a!R$^a!S$^a~Ou(ROx(SOP$`aZ$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a#m$`a'd$`a'n$`a'u$`a'v$`a!R$`a!S$`a~OP$naZ$naj$nav$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na#m$na'd$na!R$na!S$na~P!#rO#m$Yq!R$Yq!S$Yq~P#)gO#m$Zq!R$Zq!S$Zq~P#)gO!S6hO~O'_$|y!R$|y#m$|y!{$|y~P!#rO!]!wO!R&ri!c&ri~O!]!wO'n&nO!R&ri!c&ri~O!R,}O!c'{q~O!O&ti!R&ti~P!#rO!R-UO!O'|q~O!O6oO~P!#rO!O6oO~O!R'by'_'by~P!#rO!R&wa!T&wa~P!#rO!T$tq_$tq'U$tq~P!#rOZ6wO~O!R.WO!S(Tq~O]6zO~O!T&cO%Q6{O~O!T&cO%Q6{O~P!#rO!{6|O!R&ya!S&ya~O!R2jO!S(Qi~P#)gO!X7SO!Y7SO'[$bO'e(gO'm+eO~O!W7UO!x4OO~P%ArO!T.sO%Q7XO~O!T.sO%Q7XO~P!#rO]7`O'e7_O~O!R/PO!S(Rq~O!c7bO~O!c7bO~P){O!c7dO~O!c7eO~O!R#Ty!S#Ty~P#)gO_$[O!{7kO'U$[O~O_$[O!]!wO!{7kO'U$[O~O!X7nO!Y7nO'[$bO'e(gO'm+eO~O_$[O!]!wO!j7oO!{7kO'U$[O'n&nO~O#W$|yP$|yZ$|y_$|yj$|yv$|y!R$|y!a$|y!b$|y!d$|y!j$|y#[$|y#]$|y#^$|y#_$|y#`$|y#a$|y#b$|y#c$|y#e$|y#g$|y#i$|y#j$|y'U$|y'd$|y!c$|y!O$|y!T$|y!{$|yn$|y%Q$|y!]$|y~P!#rO#m#ky!R#ky!S#ky~P#)gOP$giZ$gij$giv$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi#m$gi'd$gi!R$gi!S$gi~P!#rOu(ROx(SO'v(WOP$xiZ$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi#m$xi'd$xi'n$xi'u$xi!R$xi!S$xi~Ou(ROx(SOP$ziZ$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi#m$zi'd$zi'n$zi'u$zi'v$zi!R$zi!S$zi~O#m$Zy!R$Zy!S$Zy~P#)gO#m#Oy!R#Oy!S#Oy~P#)gO!]!wO!R&rq!c&rq~O!R,}O!c'{y~O!O&tq!R&tq~P!#rO!O7uO~P!#rO!R.WO!S(Ty~O!R2jO!S(Qq~O!X8RO!Y8RO'[$bO'e(gO'm+eO~O!T.sO%Q8UO~O!T.sO%Q8UO~P!#rO!c8XO~O&V8YOP&S!ZQ&S!ZX&S!Z]&S!Z_&S!Zb&S!Zc&S!Zh&S!Zj&S!Zk&S!Zl&S!Zq&S!Zs&S!Zx&S!Z{&S!Z|&S!Z}&S!Z!T&S!Z!_&S!Z!d&S!Z!g&S!Z!h&S!Z!i&S!Z!j&S!Z!k&S!Z!n&S!Z#d&S!Z#t&S!Z#x&S!Z%P&S!Z%R&S!Z%T&S!Z%U&S!Z%X&S!Z%Z&S!Z%^&S!Z%_&S!Z%a&S!Z%n&S!Z%t&S!Z%v&S!Z%x&S!Z%z&S!Z%}&S!Z&T&S!Z&X&S!Z&Z&S!Z&]&S!Z&_&S!Z&a&S!Z'Q&S!Z'Z&S!Z'd&S!Z'm&S!Z'z&S!Z!S&S!Z%{&S!Z`&S!Z&Q&S!Z~O_$[O!{8_O'U$[O~O_$[O!]!wO!{8_O'U$[O~OP$iqZ$iqj$iqv$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq#m$iq'd$iq!R$iq!S$iq~P!#rO!R&yq!S&yq~P#)gO_$[O!{8tO'U$[O~OP$|yZ$|yj$|yv$|y!a$|y!b$|y!d$|y!j$|y#[$|y#]$|y#^$|y#_$|y#`$|y#a$|y#b$|y#c$|y#e$|y#g$|y#i$|y#j$|y#m$|y'd$|y!R$|y!S$|y~P!#rOn'fX~P.jOn[X!O[X!c[X%r[X!T[X%Q[X!][X~P$zO!]dX!c[X!cdX'ndX~P;aOP9VOQ9VO]cOb:mOc!jOhcOj9VOkcOlcOq9VOs9VOxRO{cO|cO}cO!TSO!_9XO!dUO!g9VO!h9VO!i9VO!j9VO!k9VO!n!iO#t!lO#x^O'Z'bO'dQO'mYO'z:kO~O!R9hO!S$]a~O]#qOh$OOj#rOk#qOl#qOq$POs9mOx#xO!T#yO!_:pO!d#vO#V9sO#t$TO$_9oO$a9qO$d$UO'Z&zO'd#sO~O#d'iO~P&-UO!S[X!SdX~P;aO#W9[O~O!]!wO#W9[O~O!{9kO~O#c9aO~O!{9tO!R'sX!S'sX~O!{9kO!R'qX!S'qX~O#W9uO~O'_9wO~P!#rO#W9|O~O#W9}O~O!]!wO#W:OO~O!]!wO#W9uO~O#m:PO~P#)gO#W:QO~O#W:RO~O#W:SO~O#W:TO~O#m:UO~P!#rO#m:VO~P!#rO#x~!b!r!t!u#U#V'z$_$a$d$u%P%Q%R%X%Z%^%_%a%c~UT#x'z#]}'W'X#z'W'Z'e~",
- goto: "#Ed(XPPPPPPPP(YP(jP*^PPPP-uPP.[3n5b5uP5uPPP5uP7c5uP5uP7gPP7lP8Qk|}?O}!O>k!O!P?`!P!QCl!Q!R!0[!R![!1q![!]!7s!]!^!8V!^!_!8g!_!`!9d!`!a!:[!a!b!U#R#S2`#S#T!>i#T#o2`#o#p!>y#p#q!?O#q#r!?f#r#s!?x#s$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$I|2`$I|$I}!Bq$I}$JO!Bq$JO$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`W%YR$UWO!^%T!_#o%T#p~%T,T%jg$UW'W+{OX%TXY%cYZ%TZ[%c[p%Tpq%cq!^%T!_#o%T#p$f%T$f$g%c$g#BY%T#BY#BZ%c#BZ$IS%T$IS$I_%c$I_$JT%T$JT$JU%c$JU$KV%T$KV$KW%c$KW&FU%T&FU&FV%c&FV?HT%T?HT?HU%c?HU~%T,T'YR$UW'X+{O!^%T!_#o%T#p~%T$T'jS$UW!j#{O!^%T!_!`'v!`#o%T#p~%T$O'}S#e#v$UWO!^%T!_!`(Z!`#o%T#p~%T$O(bR#e#v$UWO!^%T!_#o%T#p~%T'u(rZ$UW]!ROY(kYZ)eZr(krs*rs!^(k!^!_+U!_#O(k#O#P-b#P#o(k#o#p+U#p~(k&r)jV$UWOr)ers*Ps!^)e!^!_*a!_#o)e#o#p*a#p~)e&r*WR$P&j$UWO!^%T!_#o%T#p~%T&j*dROr*ars*ms~*a&j*rO$P&j'u*{R$P&j$UW]!RO!^%T!_#o%T#p~%T'm+ZV]!ROY+UYZ*aZr+Urs+ps#O+U#O#P+w#P~+U'm+wO$P&j]!R'm+zROr+Urs,Ts~+U'm,[U$P&j]!ROY,nZr,nrs-Vs#O,n#O#P-[#P~,n!R,sU]!ROY,nZr,nrs-Vs#O,n#O#P-[#P~,n!R-[O]!R!R-_PO~,n'u-gV$UWOr(krs-|s!^(k!^!_+U!_#o(k#o#p+U#p~(k'u.VZ$P&j$UW]!ROY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x!Z/PZ$UW]!ROY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x!Z/yR$UW]!RO!^%T!_#o%T#p~%T!Z0XT$UWO!^.x!^!_,n!_#o.x#o#p,n#p~.xy0mZ$UWOt%Ttu1`u!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`y1g]$UW'mqOt%Ttu1`u!Q%T!Q![1`![!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`&i2k_$UW#zS'Z%k'epOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`[3q_$UW#zSOt%Ttu3ju}%T}!O3j!O!Q%T!Q![3j![!^%T!_!c%T!c!}3j!}#R%T#R#S3j#S#T%T#T#o3j#p$g%T$g~3j$O4wS#^#v$UWO!^%T!_!`5T!`#o%T#p~%T$O5[R$UW#o#vO!^%T!_#o%T#p~%T%r5lU'v%j$UWOv%Tvw6Ow!^%T!_!`5T!`#o%T#p~%T$O6VS$UW#i#vO!^%T!_!`5T!`#o%T#p~%T'u6jZ$UW]!ROY6cYZ7]Zw6cwx*rx!^6c!^!_8T!_#O6c#O#P:T#P#o6c#o#p8T#p~6c&r7bV$UWOw7]wx*Px!^7]!^!_7w!_#o7]#o#p7w#p~7]&j7zROw7wwx*mx~7w'm8YV]!ROY8TYZ7wZw8Twx+px#O8T#O#P8o#P~8T'm8rROw8Twx8{x~8T'm9SU$P&j]!ROY9fZw9fwx-Vx#O9f#O#P9}#P~9f!R9kU]!ROY9fZw9fwx-Vx#O9f#O#P9}#P~9f!R:QPO~9f'u:YV$UWOw6cwx:ox!^6c!^!_8T!_#o6c#o#p8T#p~6c'u:xZ$P&j$UW]!ROY;kYZ%TZw;kwx/rx!^;k!^!_9f!_#O;k#O#PW{!^%T!_!`5T!`#o%T#p~%T$O>_S#[#v$UWO!^%T!_!`5T!`#o%T#p~%T$u>rSj$m$UWO!^%T!_!`5T!`#o%T#p~%T&i?VR!R&a$UWO!^%T!_#o%T#p~%T&i?gVu%n$UWO!O%T!O!P?|!P!Q%T!Q![@r![!^%T!_#o%T#p~%Ty@RT$UWO!O%T!O!P@b!P!^%T!_#o%T#p~%Ty@iR!Qq$UWO!^%T!_#o%T#p~%Ty@yZ$UWkqO!Q%T!Q![@r![!^%T!_!g%T!g!hAl!h#R%T#R#S@r#S#X%T#X#YAl#Y#o%T#p~%TyAqZ$UWO{%T{|Bd|}%T}!OBd!O!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%TyBiV$UWO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%TyCVV$UWkqO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%T,TCs`$UW#]#vOYDuYZ%TZzDuz{Jl{!PDu!P!Q!-e!Q!^Du!^!_Fx!_!`!.^!`!a!/]!a!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXD|[$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXEy_$UW}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%TPF}V}POYFxZ!PFx!P!QGd!Q!}Fx!}#OG{#O#PHh#P~FxPGiU}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGdPHOTOYG{Z#OG{#O#PH_#P#QFx#Q~G{PHbQOYG{Z~G{PHkQOYFxZ~FxXHvY$UWOYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~HqXIkV$UWOYHqYZ%TZ!^Hq!^!_G{!_#oHq#o#pG{#p~HqXJVV$UWOYDuYZ%TZ!^Du!^!_Fx!_#oDu#o#pFx#p~Du,TJs^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q!,R!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl,TKtV$UWOzKoz{LZ{!^Ko!^!_M]!_#oKo#o#pM]#p~Ko,TL`X$UWOzKoz{LZ{!PKo!P!QL{!Q!^Ko!^!_M]!_#oKo#o#pM]#p~Ko,TMSR$UWU+{O!^%T!_#o%T#p~%T+{M`ROzM]z{Mi{~M]+{MlTOzM]z{Mi{!PM]!P!QM{!Q~M]+{NQOU+{,TNX^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q! T!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl,T! ^_$UWU+{}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%T+{!!bY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!&x!Q!}!!]!}#O!$`#O#P!&f#P~!!]+{!#VY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!#u!Q!}!!]!}#O!$`#O#P!&f#P~!!]+{!#|UU+{}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGd+{!$cWOY!$`YZM]Zz!$`z{!${{#O!$`#O#P!&S#P#Q!!]#Q~!$`+{!%OYOY!$`YZM]Zz!$`z{!${{!P!$`!P!Q!%n!Q#O!$`#O#P!&S#P#Q!!]#Q~!$`+{!%sTU+{OYG{Z#OG{#O#PH_#P#QFx#Q~G{+{!&VTOY!$`YZM]Zz!$`z{!${{~!$`+{!&iTOY!!]YZM]Zz!!]z{!#Q{~!!]+{!&}_}POzM]z{Mi{#ZM]#Z#[!&x#[#]M]#]#^!&x#^#aM]#a#b!&x#b#gM]#g#h!&x#h#iM]#i#j!&x#j#mM]#m#n!&x#n~M],T!(R[$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|,T!(|^$UWOY!'|YZKoZz!'|z{!(w{!P!'|!P!Q!)x!Q!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|,T!*PY$UWU+{OYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~Hq,T!*tX$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#o!'|#o#p!$`#p~!'|,T!+fX$UWOYJlYZKoZzJlz{NQ{!^Jl!^!_!!]!_#oJl#o#p!!]#p~Jl,T!,Yc$UW}POzKoz{LZ{!^Ko!^!_M]!_#ZKo#Z#[!,R#[#]Ko#]#^!,R#^#aKo#a#b!,R#b#gKo#g#h!,R#h#iKo#i#j!,R#j#mKo#m#n!,R#n#oKo#o#pM]#p~Ko,T!-lV$UWT+{OY!-eYZ%TZ!^!-e!^!_!.R!_#o!-e#o#p!.R#p~!-e+{!.WQT+{OY!.RZ~!.R$P!.g[$UW#o#v}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Du]!/f[#wS$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Duy!0cd$UWkqO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#U%T#U#V!3X#V#X%T#X#YAl#Y#b%T#b#c!2w#c#d!4m#d#l%T#l#m!5{#m#o%T#p~%Ty!1x_$UWkqO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#X%T#X#YAl#Y#b%T#b#c!2w#c#o%T#p~%Ty!3OR$UWkqO!^%T!_#o%T#p~%Ty!3^W$UWO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#o%T#p~%Ty!3}Y$UWkqO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#b%T#b#c!2w#c#o%T#p~%Ty!4rV$UWO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#o%T#p~%Ty!5`X$UWkqO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#b%T#b#c!2w#c#o%T#p~%Ty!6QZ$UWO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#o%T#p~%Ty!6z]$UWkqO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#b%T#b#c!2w#c#o%T#p~%T%w!7|R!]V$UW#m%hO!^%T!_#o%T#p~%T!P!8^R_w$UWO!^%T!_#o%T#p~%T+c!8rR'`d!a%Y#x&s'zP!P!Q!8{!^!_!9Q!_!`!9_W!9QO$WW#v!9VP#`#v!_!`!9Y#v!9_O#o#v#v!9dO#a#v%w!9kT!{%o$UWO!^%T!_!`'v!`!a!9z!a#o%T#p~%T$P!:RR#W#w$UWO!^%T!_#o%T#p~%T%w!:gT'_!s#a#v$RS$UWO!^%T!_!`!:v!`!a!;W!a#o%T#p~%T$O!:}R#a#v$UWO!^%T!_#o%T#p~%T$O!;_T#`#v$UWO!^%T!_!`5T!`!a!;n!a#o%T#p~%T$O!;uS#`#v$UWO!^%T!_!`5T!`#o%T#p~%T%w!]S#g#v$UWO!^%T!_!`5T!`#o%T#p~%T$P!>pR$UW'd#wO!^%T!_#o%T#p~%T~!?OO!T~%r!?VT'u%j$UWO!^%T!_!`5T!`#o%T#p#q!=P#q~%T$u!?oR!S$knQ$UWO!^%T!_#o%T#p~%TX!@PR!kP$UWO!^%T!_#o%T#p~%T,T!@gr$UW'W+{#zS'Z%k'epOX%TXY%cYZ%TZ[%c[p%Tpq%cqt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`,T!CO_$UW'X+{#zS'Z%k'epOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`",
- tokenizers: [noSemicolon, incdecToken, template, 0, 1, 2, 3, 4, 5, 6, 7, 8, insertSemicolon],
- topRules: {"Script":[0,7]},
- dialects: {jsx: 11335, ts: 11337},
- dynamicPrecedences: {"149":1,"176":1},
- specialized: [{term: 287, get: (value, stack) => (tsExtends(value, stack) << 1)},{term: 287, get: value => spec_identifier[value] || -1},{term: 297, get: value => spec_word[value] || -1},{term: 63, get: value => spec_LessThan[value] || -1}],
- tokenPrec: 11358
-});
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ return this[offset]
+}
+
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return this[offset] | (this[offset + 1] << 8)
+}
+
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return (this[offset] << 8) | this[offset + 1]
+}
+
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return ((this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16)) +
+ (this[offset + 3] * 0x1000000)
+}
+
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] * 0x1000000) +
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
+}
+
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ if (!(this[offset] & 0x80)) return (this[offset])
+ return ((0xff - this[offset] + 1) * -1)
+}
+
+Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset] | (this[offset + 1] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset + 1] | (this[offset] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
-exports.parser = parser;
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
-},{"@lezer/common":55,"@lezer/lr":57}],57:[function(require,module,exports){
-(function (process){
-'use strict';
+ return (this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
+}
-Object.defineProperty(exports, '__esModule', { value: true });
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
-var common = require('@lezer/common');
+ return (this[offset] << 24) |
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
+}
-/// A parse stack. These are used internally by the parser to track
-/// parsing progress. They also provide some properties and methods
-/// that external code such as a tokenizer can use to get information
-/// about the parse state.
-class Stack {
- /// @internal
- constructor(
- /// The parse that this stack is part of @internal
- p,
- /// Holds state, input pos, buffer index triplets for all but the
- /// top state @internal
- stack,
- /// The current parse state @internal
- state,
- // The position at which the next reduce should take place. This
- // can be less than `this.pos` when skipped expressions have been
- // added to the stack (which should be moved outside of the next
- // reduction)
- /// @internal
- reducePos,
- /// The input position up to which this stack has parsed.
- pos,
- /// The dynamic score of the stack, including dynamic precedence
- /// and error-recovery penalties
- /// @internal
- score,
- // The output buffer. Holds (type, start, end, size) quads
- // representing nodes created by the parser, where `size` is
- // amount of buffer array entries covered by this node.
- /// @internal
- buffer,
- // The base offset of the buffer. When stacks are split, the split
- // instance shared the buffer history with its parent up to
- // `bufferBase`, which is the absolute offset (including the
- // offset of previous splits) into the buffer at which this stack
- // starts writing.
- /// @internal
- bufferBase,
- /// @internal
- curContext,
- /// @internal
- lookAhead = 0,
- // A parent stack from which this was split off, if any. This is
- // set up so that it always points to a stack that has some
- // additional buffer content, never to a stack with an equal
- // `bufferBase`.
- /// @internal
- parent) {
- this.p = p;
- this.stack = stack;
- this.state = state;
- this.reducePos = reducePos;
- this.pos = pos;
- this.score = score;
- this.buffer = buffer;
- this.bufferBase = bufferBase;
- this.curContext = curContext;
- this.lookAhead = lookAhead;
- this.parent = parent;
- }
- /// @internal
- toString() {
- return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
- }
- // Start an empty stack
- /// @internal
- static start(p, state, pos = 0) {
- let cx = p.parser.context;
- return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
- }
- /// The stack's current [context](#lr.ContextTracker) value, if
- /// any. Its type will depend on the context tracker's type
- /// parameter, or it will be `null` if there is no context
- /// tracker.
- get context() { return this.curContext ? this.curContext.context : null; }
- // Push a state onto the stack, tracking its start position as well
- // as the buffer base at that point.
- /// @internal
- pushState(state, start) {
- this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
- this.state = state;
- }
- // Apply a reduce action
- /// @internal
- reduce(action) {
- let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */;
- let { parser } = this.p;
- let dPrec = parser.dynamicPrecedence(type);
- if (dPrec)
- this.score += dPrec;
- if (depth == 0) {
- this.pushState(parser.getGoto(this.state, type, true), this.reducePos);
- // Zero-depth reductions are a special case—they add stuff to
- // the stack without popping anything off.
- if (type < parser.minRepeatTerm)
- this.storeNode(type, this.reducePos, this.reducePos, 4, true);
- this.reduceContext(type, this.reducePos);
- return;
- }
- // Find the base index into `this.stack`, content after which will
- // be dropped. Note that with `StayFlag` reductions we need to
- // consume two extra frames (the dummy parent node for the skipped
- // expression and the state that we'll be staying in, which should
- // be moved to `this.state`).
- let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0);
- let start = this.stack[base - 2];
- let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase;
- // Store normal terms or `R -> R R` repeat reductions
- if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) {
- let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos;
- this.storeNode(type, start, pos, count + 4, true);
- }
- if (action & 262144 /* StayFlag */) {
- this.state = this.stack[base];
- }
- else {
- let baseStateID = this.stack[base - 3];
- this.state = parser.getGoto(baseStateID, type, true);
- }
- while (this.stack.length > base)
- this.stack.pop();
- this.reduceContext(type, start);
- }
- // Shift a value into the buffer
- /// @internal
- storeNode(term, start, end, size = 4, isReduce = false) {
- if (term == 0 /* Err */) { // Try to omit/merge adjacent error nodes
- let cur = this, top = this.buffer.length;
- if (top == 0 && cur.parent) {
- top = cur.bufferBase - cur.parent.bufferBase;
- cur = cur.parent;
- }
- if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) {
- if (start == end)
- return;
- if (cur.buffer[top - 2] >= start) {
- cur.buffer[top - 2] = end;
- return;
- }
- }
- }
- if (!isReduce || this.pos == end) { // Simple case, just append
- this.buffer.push(term, start, end, size);
- }
- else { // There may be skipped nodes that have to be moved forward
- let index = this.buffer.length;
- if (index > 0 && this.buffer[index - 4] != 0 /* Err */)
- while (index > 0 && this.buffer[index - 2] > end) {
- // Move this record forward
- this.buffer[index] = this.buffer[index - 4];
- this.buffer[index + 1] = this.buffer[index - 3];
- this.buffer[index + 2] = this.buffer[index - 2];
- this.buffer[index + 3] = this.buffer[index - 1];
- index -= 4;
- if (size > 4)
- size -= 4;
- }
- this.buffer[index] = term;
- this.buffer[index + 1] = start;
- this.buffer[index + 2] = end;
- this.buffer[index + 3] = size;
- }
- }
- // Apply a shift action
- /// @internal
- shift(action, next, nextEnd) {
- let start = this.pos;
- if (action & 131072 /* GotoFlag */) {
- this.pushState(action & 65535 /* ValueMask */, this.pos);
- }
- else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift
- let nextState = action, { parser } = this.p;
- if (nextEnd > this.pos || next <= parser.maxNode) {
- this.pos = nextEnd;
- if (!parser.stateFlag(nextState, 1 /* Skipped */))
- this.reducePos = nextEnd;
- }
- this.pushState(nextState, start);
- this.shiftContext(next, start);
- if (next <= parser.maxNode)
- this.buffer.push(next, start, nextEnd, 4);
- }
- else { // Shift-and-stay, which means this is a skipped token
- this.pos = nextEnd;
- this.shiftContext(next, start);
- if (next <= this.p.parser.maxNode)
- this.buffer.push(next, start, nextEnd, 4);
- }
- }
- // Apply an action
- /// @internal
- apply(action, next, nextEnd) {
- if (action & 65536 /* ReduceFlag */)
- this.reduce(action);
- else
- this.shift(action, next, nextEnd);
- }
- // Add a prebuilt (reused) node into the buffer.
- /// @internal
- useNode(value, next) {
- let index = this.p.reused.length - 1;
- if (index < 0 || this.p.reused[index] != value) {
- this.p.reused.push(value);
- index++;
- }
- let start = this.pos;
- this.reducePos = this.pos = start + value.length;
- this.pushState(next, start);
- this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);
- if (this.curContext)
- this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
- }
- // Split the stack. Due to the buffer sharing and the fact
- // that `this.stack` tends to stay quite shallow, this isn't very
- // expensive.
- /// @internal
- split() {
- let parent = this;
- let off = parent.buffer.length;
- // Because the top of the buffer (after this.pos) may be mutated
- // to reorder reductions and skipped tokens, and shared buffers
- // should be immutable, this copies any outstanding skipped tokens
- // to the new buffer, and puts the base pointer before them.
- while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
- off -= 4;
- let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
- // Make sure parent points to an actual parent with content, if there is such a parent.
- while (parent && base == parent.bufferBase)
- parent = parent.parent;
- return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
- }
- // Try to recover from an error by 'deleting' (ignoring) one token.
- /// @internal
- recoverByDelete(next, nextEnd) {
- let isNode = next <= this.p.parser.maxNode;
- if (isNode)
- this.storeNode(next, this.pos, nextEnd, 4);
- this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4);
- this.pos = this.reducePos = nextEnd;
- this.score -= 190 /* Delete */;
- }
- /// Check if the given term would be able to be shifted (optionally
- /// after some reductions) on this stack. This can be useful for
- /// external tokenizers that want to make sure they only provide a
- /// given token when it applies.
- canShift(term) {
- for (let sim = new SimulatedStack(this);;) {
- let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term);
- if ((action & 65536 /* ReduceFlag */) == 0)
- return true;
- if (action == 0)
- return false;
- sim.reduce(action);
- }
- }
- // Apply up to Recover.MaxNext recovery actions that conceptually
- // inserts some missing token or rule.
- /// @internal
- recoverByInsert(next) {
- if (this.stack.length >= 300 /* MaxInsertStackDepth */)
- return [];
- let nextStates = this.p.parser.nextStates(this.state);
- if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) {
- let best = [];
- for (let i = 0, s; i < nextStates.length; i += 2) {
- if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
- best.push(nextStates[i], s);
- }
- if (this.stack.length < 120 /* DampenInsertStackDepth */)
- for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) {
- let s = nextStates[i + 1];
- if (!best.some((v, i) => (i & 1) && v == s))
- best.push(nextStates[i], s);
- }
- nextStates = best;
- }
- let result = [];
- for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) {
- let s = nextStates[i + 1];
- if (s == this.state)
- continue;
- let stack = this.split();
- stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true);
- stack.pushState(s, this.pos);
- stack.shiftContext(nextStates[i], this.pos);
- stack.score -= 200 /* Insert */;
- result.push(stack);
- }
- return result;
- }
- // Force a reduce, if possible. Return false if that can't
- // be done.
- /// @internal
- forceReduce() {
- let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */);
- if ((reduce & 65536 /* ReduceFlag */) == 0)
- return false;
- let { parser } = this.p;
- if (!parser.validAction(this.state, reduce)) {
- let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */;
- let target = this.stack.length - depth * 3;
- if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0)
- return false;
- this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true);
- this.score -= 100 /* Reduce */;
- }
- this.reduce(reduce);
- return true;
- }
- /// @internal
- forceAll() {
- while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) {
- if (!this.forceReduce()) {
- this.storeNode(0 /* Err */, this.pos, this.pos, 4, true);
- break;
- }
- }
- return this;
- }
- /// Check whether this state has no further actions (assumed to be a direct descendant of the
- /// top state, since any other states must be able to continue
- /// somehow). @internal
- get deadEnd() {
- if (this.stack.length != 3)
- return false;
- let { parser } = this.p;
- return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ &&
- !parser.stateSlot(this.state, 4 /* DefaultReduce */);
- }
- /// Restart the stack (put it back in its start state). Only safe
- /// when this.stack.length == 3 (state is directly below the top
- /// state). @internal
- restart() {
- this.state = this.stack[0];
- this.stack.length = 0;
- }
- /// @internal
- sameState(other) {
- if (this.state != other.state || this.stack.length != other.stack.length)
- return false;
- for (let i = 0; i < this.stack.length; i += 3)
- if (this.stack[i] != other.stack[i])
- return false;
- return true;
- }
- /// Get the parser used by this stack.
- get parser() { return this.p.parser; }
- /// Test whether a given dialect (by numeric ID, as exported from
- /// the terms file) is enabled.
- dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }
- shiftContext(term, start) {
- if (this.curContext)
- this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
- }
- reduceContext(term, start) {
- if (this.curContext)
- this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
- }
- /// @internal
- emitContext() {
- let last = this.buffer.length - 1;
- if (last < 0 || this.buffer[last] != -3)
- this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3);
- }
- /// @internal
- emitLookAhead() {
- let last = this.buffer.length - 1;
- if (last < 0 || this.buffer[last] != -4)
- this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4);
- }
- updateContext(context) {
- if (context != this.curContext.context) {
- let newCx = new StackContext(this.curContext.tracker, context);
- if (newCx.hash != this.curContext.hash)
- this.emitContext();
- this.curContext = newCx;
- }
- }
- /// @internal
- setLookAhead(lookAhead) {
- if (lookAhead > this.lookAhead) {
- this.emitLookAhead();
- this.lookAhead = lookAhead;
- }
- }
- /// @internal
- close() {
- if (this.curContext && this.curContext.tracker.strict)
- this.emitContext();
- if (this.lookAhead > 0)
- this.emitLookAhead();
- }
+Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, true, 23, 4)
}
-class StackContext {
- constructor(tracker, context) {
- this.tracker = tracker;
- this.context = context;
- this.hash = tracker.strict ? tracker.hash(context) : 0;
- }
+
+Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, false, 23, 4)
}
-var Recover;
-(function (Recover) {
- Recover[Recover["Insert"] = 200] = "Insert";
- Recover[Recover["Delete"] = 190] = "Delete";
- Recover[Recover["Reduce"] = 100] = "Reduce";
- Recover[Recover["MaxNext"] = 4] = "MaxNext";
- Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
- Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
-})(Recover || (Recover = {}));
-// Used to cheaply run some reductions to scan ahead without mutating
-// an entire stack
-class SimulatedStack {
- constructor(start) {
- this.start = start;
- this.state = start.state;
- this.stack = start.stack;
- this.base = this.stack.length;
- }
- reduce(action) {
- let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */;
- if (depth == 0) {
- if (this.stack == this.start.stack)
- this.stack = this.stack.slice();
- this.stack.push(this.state, 0, 0);
- this.base += 3;
- }
- else {
- this.base -= (depth - 1) * 3;
- }
- let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
- this.state = goto;
- }
+
+Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, true, 52, 8)
}
-// This is given to `Tree.build` to build a buffer, and encapsulates
-// the parent-stack-walking necessary to read the nodes.
-class StackBufferCursor {
- constructor(stack, pos, index) {
- this.stack = stack;
- this.pos = pos;
- this.index = index;
- this.buffer = stack.buffer;
- if (this.index == 0)
- this.maybeNext();
- }
- static create(stack, pos = stack.bufferBase + stack.buffer.length) {
- return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
- }
- maybeNext() {
- let next = this.stack.parent;
- if (next != null) {
- this.index = this.stack.bufferBase - next.bufferBase;
- this.stack = next;
- this.buffer = next.buffer;
- }
- }
- get id() { return this.buffer[this.index - 4]; }
- get start() { return this.buffer[this.index - 3]; }
- get end() { return this.buffer[this.index - 2]; }
- get size() { return this.buffer[this.index - 1]; }
- next() {
- this.index -= 4;
- this.pos -= 4;
- if (this.index == 0)
- this.maybeNext();
- }
- fork() {
- return new StackBufferCursor(this.stack, this.pos, this.index);
- }
+
+Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, false, 52, 8)
+}
+
+function checkInt (buf, value, offset, ext, max, min) {
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
-class CachedToken {
- constructor() {
- this.start = -1;
- this.value = -1;
- this.end = -1;
- this.extended = -1;
- this.lookAhead = 0;
- this.mask = 0;
- this.context = 0;
- }
+Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
+
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
}
-const nullToken = new CachedToken;
-/// [Tokenizers](#lr.ExternalTokenizer) interact with the input
-/// through this interface. It presents the input as a stream of
-/// characters, tracking lookahead and hiding the complexity of
-/// [ranges](#common.Parser.parse^ranges) from tokenizer code.
-class InputStream {
- /// @internal
- constructor(
- /// @internal
- input,
- /// @internal
- ranges) {
- this.input = input;
- this.ranges = ranges;
- /// @internal
- this.chunk = "";
- /// @internal
- this.chunkOff = 0;
- /// Backup chunk
- this.chunk2 = "";
- this.chunk2Pos = 0;
- /// The character code of the next code unit in the input, or -1
- /// when the stream is at the end of the input.
- this.next = -1;
- /// @internal
- this.token = nullToken;
- this.rangeIndex = 0;
- this.pos = this.chunkPos = ranges[0].from;
- this.range = ranges[0];
- this.end = ranges[ranges.length - 1].to;
- this.readNext();
- }
- resolveOffset(offset, assoc) {
- let range = this.range, index = this.rangeIndex;
- let pos = this.pos + offset;
- while (pos < range.from) {
- if (!index)
- return null;
- let next = this.ranges[--index];
- pos -= range.from - next.to;
- range = next;
- }
- while (assoc < 0 ? pos > range.to : pos >= range.to) {
- if (index == this.ranges.length - 1)
- return null;
- let next = this.ranges[++index];
- pos += next.from - range.to;
- range = next;
- }
- return pos;
- }
- /// Look at a code unit near the stream position. `.peek(0)` equals
- /// `.next`, `.peek(-1)` gives you the previous character, and so
- /// on.
- ///
- /// Note that looking around during tokenizing creates dependencies
- /// on potentially far-away content, which may reduce the
- /// effectiveness incremental parsing—when looking forward—or even
- /// cause invalid reparses when looking backward more than 25 code
- /// units, since the library does not track lookbehind.
- peek(offset) {
- let idx = this.chunkOff + offset, pos, result;
- if (idx >= 0 && idx < this.chunk.length) {
- pos = this.pos + offset;
- result = this.chunk.charCodeAt(idx);
- }
- else {
- let resolved = this.resolveOffset(offset, 1);
- if (resolved == null)
- return -1;
- pos = resolved;
- if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
- result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
- }
- else {
- let i = this.rangeIndex, range = this.range;
- while (range.to <= pos)
- range = this.ranges[++i];
- this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
- if (pos + this.chunk2.length > range.to)
- this.chunk2 = this.chunk2.slice(0, range.to - pos);
- result = this.chunk2.charCodeAt(0);
- }
- }
- if (pos >= this.token.lookAhead)
- this.token.lookAhead = pos + 1;
- return result;
- }
- /// Accept a token. By default, the end of the token is set to the
- /// current stream position, but you can pass an offset (relative to
- /// the stream position) to change that.
- acceptToken(token, endOffset = 0) {
- let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
- if (end == null || end < this.token.start)
- throw new RangeError("Token end out of bounds");
- this.token.value = token;
- this.token.end = end;
- }
- getChunk() {
- if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
- let { chunk, chunkPos } = this;
- this.chunk = this.chunk2;
- this.chunkPos = this.chunk2Pos;
- this.chunk2 = chunk;
- this.chunk2Pos = chunkPos;
- this.chunkOff = this.pos - this.chunkPos;
- }
- else {
- this.chunk2 = this.chunk;
- this.chunk2Pos = this.chunkPos;
- let nextChunk = this.input.chunk(this.pos);
- let end = this.pos + nextChunk.length;
- this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
- this.chunkPos = this.pos;
- this.chunkOff = 0;
- }
- }
- readNext() {
- if (this.chunkOff >= this.chunk.length) {
- this.getChunk();
- if (this.chunkOff == this.chunk.length)
- return this.next = -1;
- }
- return this.next = this.chunk.charCodeAt(this.chunkOff);
- }
- /// Move the stream forward N (defaults to 1) code units. Returns
- /// the new value of [`next`](#lr.InputStream.next).
- advance(n = 1) {
- this.chunkOff += n;
- while (this.pos + n >= this.range.to) {
- if (this.rangeIndex == this.ranges.length - 1)
- return this.setDone();
- n -= this.range.to - this.pos;
- this.range = this.ranges[++this.rangeIndex];
- this.pos = this.range.from;
- }
- this.pos += n;
- if (this.pos >= this.token.lookAhead)
- this.token.lookAhead = this.pos + 1;
- return this.readNext();
- }
- setDone() {
- this.pos = this.chunkPos = this.end;
- this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
- this.chunk = "";
- return this.next = -1;
- }
- /// @internal
- reset(pos, token) {
- if (token) {
- this.token = token;
- token.start = pos;
- token.lookAhead = pos + 1;
- token.value = token.extended = -1;
- }
- else {
- this.token = nullToken;
- }
- if (this.pos != pos) {
- this.pos = pos;
- if (pos == this.end) {
- this.setDone();
- return this;
- }
- while (pos < this.range.from)
- this.range = this.ranges[--this.rangeIndex];
- while (pos >= this.range.to)
- this.range = this.ranges[++this.rangeIndex];
- if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
- this.chunkOff = pos - this.chunkPos;
- }
- else {
- this.chunk = "";
- this.chunkOff = 0;
- }
- this.readNext();
- }
- return this;
- }
- /// @internal
- read(from, to) {
- if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
- return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
- if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
- return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
- if (from >= this.range.from && to <= this.range.to)
- return this.input.read(from, to);
- let result = "";
- for (let r of this.ranges) {
- if (r.from >= to)
- break;
- if (r.to > from)
- result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
- }
- return result;
- }
+
+Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
}
-/// @internal
-class TokenGroup {
- constructor(data, id) {
- this.data = data;
- this.id = id;
- }
- token(input, stack) { readToken(this.data, input, stack, this.id); }
+
+Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
+ this[offset] = (value & 0xff)
+ return offset + 1
}
-TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
-/// `@external tokens` declarations in the grammar should resolve to
-/// an instance of this class.
-class ExternalTokenizer {
- /// Create a tokenizer. The first argument is the function that,
- /// given an input stream, scans for the types of tokens it
- /// recognizes at the stream's position, and calls
- /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds
- /// one.
- constructor(
- /// @internal
- token, options = {}) {
- this.token = token;
- this.contextual = !!options.contextual;
- this.fallback = !!options.fallback;
- this.extend = !!options.extend;
- }
+
+Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ return offset + 2
}
-// Tokenizer data is stored a big uint16 array containing, for each
-// state:
-//
-// - A group bitmask, indicating what token groups are reachable from
-// this state, so that paths that can only lead to tokens not in
-// any of the current groups can be cut off early.
-//
-// - The position of the end of the state's sequence of accepting
-// tokens
-//
-// - The number of outgoing edges for the state
-//
-// - The accepting tokens, as (token id, group mask) pairs
-//
-// - The outgoing edges, as (start character, end character, state
-// index) triples, with end character being exclusive
-//
-// This function interprets that data, running through a stream as
-// long as new states with the a matching group mask can be reached,
-// and updating `token` when it matches a token.
-function readToken(data, input, stack, group) {
- let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser;
- scan: for (;;) {
- if ((groupMask & data[state]) == 0)
- break;
- let accEnd = data[state + 1];
- // Check whether this state can lead to a token in the current group
- // Accept tokens in this state, possibly overwriting
- // lower-precedence / shorter tokens
- for (let i = state + 3; i < accEnd; i += 2)
- if ((data[i + 1] & groupMask) > 0) {
- let term = data[i];
- if (dialect.allows(term) &&
- (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) {
- input.acceptToken(term);
- break;
- }
- }
- // Do a binary search on the state's edges
- for (let next = input.next, low = 0, high = data[state + 2]; low < high;) {
- let mid = (low + high) >> 1;
- let index = accEnd + mid + (mid << 1);
- let from = data[index], to = data[index + 1];
- if (next < from)
- high = mid;
- else if (next >= to)
- low = mid + 1;
- else {
- state = data[index + 2];
- input.advance();
- continue scan;
- }
- }
- break;
- }
+
+Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ return offset + 2
}
-// See lezer-generator/src/encode.ts for comments about the encoding
-// used here
-function decodeArray(input, Type = Uint16Array) {
- if (typeof input != "string")
- return input;
- let array = null;
- for (let pos = 0, out = 0; pos < input.length;) {
- let value = 0;
- for (;;) {
- let next = input.charCodeAt(pos++), stop = false;
- if (next == 126 /* BigValCode */) {
- value = 65535 /* BigVal */;
- break;
- }
- if (next >= 92 /* Gap2 */)
- next--;
- if (next >= 34 /* Gap1 */)
- next--;
- let digit = next - 32 /* Start */;
- if (digit >= 46 /* Base */) {
- digit -= 46 /* Base */;
- stop = true;
- }
- value += digit;
- if (stop)
- break;
- value *= 46 /* Base */;
- }
- if (array)
- array[out++] = value;
- else
- array = new Type(value);
- }
- return array;
+Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ this[offset + 3] = (value >>> 24)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 1] = (value >>> 8)
+ this[offset] = (value & 0xff)
+ return offset + 4
}
-// FIXME find some way to reduce recovery work done when the input
-// doesn't match the grammar at all.
-// Environment variable used to control console output
-const verbose = typeof process != "undefined" && /\bparse\b/.test(process.env.LOG);
-let stackIDs = null;
-var Safety;
-(function (Safety) {
- Safety[Safety["Margin"] = 25] = "Margin";
-})(Safety || (Safety = {}));
-function cutAt(tree, pos, side) {
- let cursor = tree.fullCursor();
- cursor.moveTo(pos);
- for (;;) {
- if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
- for (;;) {
- if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
- return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */))
- : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */));
- if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
- break;
- if (!cursor.parent())
- return side < 0 ? 0 : tree.length;
- }
- }
+Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ return offset + 4
}
-class FragmentCursor {
- constructor(fragments, nodeSet) {
- this.fragments = fragments;
- this.nodeSet = nodeSet;
- this.i = 0;
- this.fragment = null;
- this.safeFrom = -1;
- this.safeTo = -1;
- this.trees = [];
- this.start = [];
- this.index = [];
- this.nextFragment();
- }
- nextFragment() {
- let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
- if (fr) {
- this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
- this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
- while (this.trees.length) {
- this.trees.pop();
- this.start.pop();
- this.index.pop();
- }
- this.trees.push(fr.tree);
- this.start.push(-fr.offset);
- this.index.push(0);
- this.nextStart = this.safeFrom;
- }
- else {
- this.nextStart = 1e9;
- }
- }
- // `pos` must be >= any previously given `pos` for this cursor
- nodeAt(pos) {
- if (pos < this.nextStart)
- return null;
- while (this.fragment && this.safeTo <= pos)
- this.nextFragment();
- if (!this.fragment)
- return null;
- for (;;) {
- let last = this.trees.length - 1;
- if (last < 0) { // End of tree
- this.nextFragment();
- return null;
- }
- let top = this.trees[last], index = this.index[last];
- if (index == top.children.length) {
- this.trees.pop();
- this.start.pop();
- this.index.pop();
- continue;
- }
- let next = top.children[index];
- let start = this.start[last] + top.positions[index];
- if (start > pos) {
- this.nextStart = start;
- return null;
- }
- if (next instanceof common.Tree) {
- if (start == pos) {
- if (start < this.safeFrom)
- return null;
- let end = start + next.length;
- if (end <= this.safeTo) {
- let lookAhead = next.prop(common.NodeProp.lookAhead);
- if (!lookAhead || end + lookAhead < this.fragment.to)
- return next;
- }
- }
- this.index[last]++;
- if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node
- this.trees.push(next);
- this.start.push(start);
- this.index.push(0);
- }
- }
- else {
- this.index[last]++;
- this.nextStart = start + next.length;
- }
- }
+
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ var limit = Math.pow(2, (8 * byteLength) - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = 0
+ var mul = 1
+ var sub = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1
}
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
}
-class TokenCache {
- constructor(parser, stream) {
- this.stream = stream;
- this.tokens = [];
- this.mainToken = null;
- this.actions = [];
- this.tokens = parser.tokenizers.map(_ => new CachedToken);
- }
- getActions(stack) {
- let actionIndex = 0;
- let main = null;
- let { parser } = stack.p, { tokenizers } = parser;
- let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */);
- let context = stack.curContext ? stack.curContext.hash : 0;
- let lookAhead = 0;
- for (let i = 0; i < tokenizers.length; i++) {
- if (((1 << i) & mask) == 0)
- continue;
- let tokenizer = tokenizers[i], token = this.tokens[i];
- if (main && !tokenizer.fallback)
- continue;
- if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
- this.updateCachedToken(token, tokenizer, stack);
- token.mask = mask;
- token.context = context;
- }
- if (token.lookAhead > token.end + 25 /* Margin */)
- lookAhead = Math.max(token.lookAhead, lookAhead);
- if (token.value != 0 /* Err */) {
- let startIndex = actionIndex;
- if (token.extended > -1)
- actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
- actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
- if (!tokenizer.extend) {
- main = token;
- if (actionIndex > startIndex)
- break;
- }
- }
- }
- while (this.actions.length > actionIndex)
- this.actions.pop();
- if (lookAhead)
- stack.setLookAhead(lookAhead);
- if (!main && stack.pos == this.stream.end) {
- main = new CachedToken;
- main.value = stack.p.parser.eofTerm;
- main.start = main.end = stack.pos;
- actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
- }
- this.mainToken = main;
- return this.actions;
- }
- getMainToken(stack) {
- if (this.mainToken)
- return this.mainToken;
- let main = new CachedToken, { pos, p } = stack;
- main.start = pos;
- main.end = Math.min(pos + 1, p.stream.end);
- main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */;
- return main;
- }
- updateCachedToken(token, tokenizer, stack) {
- tokenizer.token(this.stream.reset(stack.pos, token), stack);
- if (token.value > -1) {
- let { parser } = stack.p;
- for (let i = 0; i < parser.specialized.length; i++)
- if (parser.specialized[i] == token.value) {
- let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);
- if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
- if ((result & 1) == 0 /* Specialize */)
- token.value = result >> 1;
- else
- token.extended = result >> 1;
- break;
- }
- }
- }
- else {
- token.value = 0 /* Err */;
- token.end = Math.min(stack.p.stream.end, stack.pos + 1);
- }
- }
- putAction(action, token, end, index) {
- // Don't add duplicate actions
- for (let i = 0; i < index; i += 3)
- if (this.actions[i] == action)
- return index;
- this.actions[index++] = action;
- this.actions[index++] = token;
- this.actions[index++] = end;
- return index;
- }
- addActions(stack, token, end, index) {
- let { state } = stack, { parser } = stack.p, { data } = parser;
- for (let set = 0; set < 2; set++) {
- for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) {
- if (data[i] == 65535 /* End */) {
- if (data[i + 1] == 1 /* Next */) {
- i = pair(data, i + 2);
- }
- else {
- if (index == 0 && data[i + 1] == 2 /* Other */)
- index = this.putAction(pair(data, i + 2), token, end, index);
- break;
- }
- }
- if (data[i] == token)
- index = this.putAction(pair(data, i + 1), token, end, index);
- }
- }
- return index;
+
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ var limit = Math.pow(2, (8 * byteLength) - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ var sub = 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1
}
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
}
-var Rec;
-(function (Rec) {
- Rec[Rec["Distance"] = 5] = "Distance";
- Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
- // When two stacks have been running independently long enough to
- // add this many elements to their buffers, prune one.
- Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune";
- Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit";
- // Once a stack reaches this depth (in .stack.length) force-reduce
- // it back to CutTo to avoid creating trees that overflow the stack
- // on recursive traversal.
- Rec[Rec["CutDepth"] = 15000] = "CutDepth";
- Rec[Rec["CutTo"] = 9000] = "CutTo";
-})(Rec || (Rec = {}));
-class Parse {
- constructor(parser, input, fragments, ranges) {
- this.parser = parser;
- this.input = input;
- this.ranges = ranges;
- this.recovering = 0;
- this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
- this.minStackPos = 0;
- this.reused = [];
- this.stoppedAt = null;
- this.stream = new InputStream(input, ranges);
- this.tokens = new TokenCache(parser, this.stream);
- this.topTerm = parser.top[1];
- let { from } = ranges[0];
- this.stacks = [Stack.start(this, parser.top[0], from)];
- this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4
- ? new FragmentCursor(fragments, parser.nodeSet) : null;
- }
- get parsedPos() {
- return this.minStackPos;
- }
- // Move the parser forward. This will process all parse stacks at
- // `this.pos` and try to advance them to a further position. If no
- // stack for such a position is found, it'll start error-recovery.
- //
- // When the parse is finished, this will return a syntax tree. When
- // not, it returns `null`.
- advance() {
- let stacks = this.stacks, pos = this.minStackPos;
- // This will hold stacks beyond `pos`.
- let newStacks = this.stacks = [];
- let stopped, stoppedTokens;
- // Keep advancing any stacks at `pos` until they either move
- // forward or can't be advanced. Gather stacks that can't be
- // advanced further in `stopped`.
- for (let i = 0; i < stacks.length; i++) {
- let stack = stacks[i];
- for (;;) {
- this.tokens.mainToken = null;
- if (stack.pos > pos) {
- newStacks.push(stack);
- }
- else if (this.advanceStack(stack, newStacks, stacks)) {
- continue;
- }
- else {
- if (!stopped) {
- stopped = [];
- stoppedTokens = [];
- }
- stopped.push(stack);
- let tok = this.tokens.getMainToken(stack);
- stoppedTokens.push(tok.value, tok.end);
- }
- break;
- }
- }
- if (!newStacks.length) {
- let finished = stopped && findFinished(stopped);
- if (finished)
- return this.stackToTree(finished);
- if (this.parser.strict) {
- if (verbose && stopped)
- console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
- throw new SyntaxError("No parse at " + pos);
- }
- if (!this.recovering)
- this.recovering = 5 /* Distance */;
- }
- if (this.recovering && stopped) {
- let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]
- : this.runRecovery(stopped, stoppedTokens, newStacks);
- if (finished)
- return this.stackToTree(finished.forceAll());
- }
- if (this.recovering) {
- let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */;
- if (newStacks.length > maxRemaining) {
- newStacks.sort((a, b) => b.score - a.score);
- while (newStacks.length > maxRemaining)
- newStacks.pop();
- }
- if (newStacks.some(s => s.reducePos > pos))
- this.recovering--;
- }
- else if (newStacks.length > 1) {
- // Prune stacks that are in the same state, or that have been
- // running without splitting for a while, to avoid getting stuck
- // with multiple successful stacks running endlessly on.
- outer: for (let i = 0; i < newStacks.length - 1; i++) {
- let stack = newStacks[i];
- for (let j = i + 1; j < newStacks.length; j++) {
- let other = newStacks[j];
- if (stack.sameState(other) ||
- stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) {
- if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {
- newStacks.splice(j--, 1);
- }
- else {
- newStacks.splice(i--, 1);
- continue outer;
- }
- }
- }
- }
- }
- this.minStackPos = newStacks[0].pos;
- for (let i = 1; i < newStacks.length; i++)
- if (newStacks[i].pos < this.minStackPos)
- this.minStackPos = newStacks[i].pos;
- return null;
- }
- stopAt(pos) {
- if (this.stoppedAt != null && this.stoppedAt < pos)
- throw new RangeError("Can't move stoppedAt forward");
- this.stoppedAt = pos;
- }
- // Returns an updated version of the given stack, or null if the
- // stack can't advance normally. When `split` and `stacks` are
- // given, stacks split off by ambiguous operations will be pushed to
- // `split`, or added to `stacks` if they move `pos` forward.
- advanceStack(stack, stacks, split) {
- let start = stack.pos, { parser } = this;
- let base = verbose ? this.stackID(stack) + " -> " : "";
- if (this.stoppedAt != null && start > this.stoppedAt)
- return stack.forceReduce() ? stack : null;
- if (this.fragments) {
- let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
- for (let cached = this.fragments.nodeAt(start); cached;) {
- let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;
- if (match > -1 && cached.length && (!strictCx || (cached.prop(common.NodeProp.contextHash) || 0) == cxHash)) {
- stack.useNode(cached, match);
- if (verbose)
- console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);
- return true;
- }
- if (!(cached instanceof common.Tree) || cached.children.length == 0 || cached.positions[0] > 0)
- break;
- let inner = cached.children[0];
- if (inner instanceof common.Tree && cached.positions[0] == 0)
- cached = inner;
- else
- break;
- }
- }
- let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */);
- if (defaultReduce > 0) {
- stack.reduce(defaultReduce);
- if (verbose)
- console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`);
- return true;
- }
- if (stack.stack.length >= 15000 /* CutDepth */) {
- while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { }
- }
- let actions = this.tokens.getActions(stack);
- for (let i = 0; i < actions.length;) {
- let action = actions[i++], term = actions[i++], end = actions[i++];
- let last = i == actions.length || !split;
- let localStack = last ? stack : stack.split();
- localStack.apply(action, term, end);
- if (verbose)
- console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift"
- : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
- if (last)
- return true;
- else if (localStack.pos > start)
- stacks.push(localStack);
- else
- split.push(localStack);
- }
- return false;
- }
- // Advance a given stack forward as far as it will go. Returns the
- // (possibly updated) stack if it got stuck, or null if it moved
- // forward and was given to `pushStackDedup`.
- advanceFully(stack, newStacks) {
- let pos = stack.pos;
- for (;;) {
- if (!this.advanceStack(stack, null, null))
- return false;
- if (stack.pos > pos) {
- pushStackDedup(stack, newStacks);
- return true;
- }
- }
- }
- runRecovery(stacks, tokens, newStacks) {
- let finished = null, restarted = false;
- for (let i = 0; i < stacks.length; i++) {
- let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
- let base = verbose ? this.stackID(stack) + " -> " : "";
- if (stack.deadEnd) {
- if (restarted)
- continue;
- restarted = true;
- stack.restart();
- if (verbose)
- console.log(base + this.stackID(stack) + " (restarted)");
- let done = this.advanceFully(stack, newStacks);
- if (done)
- continue;
- }
- let force = stack.split(), forceBase = base;
- for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) {
- if (verbose)
- console.log(forceBase + this.stackID(force) + " (via force-reduce)");
- let done = this.advanceFully(force, newStacks);
- if (done)
- break;
- if (verbose)
- forceBase = this.stackID(force) + " -> ";
- }
- for (let insert of stack.recoverByInsert(token)) {
- if (verbose)
- console.log(base + this.stackID(insert) + " (via recover-insert)");
- this.advanceFully(insert, newStacks);
- }
- if (this.stream.end > stack.pos) {
- if (tokenEnd == stack.pos) {
- tokenEnd++;
- token = 0 /* Err */;
- }
- stack.recoverByDelete(token, tokenEnd);
- if (verbose)
- console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
- pushStackDedup(stack, newStacks);
- }
- else if (!finished || finished.score < stack.score) {
- finished = stack;
- }
- }
- return finished;
- }
- // Convert the stack's buffer to a syntax tree.
- stackToTree(stack) {
- stack.close();
- return common.Tree.build({ buffer: StackBufferCursor.create(stack),
- nodeSet: this.parser.nodeSet,
- topID: this.topTerm,
- maxBufferLength: this.parser.bufferLength,
- reused: this.reused,
- start: this.ranges[0].from,
- length: stack.pos - this.ranges[0].from,
- minRepeatType: this.parser.minRepeatTerm });
- }
- stackID(stack) {
- let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);
- if (!id)
- stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
- return id + stack;
- }
+
+Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
+ if (value < 0) value = 0xff + value + 1
+ this[offset] = (value & 0xff)
+ return offset + 1
}
-function pushStackDedup(stack, newStacks) {
- for (let i = 0; i < newStacks.length; i++) {
- let other = newStacks[i];
- if (other.pos == stack.pos && other.sameState(stack)) {
- if (newStacks[i].score < stack.score)
- newStacks[i] = stack;
- return;
- }
- }
- newStacks.push(stack);
+
+Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ return offset + 2
}
-class Dialect {
- constructor(source, flags, disabled) {
- this.source = source;
- this.flags = flags;
- this.disabled = disabled;
- }
- allows(term) { return !this.disabled || this.disabled[term] == 0; }
+
+Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ return offset + 2
}
-const id = x => x;
-/// Context trackers are used to track stateful context (such as
-/// indentation in the Python grammar, or parent elements in the XML
-/// grammar) needed by external tokenizers. You declare them in a
-/// grammar file as `@context exportName from "module"`.
-///
-/// Context values should be immutable, and can be updated (replaced)
-/// on shift or reduce actions.
-///
-/// The export used in a `@context` declaration should be of this
-/// type.
-class ContextTracker {
- /// Define a context tracker.
- constructor(spec) {
- this.start = spec.start;
- this.shift = spec.shift || id;
- this.reduce = spec.reduce || id;
- this.reuse = spec.reuse || id;
- this.hash = spec.hash || (() => 0);
- this.strict = spec.strict !== false;
- }
+
+Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 3] = (value >>> 24)
+ return offset + 4
+}
+
+Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (value < 0) value = 0xffffffff + value + 1
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ return offset + 4
+}
+
+function checkIEEE754 (buf, value, offset, ext, max, min) {
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
+ if (offset < 0) throw new RangeError('Index out of range')
+}
+
+function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+ return offset + 4
+}
+
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
}
-/// A parser holds the parse tables for a given grammar, as generated
-/// by `lezer-generator`.
-class LRParser extends common.Parser {
- /// @internal
- constructor(spec) {
- super();
- /// @internal
- this.wrappers = [];
- if (spec.version != 13 /* Version */)
- throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${13 /* Version */})`);
- let nodeNames = spec.nodeNames.split(" ");
- this.minRepeatTerm = nodeNames.length;
- for (let i = 0; i < spec.repeatNodeCount; i++)
- nodeNames.push("");
- let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
- let nodeProps = [];
- for (let i = 0; i < nodeNames.length; i++)
- nodeProps.push([]);
- function setProp(nodeID, prop, value) {
- nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
- }
- if (spec.nodeProps)
- for (let propSpec of spec.nodeProps) {
- let prop = propSpec[0];
- for (let i = 1; i < propSpec.length;) {
- let next = propSpec[i++];
- if (next >= 0) {
- setProp(next, prop, propSpec[i++]);
- }
- else {
- let value = propSpec[i + -next];
- for (let j = -next; j > 0; j--)
- setProp(propSpec[i++], prop, value);
- i++;
- }
- }
- }
- this.nodeSet = new common.NodeSet(nodeNames.map((name, i) => common.NodeType.define({
- name: i >= this.minRepeatTerm ? undefined : name,
- id: i,
- props: nodeProps[i],
- top: topTerms.indexOf(i) > -1,
- error: i == 0,
- skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
- })));
- this.strict = false;
- this.bufferLength = common.DefaultBufferLength;
- let tokenArray = decodeArray(spec.tokenData);
- this.context = spec.context;
- this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0);
- this.specializers = [];
- if (spec.specialized)
- for (let i = 0; i < spec.specialized.length; i++) {
- this.specialized[i] = spec.specialized[i].term;
- this.specializers[i] = spec.specialized[i].get;
- }
- this.states = decodeArray(spec.states, Uint32Array);
- this.data = decodeArray(spec.stateData);
- this.goto = decodeArray(spec.goto);
- this.maxTerm = spec.maxTerm;
- this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
- this.topRules = spec.topRules;
- this.dialects = spec.dialects || {};
- this.dynamicPrecedences = spec.dynamicPrecedences || null;
- this.tokenPrecTable = spec.tokenPrec;
- this.termNames = spec.termNames || null;
- this.maxNode = this.nodeSet.types.length - 1;
- this.dialect = this.parseDialect();
- this.top = this.topRules[Object.keys(this.topRules)[0]];
- }
- createParse(input, fragments, ranges) {
- let parse = new Parse(this, input, fragments, ranges);
- for (let w of this.wrappers)
- parse = w(parse, input, fragments, ranges);
- return parse;
+
+function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
+}
+
+Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+ if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (targetStart >= target.length) targetStart = target.length
+ if (!targetStart) targetStart = 0
+ if (end > 0 && end < start) end = start
+
+ // Copy 0 bytes; we're done
+ if (end === start) return 0
+ if (target.length === 0 || this.length === 0) return 0
+
+ // Fatal error conditions
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds')
+ }
+ if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
+
+ // Are we oob?
+ if (end > this.length) end = this.length
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start
+ }
+
+ var len = end - start
+
+ if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
+ // Use built-in when available, missing from IE11
+ this.copyWithin(targetStart, start, end)
+ } else if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (var i = len - 1; i >= 0; --i) {
+ target[i + targetStart] = this[i + start]
}
- /// Get a goto table entry @internal
- getGoto(state, term, loose = false) {
- let table = this.goto;
- if (term >= table[0])
- return -1;
- for (let pos = table[term + 1];;) {
- let groupTag = table[pos++], last = groupTag & 1;
- let target = table[pos++];
- if (last && loose)
- return target;
- for (let end = pos + (groupTag >> 1); pos < end; pos++)
- if (table[pos] == state)
- return target;
- if (last)
- return -1;
- }
+ } else {
+ Uint8Array.prototype.set.call(
+ target,
+ this.subarray(start, end),
+ targetStart
+ )
+ }
+
+ return len
+}
+
+// Usage:
+// buffer.fill(number[, offset[, end]])
+// buffer.fill(buffer[, offset[, end]])
+// buffer.fill(string[, offset[, end]][, encoding])
+Buffer.prototype.fill = function fill (val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start
+ start = 0
+ end = this.length
+ } else if (typeof end === 'string') {
+ encoding = end
+ end = this.length
}
- /// Check if this state has an action for a given terminal @internal
- hasAction(state, terminal) {
- let data = this.data;
- for (let set = 0; set < 2; set++) {
- for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) {
- if ((next = data[i]) == 65535 /* End */) {
- if (data[i + 1] == 1 /* Next */)
- next = data[i = pair(data, i + 2)];
- else if (data[i + 1] == 2 /* Other */)
- return pair(data, i + 2);
- else
- break;
- }
- if (next == terminal || next == 0 /* Err */)
- return pair(data, i + 1);
- }
- }
- return 0;
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string')
}
- /// @internal
- stateSlot(state, slot) {
- return this.states[(state * 6 /* Size */) + slot];
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
}
- /// @internal
- stateFlag(state, flag) {
- return (this.stateSlot(state, 0 /* Flags */) & flag) > 0;
+ if (val.length === 1) {
+ var code = val.charCodeAt(0)
+ if ((encoding === 'utf8' && code < 128) ||
+ encoding === 'latin1') {
+ // Fast path: If `val` fits into a single byte, use that numeric value.
+ val = code
+ }
}
- /// @internal
- validAction(state, action) {
- if (action == this.stateSlot(state, 4 /* DefaultReduce */))
- return true;
- for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) {
- if (this.data[i] == 65535 /* End */) {
- if (this.data[i + 1] == 1 /* Next */)
- i = pair(this.data, i + 2);
- else
- return false;
- }
- if (action == pair(this.data, i + 1))
- return true;
- }
+ } else if (typeof val === 'number') {
+ val = val & 255
+ }
+
+ // Invalid ranges are not set to a default, so can range check early.
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index')
+ }
+
+ if (end <= start) {
+ return this
+ }
+
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
+
+ if (!val) val = 0
+
+ var i
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val
}
- /// Get the states that can follow this one through shift actions or
- /// goto jumps. @internal
- nextStates(state) {
- let result = [];
- for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) {
- if (this.data[i] == 65535 /* End */) {
- if (this.data[i + 1] == 1 /* Next */)
- i = pair(this.data, i + 2);
- else
- break;
- }
- if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) {
- let value = this.data[i + 1];
- if (!result.some((v, i) => (i & 1) && v == value))
- result.push(this.data[i], value);
- }
- }
- return result;
+ } else {
+ var bytes = Buffer.isBuffer(val)
+ ? val
+ : Buffer.from(val, encoding)
+ var len = bytes.length
+ if (len === 0) {
+ throw new TypeError('The value "' + val +
+ '" is invalid for argument "value"')
}
- /// @internal
- overrides(token, prev) {
- let iPrev = findOffset(this.data, this.tokenPrecTable, prev);
- return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev;
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len]
}
- /// Configure the parser. Returns a new parser instance that has the
- /// given settings modified. Settings not provided in `config` are
- /// kept from the original parser.
- configure(config) {
- // Hideous reflection-based kludge to make it easy to create a
- // slightly modified copy of a parser.
- let copy = Object.assign(Object.create(LRParser.prototype), this);
- if (config.props)
- copy.nodeSet = this.nodeSet.extend(...config.props);
- if (config.top) {
- let info = this.topRules[config.top];
- if (!info)
- throw new RangeError(`Invalid top rule name ${config.top}`);
- copy.top = info;
+ }
+
+ return this
+}
+
+// HELPER FUNCTIONS
+// ================
+
+var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
+
+function base64clean (str) {
+ // Node takes equal signs as end of the Base64 encoding
+ str = str.split('=')[0]
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = str.trim().replace(INVALID_BASE64_RE, '')
+ // Node converts strings with length < 2 to ''
+ if (str.length < 2) return ''
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+ while (str.length % 4 !== 0) {
+ str = str + '='
+ }
+ return str
+}
+
+function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
+}
+
+function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
+
+ for (var i = 0; i < length; ++i) {
+ codePoint = string.charCodeAt(i)
+
+ // is surrogate component
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
}
- if (config.tokenizers)
- copy.tokenizers = this.tokenizers.map(t => {
- let found = config.tokenizers.find(r => r.from == t);
- return found ? found.to : t;
- });
- if (config.contextTracker)
- copy.context = config.contextTracker;
- if (config.dialect)
- copy.dialect = this.parseDialect(config.dialect);
- if (config.strict != null)
- copy.strict = config.strict;
- if (config.wrap)
- copy.wrappers = copy.wrappers.concat(config.wrap);
- if (config.bufferLength != null)
- copy.bufferLength = config.bufferLength;
- return copy;
- }
- /// Returns the name associated with a given term. This will only
- /// work for all terms when the parser was generated with the
- /// `--names` option. By default, only the names of tagged terms are
- /// stored.
- getName(term) {
- return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
- }
- /// The eof term id is always allocated directly after the node
- /// types. @internal
- get eofTerm() { return this.maxNode + 1; }
- /// The type of top node produced by the parser.
- get topNode() { return this.nodeSet.types[this.top[1]]; }
- /// @internal
- dynamicPrecedence(term) {
- let prec = this.dynamicPrecedences;
- return prec == null ? 0 : prec[term] || 0;
- }
- /// @internal
- parseDialect(dialect) {
- let values = Object.keys(this.dialects), flags = values.map(() => false);
- if (dialect)
- for (let part of dialect.split(" ")) {
- let id = values.indexOf(part);
- if (id >= 0)
- flags[id] = true;
- }
- let disabled = null;
- for (let i = 0; i < values.length; i++)
- if (!flags[i]) {
- for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;)
- (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
- }
- return new Dialect(dialect, flags, disabled);
+
+ // valid lead
+ leadSurrogate = codePoint
+
+ continue
+ }
+
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ }
+
+ // valid surrogate pair
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
- /// (used by the output of the parser generator) @internal
- static deserialize(spec) {
- return new LRParser(spec);
+
+ leadSurrogate = null
+
+ // encode utf8
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break
+ bytes.push(codePoint)
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break
+ bytes.push(
+ codePoint >> 0x6 | 0xC0,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break
+ bytes.push(
+ codePoint >> 0xC | 0xE0,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break
+ bytes.push(
+ codePoint >> 0x12 | 0xF0,
+ codePoint >> 0xC & 0x3F | 0x80,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else {
+ throw new Error('Invalid code point')
}
+ }
+
+ return bytes
}
-function pair(data, off) { return data[off] | (data[off + 1] << 16); }
-function findOffset(data, start, term) {
- for (let i = start, next; (next = data[i]) != 65535 /* End */; i++)
- if (next == term)
- return i - start;
- return -1;
+
+function asciiToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF)
+ }
+ return byteArray
}
-function findFinished(stacks) {
- let best = null;
- for (let stack of stacks) {
- let stopped = stack.p.stoppedAt;
- if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&
- stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) &&
- (!best || best.score < stack.score))
- best = stack;
- }
- return best;
+
+function utf16leToBytes (str, units) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ if ((units -= 2) < 0) break
+
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
+ }
+
+ return byteArray
}
-exports.ContextTracker = ContextTracker;
-exports.ExternalTokenizer = ExternalTokenizer;
-exports.InputStream = InputStream;
-exports.LRParser = LRParser;
-exports.Stack = Stack;
+function base64ToBytes (str) {
+ return base64.toByteArray(base64clean(str))
+}
+
+function blitBuffer (src, dst, offset, length) {
+ for (var i = 0; i < length; ++i) {
+ if ((i + offset >= dst.length) || (i >= src.length)) break
+ dst[i + offset] = src[i]
+ }
+ return i
+}
+
+// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
+// the `instanceof` check but they should be treated as of that type.
+// See: https://github.com/feross/buffer/issues/166
+function isInstance (obj, type) {
+ return obj instanceof type ||
+ (obj != null && obj.constructor != null && obj.constructor.name != null &&
+ obj.constructor.name === type.name)
+}
+function numberIsNaN (obj) {
+ // For IE11 support
+ return obj !== obj // eslint-disable-line no-self-compare
+}
-}).call(this,require('_process'))
-},{"@lezer/common":55,"_process":135}],58:[function(require,module,exports){
+}).call(this)}).call(this,require("buffer").Buffer)
+},{"base64-js":41,"buffer":44,"ieee754":90}],45:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter
var storage = require('./lib/storage')
@@ -26508,7 +26802,7 @@ function expose (opts) {
}
}
-},{"./lib/copy":59,"./lib/debug":60,"./lib/help":61,"./lib/log":62,"./lib/logger":63,"./lib/perf":64,"./lib/storage":65,"events":132,"wayfarer/get-all-routes":122}],59:[function(require,module,exports){
+},{"./lib/copy":46,"./lib/debug":47,"./lib/help":48,"./lib/log":49,"./lib/logger":50,"./lib/perf":51,"./lib/storage":52,"events":43,"wayfarer/get-all-routes":131}],46:[function(require,module,exports){
var stateCopy = require('state-copy')
var pluck = require('plucker')
@@ -26524,7 +26818,7 @@ function copy (state) {
stateCopy(isStateString ? pluck.apply(this, arguments) : state)
}
-},{"plucker":111,"state-copy":119}],60:[function(require,module,exports){
+},{"plucker":119,"state-copy":128}],47:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var onChange = require('object-change-callsite')
var nanologger = require('nanologger')
@@ -26566,7 +26860,7 @@ function debug (state, emitter, app, localEmitter) {
})
}
-},{"assert":125,"nanologger":97,"object-change-callsite":107}],61:[function(require,module,exports){
+},{"assert":37,"nanologger":104,"object-change-callsite":115}],48:[function(require,module,exports){
module.exports = help
function help () {
@@ -26599,7 +26893,7 @@ function print (cmd, desc) {
function noop () {}
-},{}],62:[function(require,module,exports){
+},{}],49:[function(require,module,exports){
var removeItems = require('remove-array-items')
var scheduler = require('nanoscheduler')()
var nanologger = require('nanologger')
@@ -26677,7 +26971,7 @@ function log (state, emitter, app, localEmitter) {
function noop () {}
-},{"clone":74,"nanologger":97,"nanoscheduler":105,"remove-array-items":66}],63:[function(require,module,exports){
+},{"clone":61,"nanologger":104,"nanoscheduler":112,"remove-array-items":53}],50:[function(require,module,exports){
var scheduler = require('nanoscheduler')()
var nanologger = require('nanologger')
var Hooks = require('choo-hooks')
@@ -26762,7 +27056,7 @@ function logger (state, emitter, opts) {
}
}
-},{"choo-hooks":67,"nanologger":97,"nanoscheduler":105}],64:[function(require,module,exports){
+},{"choo-hooks":54,"nanologger":104,"nanoscheduler":112}],51:[function(require,module,exports){
var onPerformance = require('on-performance')
var BAR = '█'
@@ -26903,7 +27197,7 @@ function getMedian (args) {
// Do nothing.
function noop () {}
-},{"on-performance":109}],65:[function(require,module,exports){
+},{"on-performance":117}],52:[function(require,module,exports){
var pretty = require('prettier-bytes')
module.exports = storage
@@ -26946,7 +27240,7 @@ function fmt (num) {
function noop () {}
-},{"prettier-bytes":112}],66:[function(require,module,exports){
+},{"prettier-bytes":120}],53:[function(require,module,exports){
'use strict';
/**
@@ -26977,7 +27271,7 @@ function removeItems (arr, startIdx, removeCount) {
module.exports = removeItems;
-},{}],67:[function(require,module,exports){
+},{}],54:[function(require,module,exports){
var onPerformance = require('on-performance')
var scheduler = require('nanoscheduler')()
var assert = require('assert')
@@ -27106,7 +27400,7 @@ ChooHooks.prototype._emitLoaded = function () {
})
}
-},{"assert":125,"nanoscheduler":105,"on-performance":109}],68:[function(require,module,exports){
+},{"assert":37,"nanoscheduler":112,"on-performance":117}],55:[function(require,module,exports){
var assert = require('assert')
var LRU = require('nanolru')
@@ -27149,16 +27443,16 @@ function newCall (Cls) {
return new (Cls.bind.apply(Cls, arguments)) // eslint-disable-line
}
-},{"assert":85,"nanolru":98}],69:[function(require,module,exports){
+},{"assert":93,"nanolru":105}],56:[function(require,module,exports){
module.exports = require('nanocomponent')
-},{"nanocomponent":87}],70:[function(require,module,exports){
+},{"nanocomponent":95}],57:[function(require,module,exports){
module.exports = require('nanohtml')
-},{"nanohtml":92}],71:[function(require,module,exports){
+},{"nanohtml":99}],58:[function(require,module,exports){
module.exports = require('nanohtml/raw')
-},{"nanohtml/raw":95}],72:[function(require,module,exports){
+},{"nanohtml/raw":102}],59:[function(require,module,exports){
var scrollToAnchor = require('scroll-to-anchor')
var documentReady = require('document-ready')
var nanotiming = require('nanotiming')
@@ -27442,7 +27736,7 @@ Choo.prototype._setCache = function (state) {
}
}
-},{"./component/cache":68,"assert":85,"document-ready":75,"nanobus":86,"nanohref":89,"nanomorph":99,"nanoquery":102,"nanoraf":103,"nanorouter":104,"nanotiming":106,"scroll-to-anchor":118}],73:[function(require,module,exports){
+},{"./component/cache":55,"assert":93,"document-ready":62,"nanobus":94,"nanohref":96,"nanomorph":106,"nanoquery":109,"nanoraf":110,"nanorouter":111,"nanotiming":113,"scroll-to-anchor":127}],60:[function(require,module,exports){
/*! clipboard-copy. MIT License. Feross Aboukhadijeh */
/* global DOMException */
@@ -27495,8 +27789,8 @@ function clipboardCopy (text) {
: Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError'))
}
-},{}],74:[function(require,module,exports){
-(function (Buffer){
+},{}],61:[function(require,module,exports){
+(function (Buffer){(function (){
var clone = (function() {
'use strict';
@@ -27607,14211 +27901,13840 @@ function clone(parent, circular, depth, prototype, includeNonEnumerable) {
// Node.js >= 4.5.0
child = Buffer.allocUnsafe(parent.length);
} else {
- // Older Node.js versions
- child = new Buffer(parent.length);
- }
- parent.copy(child);
- return child;
- } else if (_instanceof(parent, Error)) {
- child = Object.create(parent);
- } else {
- if (typeof prototype == 'undefined') {
- proto = Object.getPrototypeOf(parent);
- child = Object.create(proto);
- }
- else {
- child = Object.create(prototype);
- proto = prototype;
- }
- }
-
- if (circular) {
- var index = allParents.indexOf(parent);
-
- if (index != -1) {
- return allChildren[index];
- }
- allParents.push(parent);
- allChildren.push(child);
- }
-
- if (_instanceof(parent, nativeMap)) {
- parent.forEach(function(value, key) {
- var keyChild = _clone(key, depth - 1);
- var valueChild = _clone(value, depth - 1);
- child.set(keyChild, valueChild);
- });
- }
- if (_instanceof(parent, nativeSet)) {
- parent.forEach(function(value) {
- var entryChild = _clone(value, depth - 1);
- child.add(entryChild);
- });
- }
-
- for (var i in parent) {
- var attrs;
- if (proto) {
- attrs = Object.getOwnPropertyDescriptor(proto, i);
- }
-
- if (attrs && attrs.set == null) {
- continue;
- }
- child[i] = _clone(parent[i], depth - 1);
- }
-
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(parent);
- for (var i = 0; i < symbols.length; i++) {
- // Don't need to worry about cloning a symbol because it is a primitive,
- // like a number or string.
- var symbol = symbols[i];
- var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
- if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
- continue;
- }
- child[symbol] = _clone(parent[symbol], depth - 1);
- if (!descriptor.enumerable) {
- Object.defineProperty(child, symbol, {
- enumerable: false
- });
- }
- }
- }
-
- if (includeNonEnumerable) {
- var allPropertyNames = Object.getOwnPropertyNames(parent);
- for (var i = 0; i < allPropertyNames.length; i++) {
- var propertyName = allPropertyNames[i];
- var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
- if (descriptor && descriptor.enumerable) {
- continue;
- }
- child[propertyName] = _clone(parent[propertyName], depth - 1);
- Object.defineProperty(child, propertyName, {
- enumerable: false
- });
- }
- }
-
- return child;
- }
-
- return _clone(parent, depth);
-}
-
-/**
- * Simple flat clone using prototype, accepts only objects, usefull for property
- * override on FLAT configuration object (no nested props).
- *
- * USE WITH CAUTION! This may not behave as you wish if you do not know how this
- * works.
- */
-clone.clonePrototype = function clonePrototype(parent) {
- if (parent === null)
- return null;
-
- var c = function () {};
- c.prototype = parent;
- return new c();
-};
-
-// private utility functions
-
-function __objToStr(o) {
- return Object.prototype.toString.call(o);
-}
-clone.__objToStr = __objToStr;
-
-function __isDate(o) {
- return typeof o === 'object' && __objToStr(o) === '[object Date]';
-}
-clone.__isDate = __isDate;
-
-function __isArray(o) {
- return typeof o === 'object' && __objToStr(o) === '[object Array]';
-}
-clone.__isArray = __isArray;
-
-function __isRegExp(o) {
- return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
-}
-clone.__isRegExp = __isRegExp;
-
-function __getRegExpFlags(re) {
- var flags = '';
- if (re.global) flags += 'g';
- if (re.ignoreCase) flags += 'i';
- if (re.multiline) flags += 'm';
- return flags;
-}
-clone.__getRegExpFlags = __getRegExpFlags;
-
-return clone;
-})();
-
-if (typeof module === 'object' && module.exports) {
- module.exports = clone;
-}
-
-}).call(this,require("buffer").Buffer)
-},{"buffer":131}],75:[function(require,module,exports){
-'use strict'
-
-module.exports = ready
-
-function ready (callback) {
- if (typeof document === 'undefined') {
- throw new Error('document-ready only runs in the browser')
- }
- var state = document.readyState
- if (state === 'complete' || state === 'interactive') {
- return setTimeout(callback, 0)
- }
-
- document.addEventListener('DOMContentLoaded', function onLoad () {
- callback()
- })
-}
-
-},{}],76:[function(require,module,exports){
-module.exports = stringify
-stringify.default = stringify
-stringify.stable = deterministicStringify
-stringify.stableStringify = deterministicStringify
-
-var LIMIT_REPLACE_NODE = '[...]'
-var CIRCULAR_REPLACE_NODE = '[Circular]'
-
-var arr = []
-var replacerStack = []
-
-function defaultOptions () {
- return {
- depthLimit: Number.MAX_SAFE_INTEGER,
- edgesLimit: Number.MAX_SAFE_INTEGER
- }
-}
-
-// Regular stringify
-function stringify (obj, replacer, spacer, options) {
- if (typeof options === 'undefined') {
- options = defaultOptions()
- }
-
- decirc(obj, '', 0, [], undefined, 0, options)
- var res
- try {
- if (replacerStack.length === 0) {
- res = JSON.stringify(obj, replacer, spacer)
- } else {
- res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)
- }
- } catch (_) {
- return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
- } finally {
- while (arr.length !== 0) {
- var part = arr.pop()
- if (part.length === 4) {
- Object.defineProperty(part[0], part[1], part[3])
- } else {
- part[0][part[1]] = part[2]
- }
- }
- }
- return res
-}
-
-function setReplace (replace, val, k, parent) {
- var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
- if (propertyDescriptor.get !== undefined) {
- if (propertyDescriptor.configurable) {
- Object.defineProperty(parent, k, { value: replace })
- arr.push([parent, k, val, propertyDescriptor])
- } else {
- replacerStack.push([val, k, replace])
- }
- } else {
- parent[k] = replace
- arr.push([parent, k, val])
- }
-}
-
-function decirc (val, k, edgeIndex, stack, parent, depth, options) {
- depth += 1
- var i
- if (typeof val === 'object' && val !== null) {
- for (i = 0; i < stack.length; i++) {
- if (stack[i] === val) {
- setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)
- return
- }
- }
-
- if (
- typeof options.depthLimit !== 'undefined' &&
- depth > options.depthLimit
- ) {
- setReplace(LIMIT_REPLACE_NODE, val, k, parent)
- return
- }
-
- if (
- typeof options.edgesLimit !== 'undefined' &&
- edgeIndex + 1 > options.edgesLimit
- ) {
- setReplace(LIMIT_REPLACE_NODE, val, k, parent)
- return
- }
-
- stack.push(val)
- // Optimize for Arrays. Big arrays could kill the performance otherwise!
- if (Array.isArray(val)) {
- for (i = 0; i < val.length; i++) {
- decirc(val[i], i, i, stack, val, depth, options)
- }
- } else {
- var keys = Object.keys(val)
- for (i = 0; i < keys.length; i++) {
- var key = keys[i]
- decirc(val[key], key, i, stack, val, depth, options)
- }
- }
- stack.pop()
- }
-}
-
-// Stable-stringify
-function compareFunction (a, b) {
- if (a < b) {
- return -1
- }
- if (a > b) {
- return 1
- }
- return 0
-}
-
-function deterministicStringify (obj, replacer, spacer, options) {
- if (typeof options === 'undefined') {
- options = defaultOptions()
- }
-
- var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj
- var res
- try {
- if (replacerStack.length === 0) {
- res = JSON.stringify(tmp, replacer, spacer)
- } else {
- res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
- }
- } catch (_) {
- return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
- } finally {
- // Ensure that we restore the object as it was.
- while (arr.length !== 0) {
- var part = arr.pop()
- if (part.length === 4) {
- Object.defineProperty(part[0], part[1], part[3])
- } else {
- part[0][part[1]] = part[2]
- }
- }
- }
- return res
-}
-
-function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) {
- depth += 1
- var i
- if (typeof val === 'object' && val !== null) {
- for (i = 0; i < stack.length; i++) {
- if (stack[i] === val) {
- setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)
- return
- }
- }
- try {
- if (typeof val.toJSON === 'function') {
- return
- }
- } catch (_) {
- return
- }
-
- if (
- typeof options.depthLimit !== 'undefined' &&
- depth > options.depthLimit
- ) {
- setReplace(LIMIT_REPLACE_NODE, val, k, parent)
- return
- }
-
- if (
- typeof options.edgesLimit !== 'undefined' &&
- edgeIndex + 1 > options.edgesLimit
- ) {
- setReplace(LIMIT_REPLACE_NODE, val, k, parent)
- return
- }
-
- stack.push(val)
- // Optimize for Arrays. Big arrays could kill the performance otherwise!
- if (Array.isArray(val)) {
- for (i = 0; i < val.length; i++) {
- deterministicDecirc(val[i], i, i, stack, val, depth, options)
- }
- } else {
- // Create a temporary object in the required way
- var tmp = {}
- var keys = Object.keys(val).sort(compareFunction)
- for (i = 0; i < keys.length; i++) {
- var key = keys[i]
- deterministicDecirc(val[key], key, i, stack, val, depth, options)
- tmp[key] = val[key]
- }
- if (typeof parent !== 'undefined') {
- arr.push([parent, k, val])
- parent[k] = tmp
- } else {
- return tmp
- }
- }
- stack.pop()
- }
-}
-
-// wraps replacer function to handle values we couldn't replace
-// and mark them as replaced value
-function replaceGetterValues (replacer) {
- replacer =
- typeof replacer !== 'undefined'
- ? replacer
- : function (k, v) {
- return v
- }
- return function (key, val) {
- if (replacerStack.length > 0) {
- for (var i = 0; i < replacerStack.length; i++) {
- var part = replacerStack[i]
- if (part[1] === key && part[0] === val) {
- val = part[2]
- replacerStack.splice(i, 1)
- break
- }
- }
- }
- return replacer.call(this, key, val)
- }
-}
-
-},{}],77:[function(require,module,exports){
-(function (global){
-var topLevel = typeof global !== 'undefined' ? global :
- typeof window !== 'undefined' ? window : {}
-var minDoc = require('min-document');
-
-var doccy;
-
-if (typeof document !== 'undefined') {
- doccy = document;
-} else {
- doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
-
- if (!doccy) {
- doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
- }
-}
-
-module.exports = doccy;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"min-document":130}],78:[function(require,module,exports){
-(function (global){
-var win;
-
-if (typeof window !== "undefined") {
- win = window;
-} else if (typeof global !== "undefined") {
- win = global;
-} else if (typeof self !== "undefined"){
- win = self;
-} else {
- win = {};
-}
-
-module.exports = win;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],79:[function(require,module,exports){
-module.exports = attributeToProperty
-
-var transform = {
- 'class': 'className',
- 'for': 'htmlFor',
- 'http-equiv': 'httpEquiv'
-}
-
-function attributeToProperty (h) {
- return function (tagName, attrs, children) {
- for (var attr in attrs) {
- if (attr in transform) {
- attrs[transform[attr]] = attrs[attr]
- delete attrs[attr]
- }
- }
- return h(tagName, attrs, children)
- }
-}
-
-},{}],80:[function(require,module,exports){
-var attrToProp = require('hyperscript-attribute-to-property')
-
-var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4
-var ATTR_KEY = 5, ATTR_KEY_W = 6
-var ATTR_VALUE_W = 7, ATTR_VALUE = 8
-var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10
-var ATTR_EQ = 11, ATTR_BREAK = 12
-var COMMENT = 13
-
-module.exports = function (h, opts) {
- if (!opts) opts = {}
- var concat = opts.concat || function (a, b) {
- return String(a) + String(b)
- }
- if (opts.attrToProp !== false) {
- h = attrToProp(h)
- }
-
- return function (strings) {
- var state = TEXT, reg = ''
- var arglen = arguments.length
- var parts = []
-
- for (var i = 0; i < strings.length; i++) {
- if (i < arglen - 1) {
- var arg = arguments[i+1]
- var p = parse(strings[i])
- var xstate = state
- if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE
- if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE
- if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE
- if (xstate === ATTR) xstate = ATTR_KEY
- if (xstate === OPEN) {
- if (reg === '/') {
- p.push([ OPEN, '/', arg ])
- reg = ''
- } else {
- p.push([ OPEN, arg ])
- }
- } else if (xstate === COMMENT && opts.comments) {
- reg += String(arg)
- } else if (xstate !== COMMENT) {
- p.push([ VAR, xstate, arg ])
- }
- parts.push.apply(parts, p)
- } else parts.push.apply(parts, parse(strings[i]))
- }
-
- var tree = [null,{},[]]
- var stack = [[tree,-1]]
- for (var i = 0; i < parts.length; i++) {
- var cur = stack[stack.length-1][0]
- var p = parts[i], s = p[0]
- if (s === OPEN && /^\//.test(p[1])) {
- var ix = stack[stack.length-1][1]
- if (stack.length > 1) {
- stack.pop()
- stack[stack.length-1][0][2][ix] = h(
- cur[0], cur[1], cur[2].length ? cur[2] : undefined
- )
- }
- } else if (s === OPEN) {
- var c = [p[1],{},[]]
- cur[2].push(c)
- stack.push([c,cur[2].length-1])
- } else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) {
- var key = ''
- var copyKey
- for (; i < parts.length; i++) {
- if (parts[i][0] === ATTR_KEY) {
- key = concat(key, parts[i][1])
- } else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) {
- if (typeof parts[i][2] === 'object' && !key) {
- for (copyKey in parts[i][2]) {
- if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) {
- cur[1][copyKey] = parts[i][2][copyKey]
- }
- }
- } else {
- key = concat(key, parts[i][2])
- }
- } else break
- }
- if (parts[i][0] === ATTR_EQ) i++
- var j = i
- for (; i < parts.length; i++) {
- if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) {
- if (!cur[1][key]) cur[1][key] = strfn(parts[i][1])
- else parts[i][1]==="" || (cur[1][key] = concat(cur[1][key], parts[i][1]));
- } else if (parts[i][0] === VAR
- && (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) {
- if (!cur[1][key]) cur[1][key] = strfn(parts[i][2])
- else parts[i][2]==="" || (cur[1][key] = concat(cur[1][key], parts[i][2]));
- } else {
- if (key.length && !cur[1][key] && i === j
- && (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) {
- // https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes
- // empty string is falsy, not well behaved value in browser
- cur[1][key] = key.toLowerCase()
- }
- if (parts[i][0] === CLOSE) {
- i--
- }
- break
- }
- }
- } else if (s === ATTR_KEY) {
- cur[1][p[1]] = true
- } else if (s === VAR && p[1] === ATTR_KEY) {
- cur[1][p[2]] = true
- } else if (s === CLOSE) {
- if (selfClosing(cur[0]) && stack.length) {
- var ix = stack[stack.length-1][1]
- stack.pop()
- stack[stack.length-1][0][2][ix] = h(
- cur[0], cur[1], cur[2].length ? cur[2] : undefined
- )
- }
- } else if (s === VAR && p[1] === TEXT) {
- if (p[2] === undefined || p[2] === null) p[2] = ''
- else if (!p[2]) p[2] = concat('', p[2])
- if (Array.isArray(p[2][0])) {
- cur[2].push.apply(cur[2], p[2])
- } else {
- cur[2].push(p[2])
- }
- } else if (s === TEXT) {
- cur[2].push(p[1])
- } else if (s === ATTR_EQ || s === ATTR_BREAK) {
- // no-op
- } else {
- throw new Error('unhandled: ' + s)
+ // Older Node.js versions
+ child = new Buffer(parent.length);
+ }
+ parent.copy(child);
+ return child;
+ } else if (_instanceof(parent, Error)) {
+ child = Object.create(parent);
+ } else {
+ if (typeof prototype == 'undefined') {
+ proto = Object.getPrototypeOf(parent);
+ child = Object.create(proto);
+ }
+ else {
+ child = Object.create(prototype);
+ proto = prototype;
}
}
- if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) {
- tree[2].shift()
+ if (circular) {
+ var index = allParents.indexOf(parent);
+
+ if (index != -1) {
+ return allChildren[index];
+ }
+ allParents.push(parent);
+ allChildren.push(child);
}
- if (tree[2].length > 2
- || (tree[2].length === 2 && /\S/.test(tree[2][1]))) {
- if (opts.createFragment) return opts.createFragment(tree[2])
- throw new Error(
- 'multiple root elements must be wrapped in an enclosing tag'
- )
+ if (_instanceof(parent, nativeMap)) {
+ parent.forEach(function(value, key) {
+ var keyChild = _clone(key, depth - 1);
+ var valueChild = _clone(value, depth - 1);
+ child.set(keyChild, valueChild);
+ });
}
- if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string'
- && Array.isArray(tree[2][0][2])) {
- tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2])
+ if (_instanceof(parent, nativeSet)) {
+ parent.forEach(function(value) {
+ var entryChild = _clone(value, depth - 1);
+ child.add(entryChild);
+ });
}
- return tree[2][0]
- function parse (str) {
- var res = []
- if (state === ATTR_VALUE_W) state = ATTR
- for (var i = 0; i < str.length; i++) {
- var c = str.charAt(i)
- if (state === TEXT && c === '<') {
- if (reg.length) res.push([TEXT, reg])
- reg = ''
- state = OPEN
- } else if (c === '>' && !quot(state) && state !== COMMENT) {
- if (state === OPEN && reg.length) {
- res.push([OPEN,reg])
- } else if (state === ATTR_KEY) {
- res.push([ATTR_KEY,reg])
- } else if (state === ATTR_VALUE && reg.length) {
- res.push([ATTR_VALUE,reg])
- }
- res.push([CLOSE])
- reg = ''
- state = TEXT
- } else if (state === COMMENT && /-$/.test(reg) && c === '-') {
- if (opts.comments) {
- res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)])
- }
- reg = ''
- state = TEXT
- } else if (state === OPEN && /^!--$/.test(reg)) {
- if (opts.comments) {
- res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ])
- }
- reg = c
- state = COMMENT
- } else if (state === TEXT || state === COMMENT) {
- reg += c
- } else if (state === OPEN && c === '/' && reg.length) {
- // no-op, self closing tag without a space
- } else if (state === OPEN && /\s/.test(c)) {
- if (reg.length) {
- res.push([OPEN, reg])
- }
- reg = ''
- state = ATTR
- } else if (state === OPEN) {
- reg += c
- } else if (state === ATTR && /[^\s"'=/]/.test(c)) {
- state = ATTR_KEY
- reg = c
- } else if (state === ATTR && /\s/.test(c)) {
- if (reg.length) res.push([ATTR_KEY,reg])
- res.push([ATTR_BREAK])
- } else if (state === ATTR_KEY && /\s/.test(c)) {
- res.push([ATTR_KEY,reg])
- reg = ''
- state = ATTR_KEY_W
- } else if (state === ATTR_KEY && c === '=') {
- res.push([ATTR_KEY,reg],[ATTR_EQ])
- reg = ''
- state = ATTR_VALUE_W
- } else if (state === ATTR_KEY) {
- reg += c
- } else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') {
- res.push([ATTR_EQ])
- state = ATTR_VALUE_W
- } else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) {
- res.push([ATTR_BREAK])
- if (/[\w-]/.test(c)) {
- reg += c
- state = ATTR_KEY
- } else state = ATTR
- } else if (state === ATTR_VALUE_W && c === '"') {
- state = ATTR_VALUE_DQ
- } else if (state === ATTR_VALUE_W && c === "'") {
- state = ATTR_VALUE_SQ
- } else if (state === ATTR_VALUE_DQ && c === '"') {
- res.push([ATTR_VALUE,reg],[ATTR_BREAK])
- reg = ''
- state = ATTR
- } else if (state === ATTR_VALUE_SQ && c === "'") {
- res.push([ATTR_VALUE,reg],[ATTR_BREAK])
- reg = ''
- state = ATTR
- } else if (state === ATTR_VALUE_W && !/\s/.test(c)) {
- state = ATTR_VALUE
- i--
- } else if (state === ATTR_VALUE && /\s/.test(c)) {
- res.push([ATTR_VALUE,reg],[ATTR_BREAK])
- reg = ''
- state = ATTR
- } else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ
- || state === ATTR_VALUE_DQ) {
- reg += c
+ for (var i in parent) {
+ var attrs;
+ if (proto) {
+ attrs = Object.getOwnPropertyDescriptor(proto, i);
+ }
+
+ if (attrs && attrs.set == null) {
+ continue;
+ }
+ child[i] = _clone(parent[i], depth - 1);
+ }
+
+ if (Object.getOwnPropertySymbols) {
+ var symbols = Object.getOwnPropertySymbols(parent);
+ for (var i = 0; i < symbols.length; i++) {
+ // Don't need to worry about cloning a symbol because it is a primitive,
+ // like a number or string.
+ var symbol = symbols[i];
+ var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
+ if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
+ continue;
+ }
+ child[symbol] = _clone(parent[symbol], depth - 1);
+ if (!descriptor.enumerable) {
+ Object.defineProperty(child, symbol, {
+ enumerable: false
+ });
}
}
- if (state === TEXT && reg.length) {
- res.push([TEXT,reg])
- reg = ''
- } else if (state === ATTR_VALUE && reg.length) {
- res.push([ATTR_VALUE,reg])
- reg = ''
- } else if (state === ATTR_VALUE_DQ && reg.length) {
- res.push([ATTR_VALUE,reg])
- reg = ''
- } else if (state === ATTR_VALUE_SQ && reg.length) {
- res.push([ATTR_VALUE,reg])
- reg = ''
- } else if (state === ATTR_KEY) {
- res.push([ATTR_KEY,reg])
- reg = ''
+ }
+
+ if (includeNonEnumerable) {
+ var allPropertyNames = Object.getOwnPropertyNames(parent);
+ for (var i = 0; i < allPropertyNames.length; i++) {
+ var propertyName = allPropertyNames[i];
+ var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
+ if (descriptor && descriptor.enumerable) {
+ continue;
+ }
+ child[propertyName] = _clone(parent[propertyName], depth - 1);
+ Object.defineProperty(child, propertyName, {
+ enumerable: false
+ });
}
- return res
}
- }
- function strfn (x) {
- if (typeof x === 'function') return x
- else if (typeof x === 'string') return x
- else if (x && typeof x === 'object') return x
- else if (x === null || x === undefined) return x
- else return concat('', x)
+ return child;
}
-}
-function quot (state) {
- return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ
+ return _clone(parent, depth);
}
-var closeRE = RegExp('^(' + [
- 'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed',
- 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param',
- 'source', 'track', 'wbr', '!--',
- // SVG TAGS
- 'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse',
- 'feBlend', 'feColorMatrix', 'feComposite',
- 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
- 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR',
- 'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology',
- 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
- 'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri',
- 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath',
- 'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view',
- 'vkern'
-].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$')
-function selfClosing (tag) { return closeRE.test(tag) }
+/**
+ * Simple flat clone using prototype, accepts only objects, usefull for property
+ * override on FLAT configuration object (no nested props).
+ *
+ * USE WITH CAUTION! This may not behave as you wish if you do not know how this
+ * works.
+ */
+clone.clonePrototype = function clonePrototype(parent) {
+ if (parent === null)
+ return null;
-},{"hyperscript-attribute-to-property":79}],81:[function(require,module,exports){
-'use strict';
+ var c = function () {};
+ c.prototype = parent;
+ return new c();
+};
-var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
-var _createClass = require('@babel/runtime/helpers/createClass');
+// private utility functions
-function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
+function __objToStr(o) {
+ return Object.prototype.toString.call(o);
+}
+clone.__objToStr = __objToStr;
-var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
-var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
+function __isDate(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object Date]';
+}
+clone.__isDate = __isDate;
-var arr = [];
-var each = arr.forEach;
-var slice = arr.slice;
-function defaults(obj) {
- each.call(slice.call(arguments, 1), function (source) {
- if (source) {
- for (var prop in source) {
- if (obj[prop] === undefined) obj[prop] = source[prop];
- }
- }
- });
- return obj;
+function __isArray(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
+clone.__isArray = __isArray;
-// eslint-disable-next-line no-control-regex
-var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
+function __isRegExp(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
+}
+clone.__isRegExp = __isRegExp;
-var serializeCookie = function serializeCookie(name, val, options) {
- var opt = options || {};
- opt.path = opt.path || '/';
- var value = encodeURIComponent(val);
- var str = name + '=' + value;
+function __getRegExpFlags(re) {
+ var flags = '';
+ if (re.global) flags += 'g';
+ if (re.ignoreCase) flags += 'i';
+ if (re.multiline) flags += 'm';
+ return flags;
+}
+clone.__getRegExpFlags = __getRegExpFlags;
- if (opt.maxAge > 0) {
- var maxAge = opt.maxAge - 0;
- if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
- str += '; Max-Age=' + Math.floor(maxAge);
- }
+return clone;
+})();
- if (opt.domain) {
- if (!fieldContentRegExp.test(opt.domain)) {
- throw new TypeError('option domain is invalid');
- }
+if (typeof module === 'object' && module.exports) {
+ module.exports = clone;
+}
- str += '; Domain=' + opt.domain;
- }
+}).call(this)}).call(this,require("buffer").Buffer)
+},{"buffer":44}],62:[function(require,module,exports){
+'use strict'
- if (opt.path) {
- if (!fieldContentRegExp.test(opt.path)) {
- throw new TypeError('option path is invalid');
- }
+module.exports = ready
- str += '; Path=' + opt.path;
+function ready (callback) {
+ if (typeof document === 'undefined') {
+ throw new Error('document-ready only runs in the browser')
}
-
- if (opt.expires) {
- if (typeof opt.expires.toUTCString !== 'function') {
- throw new TypeError('option expires is invalid');
- }
-
- str += '; Expires=' + opt.expires.toUTCString();
+ var state = document.readyState
+ if (state === 'complete' || state === 'interactive') {
+ return setTimeout(callback, 0)
}
- if (opt.httpOnly) str += '; HttpOnly';
- if (opt.secure) str += '; Secure';
-
- if (opt.sameSite) {
- var sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
-
- switch (sameSite) {
- case true:
- str += '; SameSite=Strict';
- break;
-
- case 'lax':
- str += '; SameSite=Lax';
- break;
+ document.addEventListener('DOMContentLoaded', function onLoad () {
+ callback()
+ })
+}
- case 'strict':
- str += '; SameSite=Strict';
- break;
+},{}],63:[function(require,module,exports){
+module.exports = stringify
+stringify.default = stringify
+stringify.stable = deterministicStringify
+stringify.stableStringify = deterministicStringify
- case 'none':
- str += '; SameSite=None';
- break;
+var arr = []
+var replacerStack = []
- default:
- throw new TypeError('option sameSite is invalid');
+// Regular stringify
+function stringify (obj, replacer, spacer) {
+ decirc(obj, '', [], undefined)
+ var res
+ if (replacerStack.length === 0) {
+ res = JSON.stringify(obj, replacer, spacer)
+ } else {
+ res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)
+ }
+ while (arr.length !== 0) {
+ var part = arr.pop()
+ if (part.length === 4) {
+ Object.defineProperty(part[0], part[1], part[3])
+ } else {
+ part[0][part[1]] = part[2]
}
}
-
- return str;
-};
-
-var cookie = {
- create: function create(name, value, minutes, domain) {
- var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
- path: '/',
- sameSite: 'strict'
- };
-
- if (minutes) {
- cookieOptions.expires = new Date();
- cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1000);
+ return res
+}
+function decirc (val, k, stack, parent) {
+ var i
+ if (typeof val === 'object' && val !== null) {
+ for (i = 0; i < stack.length; i++) {
+ if (stack[i] === val) {
+ var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
+ if (propertyDescriptor.get !== undefined) {
+ if (propertyDescriptor.configurable) {
+ Object.defineProperty(parent, k, { value: '[Circular]' })
+ arr.push([parent, k, val, propertyDescriptor])
+ } else {
+ replacerStack.push([val, k])
+ }
+ } else {
+ parent[k] = '[Circular]'
+ arr.push([parent, k, val])
+ }
+ return
+ }
}
-
- if (domain) cookieOptions.domain = domain;
- document.cookie = serializeCookie(name, encodeURIComponent(value), cookieOptions);
- },
- read: function read(name) {
- var nameEQ = name + '=';
- var ca = document.cookie.split(';');
-
- for (var i = 0; i < ca.length; i++) {
- var c = ca[i];
-
- while (c.charAt(0) === ' ') {
- c = c.substring(1, c.length);
+ stack.push(val)
+ // Optimize for Arrays. Big arrays could kill the performance otherwise!
+ if (Array.isArray(val)) {
+ for (i = 0; i < val.length; i++) {
+ decirc(val[i], i, stack, val)
+ }
+ } else {
+ var keys = Object.keys(val)
+ for (i = 0; i < keys.length; i++) {
+ var key = keys[i]
+ decirc(val[key], key, stack, val)
}
-
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
-
- return null;
- },
- remove: function remove(name) {
- this.create(name, '', -1);
+ stack.pop()
}
-};
-var cookie$1 = {
- name: 'cookie',
- lookup: function lookup(options) {
- var found;
+}
- if (options.lookupCookie && typeof document !== 'undefined') {
- var c = cookie.read(options.lookupCookie);
- if (c) found = c;
- }
+// Stable-stringify
+function compareFunction (a, b) {
+ if (a < b) {
+ return -1
+ }
+ if (a > b) {
+ return 1
+ }
+ return 0
+}
- return found;
- },
- cacheUserLanguage: function cacheUserLanguage(lng, options) {
- if (options.lookupCookie && typeof document !== 'undefined') {
- cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
+function deterministicStringify (obj, replacer, spacer) {
+ var tmp = deterministicDecirc(obj, '', [], undefined) || obj
+ var res
+ if (replacerStack.length === 0) {
+ res = JSON.stringify(tmp, replacer, spacer)
+ } else {
+ res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
+ }
+ while (arr.length !== 0) {
+ var part = arr.pop()
+ if (part.length === 4) {
+ Object.defineProperty(part[0], part[1], part[3])
+ } else {
+ part[0][part[1]] = part[2]
}
}
-};
-
-var querystring = {
- name: 'querystring',
- lookup: function lookup(options) {
- var found;
-
- if (typeof window !== 'undefined') {
- var query = window.location.search.substring(1);
- var params = query.split('&');
-
- for (var i = 0; i < params.length; i++) {
- var pos = params[i].indexOf('=');
-
- if (pos > 0) {
- var key = params[i].substring(0, pos);
+ return res
+}
- if (key === options.lookupQuerystring) {
- found = params[i].substring(pos + 1);
+function deterministicDecirc (val, k, stack, parent) {
+ var i
+ if (typeof val === 'object' && val !== null) {
+ for (i = 0; i < stack.length; i++) {
+ if (stack[i] === val) {
+ var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
+ if (propertyDescriptor.get !== undefined) {
+ if (propertyDescriptor.configurable) {
+ Object.defineProperty(parent, k, { value: '[Circular]' })
+ arr.push([parent, k, val, propertyDescriptor])
+ } else {
+ replacerStack.push([val, k])
}
+ } else {
+ parent[k] = '[Circular]'
+ arr.push([parent, k, val])
}
+ return
+ }
+ }
+ if (typeof val.toJSON === 'function') {
+ return
+ }
+ stack.push(val)
+ // Optimize for Arrays. Big arrays could kill the performance otherwise!
+ if (Array.isArray(val)) {
+ for (i = 0; i < val.length; i++) {
+ deterministicDecirc(val[i], i, stack, val)
+ }
+ } else {
+ // Create a temporary object in the required way
+ var tmp = {}
+ var keys = Object.keys(val).sort(compareFunction)
+ for (i = 0; i < keys.length; i++) {
+ var key = keys[i]
+ deterministicDecirc(val[key], key, stack, val)
+ tmp[key] = val[key]
+ }
+ if (parent !== undefined) {
+ arr.push([parent, k, val])
+ parent[k] = tmp
+ } else {
+ return tmp
}
}
+ stack.pop()
+ }
+}
- return found;
+// wraps replacer function to handle values we couldn't replace
+// and mark them as [Circular]
+function replaceGetterValues (replacer) {
+ replacer = replacer !== undefined ? replacer : function (k, v) { return v }
+ return function (key, val) {
+ if (replacerStack.length > 0) {
+ for (var i = 0; i < replacerStack.length; i++) {
+ var part = replacerStack[i]
+ if (part[1] === key && part[0] === val) {
+ val = '[Circular]'
+ replacerStack.splice(i, 1)
+ break
+ }
+ }
+ }
+ return replacer.call(this, key, val)
}
-};
+}
-var hasLocalStorageSupport = null;
+},{}],64:[function(require,module,exports){
+(function (global){(function (){
+var topLevel = typeof global !== 'undefined' ? global :
+ typeof window !== 'undefined' ? window : {}
+var minDoc = require('min-document');
-var localStorageAvailable = function localStorageAvailable() {
- if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
+var doccy;
- try {
- hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
- var testKey = 'i18next.translate.boo';
- window.localStorage.setItem(testKey, 'foo');
- window.localStorage.removeItem(testKey);
- } catch (e) {
- hasLocalStorageSupport = false;
- }
+if (typeof document !== 'undefined') {
+ doccy = document;
+} else {
+ doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
- return hasLocalStorageSupport;
-};
+ if (!doccy) {
+ doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
+ }
+}
-var localStorage = {
- name: 'localStorage',
- lookup: function lookup(options) {
- var found;
+module.exports = doccy;
- if (options.lookupLocalStorage && localStorageAvailable()) {
- var lng = window.localStorage.getItem(options.lookupLocalStorage);
- if (lng) found = lng;
- }
+}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"min-document":42}],65:[function(require,module,exports){
+(function (global){(function (){
+var win;
- return found;
- },
- cacheUserLanguage: function cacheUserLanguage(lng, options) {
- if (options.lookupLocalStorage && localStorageAvailable()) {
- window.localStorage.setItem(options.lookupLocalStorage, lng);
- }
- }
-};
+if (typeof window !== "undefined") {
+ win = window;
+} else if (typeof global !== "undefined") {
+ win = global;
+} else if (typeof self !== "undefined"){
+ win = self;
+} else {
+ win = {};
+}
-var hasSessionStorageSupport = null;
+module.exports = win;
-var sessionStorageAvailable = function sessionStorageAvailable() {
- if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
+}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],66:[function(require,module,exports){
+const Output = require('./src/output.js')
+const loop = require('raf-loop')
+const Source = require('./src/hydra-source.js')
+const Mouse = require('./src/lib/mouse.js')()
+const Audio = require('./src/lib/audio.js')
+const VidRecorder = require('./src/lib/video-recorder.js')
+const ArrayUtils = require('./src/lib/array-utils.js')
+const Sandbox = require('./src/eval-sandbox.js')
- try {
- hasSessionStorageSupport = window !== 'undefined' && window.sessionStorage !== null;
- var testKey = 'i18next.translate.boo';
- window.sessionStorage.setItem(testKey, 'foo');
- window.sessionStorage.removeItem(testKey);
- } catch (e) {
- hasSessionStorageSupport = false;
- }
+const Generator = require('./src/generator-factory.js')
- return hasSessionStorageSupport;
-};
+// to do: add ability to pass in certain uniforms and transforms
+class HydraRenderer {
-var sessionStorage = {
- name: 'sessionStorage',
- lookup: function lookup(options) {
- var found;
+ constructor ({
+ pb = null,
+ width = 1280,
+ height = 720,
+ numSources = 4,
+ numOutputs = 4,
+ makeGlobal = true,
+ autoLoop = true,
+ detectAudio = true,
+ enableStreamCapture = true,
+ canvas,
+ precision,
+ extendTransforms = {} // add your own functions on init
+ } = {}) {
- if (options.lookupSessionStorage && sessionStorageAvailable()) {
- var lng = window.sessionStorage.getItem(options.lookupSessionStorage);
- if (lng) found = lng;
- }
+ ArrayUtils.init()
- return found;
- },
- cacheUserLanguage: function cacheUserLanguage(lng, options) {
- if (options.lookupSessionStorage && sessionStorageAvailable()) {
- window.sessionStorage.setItem(options.lookupSessionStorage, lng);
- }
- }
-};
+ this.pb = pb
-var navigator$1 = {
- name: 'navigator',
- lookup: function lookup(options) {
- var found = [];
+ this.width = width
+ this.height = height
+ this.renderAll = false
+ this.detectAudio = detectAudio
- if (typeof navigator !== 'undefined') {
- if (navigator.languages) {
- // chrome only; not an array, so can't use .push.apply instead of iterating
- for (var i = 0; i < navigator.languages.length; i++) {
- found.push(navigator.languages[i]);
- }
- }
+ this._initCanvas(canvas)
- if (navigator.userLanguage) {
- found.push(navigator.userLanguage);
- }
- if (navigator.language) {
- found.push(navigator.language);
- }
+ // object that contains all properties that will be made available on the global context and during local evaluation
+ this.synth = {
+ time: 0,
+ bpm: 30,
+ width: this.width,
+ height: this.height,
+ fps: undefined,
+ stats: {
+ fps: 0
+ },
+ speed: 1,
+ mouse: Mouse,
+ render: this._render.bind(this),
+ setResolution: this.setResolution.bind(this),
+ update: (dt) => {},// user defined update function
+ hush: this.hush.bind(this)
}
- return found.length > 0 ? found : undefined;
- }
-};
+ if (makeGlobal) window.loadScript = this.loadScript
-var htmlTag = {
- name: 'htmlTag',
- lookup: function lookup(options) {
- var found;
- var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
- if (htmlTag && typeof htmlTag.getAttribute === 'function') {
- found = htmlTag.getAttribute('lang');
+ this.timeSinceLastUpdate = 0
+ this._time = 0 // for internal use, only to use for deciding when to render frames
+
+ // only allow valid precision options
+ let precisionOptions = ['lowp','mediump','highp']
+ if(precision && precisionOptions.includes(precision.toLowerCase())) {
+ this.precision = precision.toLowerCase()
+ //
+ // if(!precisionValid){
+ // console.warn('[hydra-synth warning]\nConstructor was provided an invalid floating point precision value of "' + precision + '". Using default value of "mediump" instead.')
+ // }
+ } else {
+ let isIOS =
+ (/iPad|iPhone|iPod/.test(navigator.platform) ||
+ (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
+ !window.MSStream;
+ this.precision = isIOS ? 'highp' : 'mediump'
}
- return found;
- }
-};
-var path = {
- name: 'path',
- lookup: function lookup(options) {
- var found;
- if (typeof window !== 'undefined') {
- var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
+ this.extendTransforms = extendTransforms
- if (language instanceof Array) {
- if (typeof options.lookupFromPathIndex === 'number') {
- if (typeof language[options.lookupFromPathIndex] !== 'string') {
- return undefined;
- }
+ // boolean to store when to save screenshot
+ this.saveFrame = false
- found = language[options.lookupFromPathIndex].replace('/', '');
- } else {
- found = language[0].replace('/', '');
- }
- }
- }
+ // if stream capture is enabled, this object contains the capture stream
+ this.captureStream = null
- return found;
- }
-};
+ this.generator = undefined
-var subdomain = {
- name: 'subdomain',
- lookup: function lookup(options) {
- var found;
+ this._initRegl()
+ this._initOutputs(numOutputs)
+ this._initSources(numSources)
+ this._generateGlslTransforms()
- if (typeof window !== 'undefined') {
- var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
+ this.synth.screencap = () => {
+ this.saveFrame = true
+ }
- if (language instanceof Array) {
- if (typeof options.lookupFromSubdomainIndex === 'number') {
- found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
- } else {
- found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
- }
+ if (enableStreamCapture) {
+ try {
+ this.captureStream = this.canvas.captureStream(25)
+ // to do: enable capture stream of specific sources and outputs
+ this.synth.vidRecorder = new VidRecorder(this.captureStream)
+ } catch (e) {
+ console.warn('[hydra-synth warning]\nnew MediaSource() is not currently supported on iOS.')
+ console.error(e)
}
}
- return found;
- }
-};
+ if(detectAudio) this._initAudio()
-function getDefaults() {
- return {
- order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
- lookupQuerystring: 'lng',
- lookupCookie: 'i18next',
- lookupLocalStorage: 'i18nextLng',
- lookupSessionStorage: 'i18nextLng',
- // cache user language
- caches: ['localStorage'],
- excludeCacheFor: ['cimode'] //cookieMinutes: 10,
- //cookieDomain: 'myDomain'
+ if(autoLoop) loop(this.tick.bind(this)).start()
- };
-}
+ // final argument is properties that the user can set, all others are treated as read-only
+ this.sandbox = new Sandbox(this.synth, makeGlobal, ['speed', 'update', 'bpm', 'fps'])
+ }
-var Browser = /*#__PURE__*/function () {
- function Browser(services) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ eval(code) {
+ this.sandbox.eval(code)
+ }
- _classCallCheck__default["default"](this, Browser);
+ getScreenImage(callback) {
+ this.imageCallback = callback
+ this.saveFrame = true
+ }
- this.type = 'languageDetector';
- this.detectors = {};
- this.init(services, options);
+ hush() {
+ this.s.forEach((source) => {
+ source.clear()
+ })
+ this.o.forEach((output) => {
+ this.synth.solid(1, 1, 1, 0).out(output)
+ })
}
- _createClass__default["default"](Browser, [{
- key: "init",
- value: function init(services) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- this.services = services;
- this.options = defaults(options, this.options || {}, getDefaults()); // backwards compatibility
+ loadScript(url = "") {
+ const p = new Promise((res, rej) => {
+ var script = document.createElement("script");
+ script.onload = function () {
+ console.log(`loaded script ${url}`);
+ res();
+ };
+ script.onerror = (err) => {
+ console.log(`error loading script ${url}`, "log-error");
+ res()
+ };
+ script.src = url;
+ document.head.appendChild(script);
+ });
+ return p;
+ }
- if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
- this.i18nOptions = i18nOptions;
- this.addDetector(cookie$1);
- this.addDetector(querystring);
- this.addDetector(localStorage);
- this.addDetector(sessionStorage);
- this.addDetector(navigator$1);
- this.addDetector(htmlTag);
- this.addDetector(path);
- this.addDetector(subdomain);
- }
- }, {
- key: "addDetector",
- value: function addDetector(detector) {
- this.detectors[detector.name] = detector;
- }
- }, {
- key: "detect",
- value: function detect(detectionOrder) {
- var _this = this;
+ setResolution(width, height) {
+ // console.log(width, height)
+ this.canvas.width = width
+ this.canvas.height = height
+ this.width = width
+ this.height = height
+ this.o.forEach((output) => {
+ output.resize(width, height)
+ })
+ this.s.forEach((source) => {
+ source.resize(width, height)
+ })
+ this.regl._refresh()
+ console.log(this.canvas.width)
+ }
- if (!detectionOrder) detectionOrder = this.options.order;
- var detected = [];
- detectionOrder.forEach(function (detectorName) {
- if (_this.detectors[detectorName]) {
- var lookup = _this.detectors[detectorName].lookup(_this.options);
+ canvasToImage (callback) {
+ const a = document.createElement('a')
+ a.style.display = 'none'
- if (lookup && typeof lookup === 'string') lookup = [lookup];
- if (lookup) detected = detected.concat(lookup);
+ let d = new Date()
+ a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.png`
+ document.body.appendChild(a)
+ var self = this
+ this.canvas.toBlob( (blob) => {
+ if(self.imageCallback){
+ self.imageCallback(blob)
+ delete self.imageCallback
+ } else {
+ a.href = URL.createObjectURL(blob)
+ console.log(a.href)
+ a.click()
}
- });
- if (this.services.languageUtils.getBestMatchFromCodes) return detected; // new i18next v19.5.0
+ }, 'image/png')
+ setTimeout(() => {
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(a.href);
+ }, 300);
+ }
- return detected.length > 0 ? detected[0] : null; // a little backward compatibility
- }
- }, {
- key: "cacheUserLanguage",
- value: function cacheUserLanguage(lng, caches) {
- var _this2 = this;
+ _initAudio () {
+ const that = this
+ this.synth.a = new Audio({
+ numBins: 4,
+ // changeListener: ({audio}) => {
+ // that.a = audio.bins.map((_, index) =>
+ // (scale = 1, offset = 0) => () => (audio.fft[index] * scale + offset)
+ // )
+ //
+ // if (that.makeGlobal) {
+ // that.a.forEach((a, index) => {
+ // const aname = `a${index}`
+ // window[aname] = a
+ // })
+ // }
+ // }
+ })
+ }
- if (!caches) caches = this.options.caches;
- if (!caches) return;
- if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
- caches.forEach(function (cacheName) {
- if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
- });
+ // create main output canvas and add to screen
+ _initCanvas (canvas) {
+ if (canvas) {
+ this.canvas = canvas
+ this.width = canvas.width
+ this.height = canvas.height
+ } else {
+ this.canvas = document.createElement('canvas')
+ this.canvas.width = this.width
+ this.canvas.height = this.height
+ this.canvas.style.width = '100%'
+ this.canvas.style.height = '100%'
+ this.canvas.style.imageRendering = 'pixelated'
+ document.body.appendChild(this.canvas)
}
- }]);
+ }
- return Browser;
-}();
+ _initRegl () {
+ this.regl = require('regl')({
+ // profile: true,
+ canvas: this.canvas,
+ pixelRatio: 1//,
+ // extensions: [
+ // 'oes_texture_half_float',
+ // 'oes_texture_half_float_linear'
+ // ],
+ // optionalExtensions: [
+ // 'oes_texture_float',
+ // 'oes_texture_float_linear'
+ //]
+ })
-Browser.type = 'languageDetector';
+ // This clears the color buffer to black and the depth buffer to 1
+ this.regl.clear({
+ color: [0, 0, 0, 1]
+ })
-module.exports = Browser;
+ this.renderAll = this.regl({
+ frag: `
+ precision ${this.precision} float;
+ varying vec2 uv;
+ uniform sampler2D tex0;
+ uniform sampler2D tex1;
+ uniform sampler2D tex2;
+ uniform sampler2D tex3;
-},{"@babel/runtime/helpers/classCallCheck":32,"@babel/runtime/helpers/createClass":33}],82:[function(require,module,exports){
-'use strict';
+ void main () {
+ vec2 st = vec2(1.0 - uv.x, uv.y);
+ st*= vec2(2);
+ vec2 q = floor(st).xy*(vec2(2.0, 1.0));
+ int quad = int(q.x) + int(q.y);
+ st.x += step(1., mod(st.y,2.0));
+ st.y += step(1., mod(st.x,2.0));
+ st = fract(st);
+ if(quad==0){
+ gl_FragColor = texture2D(tex0, st);
+ } else if(quad==1){
+ gl_FragColor = texture2D(tex1, st);
+ } else if (quad==2){
+ gl_FragColor = texture2D(tex2, st);
+ } else {
+ gl_FragColor = texture2D(tex3, st);
+ }
-var _typeof = require('@babel/runtime/helpers/typeof');
-var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
-var _createClass = require('@babel/runtime/helpers/createClass');
-var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
-var _inherits = require('@babel/runtime/helpers/inherits');
-var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
-var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
-var _defineProperty = require('@babel/runtime/helpers/defineProperty');
-var _toArray = require('@babel/runtime/helpers/toArray');
+ }
+ `,
+ vert: `
+ precision ${this.precision} float;
+ attribute vec2 position;
+ varying vec2 uv;
-function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
+ void main () {
+ uv = position;
+ gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
+ }`,
+ attributes: {
+ position: [
+ [-2, 0],
+ [0, -2],
+ [2, 2]
+ ]
+ },
+ uniforms: {
+ tex0: this.regl.prop('tex0'),
+ tex1: this.regl.prop('tex1'),
+ tex2: this.regl.prop('tex2'),
+ tex3: this.regl.prop('tex3')
+ },
+ count: 3,
+ depth: { enable: false }
+ })
-var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
-var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
-var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
-var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
-var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
-var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
-var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
-var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
-var _toArray__default = /*#__PURE__*/_interopDefaultLegacy(_toArray);
+ this.renderFbo = this.regl({
+ frag: `
+ precision ${this.precision} float;
+ varying vec2 uv;
+ uniform vec2 resolution;
+ uniform sampler2D tex0;
+
+ void main () {
+ gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y));
+ }
+ `,
+ vert: `
+ precision ${this.precision} float;
+ attribute vec2 position;
+ varying vec2 uv;
-function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
+ void main () {
+ uv = position;
+ gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
+ }`,
+ attributes: {
+ position: [
+ [-2, 0],
+ [0, -2],
+ [2, 2]
+ ]
+ },
+ uniforms: {
+ tex0: this.regl.prop('tex0'),
+ resolution: this.regl.prop('resolution')
+ },
+ count: 3,
+ depth: { enable: false }
+ })
+ }
-function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+ _initOutputs (numOutputs) {
+ const self = this
+ this.o = (Array(numOutputs)).fill().map((el, index) => {
+ var o = new Output({
+ regl: this.regl,
+ width: this.width,
+ height: this.height,
+ precision: this.precision,
+ label: `o${index}`
+ })
+ // o.render()
+ o.id = index
+ self.synth['o'+index] = o
+ return o
+ })
-var consoleLogger = {
- type: 'logger',
- log: function log(args) {
- this.output('log', args);
- },
- warn: function warn(args) {
- this.output('warn', args);
- },
- error: function error(args) {
- this.output('error', args);
- },
- output: function output(type, args) {
- if (console && console[type]) console[type].apply(console, args);
+ // set default output
+ this.output = this.o[0]
}
-};
-
-var Logger = function () {
- function Logger(concreteLogger) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- _classCallCheck__default['default'](this, Logger);
+ _initSources (numSources) {
+ this.s = []
+ for(var i = 0; i < numSources; i++) {
+ this.createSource(i)
+ }
+ }
- this.init(concreteLogger, options);
+ createSource (i) {
+ let s = new Source({regl: this.regl, pb: this.pb, width: this.width, height: this.height, label: `s${i}`})
+ this.synth['s' + this.s.length] = s
+ this.s.push(s)
+ return s
}
- _createClass__default['default'](Logger, [{
- key: "init",
- value: function init(concreteLogger) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- this.prefix = options.prefix || 'i18next:';
- this.logger = concreteLogger || consoleLogger;
- this.options = options;
- this.debug = options.debug;
- }
- }, {
- key: "setDebug",
- value: function setDebug(bool) {
- this.debug = bool;
- }
- }, {
- key: "log",
- value: function log() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
+ _generateGlslTransforms () {
+ var self = this
+ this.generator = new Generator({
+ defaultOutput: this.o[0],
+ defaultUniforms: this.o[0].uniforms,
+ extendTransforms: this.extendTransforms,
+ changeListener: ({type, method, synth}) => {
+ if (type === 'add') {
+ self.synth[method] = synth.generators[method]
+ if(self.sandbox) self.sandbox.add(method)
+ } else if (type === 'remove') {
+ // what to do here? dangerously deleting window methods
+ //delete window[method]
+ }
+ // }
}
+ })
+ this.synth.setFunction = this.generator.setFunction.bind(this.generator)
+ }
- return this.forward(args, 'log', '', true);
+ _render (output) {
+ if (output) {
+ this.output = output
+ this.isRenderingAll = false
+ } else {
+ this.isRenderingAll = true
}
- }, {
- key: "warn",
- value: function warn() {
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
+ }
- return this.forward(args, 'warn', '', true);
+ // dt in ms
+ tick (dt, uniforms) {
+ this.sandbox.tick()
+ if(this.detectAudio === true) this.synth.a.tick()
+ // let updateInterval = 1000/this.synth.fps // ms
+ if(this.synth.update) {
+ try { this.synth.update(dt) } catch (e) { console.log(error) }
}
- }, {
- key: "error",
- value: function error() {
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- args[_key3] = arguments[_key3];
- }
- return this.forward(args, 'error', '');
- }
- }, {
- key: "deprecate",
- value: function deprecate() {
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
- args[_key4] = arguments[_key4];
+ this.sandbox.set('time', this.synth.time += dt * 0.001 * this.synth.speed)
+ this.timeSinceLastUpdate += dt
+ if(!this.synth.fps || this.timeSinceLastUpdate >= 1000/this.synth.fps) {
+ // console.log(1000/this.timeSinceLastUpdate)
+ this.synth.stats.fps = Math.ceil(1000/this.timeSinceLastUpdate)
+ // console.log(this.synth.speed, this.synth.time)
+ for (let i = 0; i < this.s.length; i++) {
+ this.s[i].tick(this.synth.time)
+ }
+ // console.log(this.canvas.width, this.canvas.height)
+ for (let i = 0; i < this.o.length; i++) {
+ this.o[i].tick({
+ time: this.synth.time,
+ mouse: this.synth.mouse,
+ bpm: this.synth.bpm,
+ resolution: [this.canvas.width, this.canvas.height]
+ })
}
+ if (this.isRenderingAll) {
+ this.renderAll({
+ tex0: this.o[0].getCurrent(),
+ tex1: this.o[1].getCurrent(),
+ tex2: this.o[2].getCurrent(),
+ tex3: this.o[3].getCurrent(),
+ resolution: [this.canvas.width, this.canvas.height]
+ })
+ } else {
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
- }
- }, {
- key: "forward",
- value: function forward(args, lvl, prefix, debugOnly) {
- if (debugOnly && !this.debug) return null;
- if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
- return this.logger[lvl](args);
+ this.renderFbo({
+ tex0: this.output.getCurrent(),
+ resolution: [this.canvas.width, this.canvas.height]
+ })
+ }
+ this.timeSinceLastUpdate = 0
}
- }, {
- key: "create",
- value: function create(moduleName) {
- return new Logger(this.logger, _objectSpread(_objectSpread({}, {
- prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
- }), this.options));
+ if(this.saveFrame === true) {
+ this.canvasToImage()
+ this.saveFrame = false
}
- }]);
-
- return Logger;
-}();
+ // this.regl.poll()
+ }
-var baseLogger = new Logger();
-var EventEmitter = function () {
- function EventEmitter() {
- _classCallCheck__default['default'](this, EventEmitter);
+}
- this.observers = {};
- }
+module.exports = HydraRenderer
- _createClass__default['default'](EventEmitter, [{
- key: "on",
- value: function on(events, listener) {
- var _this = this;
+},{"./src/eval-sandbox.js":68,"./src/generator-factory.js":71,"./src/hydra-source.js":75,"./src/lib/array-utils.js":76,"./src/lib/audio.js":77,"./src/lib/mouse.js":80,"./src/lib/video-recorder.js":83,"./src/output.js":85,"raf-loop":122,"regl":124}],67:[function(require,module,exports){
+const Synth = require('./hydra-synth.js')
+//const ShaderGenerator = require('./shader-generator.js')
- events.split(' ').forEach(function (event) {
- _this.observers[event] = _this.observers[event] || [];
+module.exports = Synth
- _this.observers[event].push(listener);
- });
- return this;
- }
- }, {
- key: "off",
- value: function off(event, listener) {
- if (!this.observers[event]) return;
+},{"./hydra-synth.js":66}],68:[function(require,module,exports){
+// handles code evaluation and attaching relevant objects to global and evaluation contexts
- if (!listener) {
- delete this.observers[event];
- return;
- }
+const Sandbox = require('./lib/sandbox.js')
+const ArrayUtils = require('./lib/array-utils.js')
- this.observers[event] = this.observers[event].filter(function (l) {
- return l !== listener;
- });
- }
- }, {
- key: "emit",
- value: function emit(event) {
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
+class EvalSandbox {
+ constructor(parent, makeGlobal, userProps = []) {
+ this.makeGlobal = makeGlobal
+ this.sandbox = Sandbox(parent)
+ this.parent = parent
+ var properties = Object.keys(parent)
+ properties.forEach((property) => this.add(property))
+ this.userProps = userProps
+ }
- if (this.observers[event]) {
- var cloned = [].concat(this.observers[event]);
- cloned.forEach(function (observer) {
- observer.apply(void 0, args);
- });
- }
+ add(name) {
+ if(this.makeGlobal) window[name] = this.parent[name]
+ this.sandbox.addToContext(name, `parent.${name}`)
+ }
- if (this.observers['*']) {
- var _cloned = [].concat(this.observers['*']);
+// sets on window as well as synth object if global (not needed for objects, which can be set directly)
- _cloned.forEach(function (observer) {
- observer.apply(observer, [event].concat(args));
- });
- }
+ set(property, value) {
+ if(this.makeGlobal) {
+ window[property] = value
}
- }]);
-
- return EventEmitter;
-}();
+ this.parent[property] = value
+ }
-function defer() {
- var res;
- var rej;
- var promise = new Promise(function (resolve, reject) {
- res = resolve;
- rej = reject;
- });
- promise.resolve = res;
- promise.reject = rej;
- return promise;
-}
-function makeString(object) {
- if (object == null) return '';
- return '' + object;
-}
-function copy(a, s, t) {
- a.forEach(function (m) {
- if (s[m]) t[m] = s[m];
- });
-}
+ tick() {
+ if(this.makeGlobal) {
+ this.userProps.forEach((property) => {
+ this.parent[property] = window[property]
+ })
+ // this.parent.speed = window.speed
+ } else {
-function getLastOfPath(object, path, Empty) {
- function cleanKey(key) {
- return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
+ }
}
- function canNotTraverseDeeper() {
- return !object || typeof object === 'string';
+ eval(code) {
+ this.sandbox.eval(code)
}
+}
- var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
+module.exports = EvalSandbox
- while (stack.length > 1) {
- if (canNotTraverseDeeper()) return {};
- var key = cleanKey(stack.shift());
- if (!object[key] && Empty) object[key] = new Empty();
+},{"./lib/array-utils.js":76,"./lib/sandbox.js":81}],69:[function(require,module,exports){
+const arrayUtils = require('./lib/array-utils.js')
- if (Object.prototype.hasOwnProperty.call(object, key)) {
- object = object[key];
+// [WIP] how to treat different dimensions (?)
+const DEFAULT_CONVERSIONS = {
+ float: {
+ 'vec4': { name: 'sum', args: [[1, 1, 1, 1]] },
+ 'vec2': { name: 'sum', args: [[1, 1]] }
+ }
+}
+
+function fillArrayWithDefaults(arr, len) {
+ // fill the array with default values if it's too short
+ while (arr.length < len) {
+ if (arr.length === 3) { // push a 1 as the default for .a in vec4
+ arr.push(1.0)
} else {
- object = {};
+ arr.push(0.0)
}
}
+ return arr.slice(0, len)
+}
- if (canNotTraverseDeeper()) return {};
- return {
- obj: object,
- k: cleanKey(stack.shift())
- };
+const ensure_decimal_dot = (val) => {
+ val = val.toString()
+ if (val.indexOf('.') < 0) {
+ val += '.'
+ }
+ return val
}
-function setPath(object, path, newValue) {
- var _getLastOfPath = getLastOfPath(object, path, Object),
- obj = _getLastOfPath.obj,
- k = _getLastOfPath.k;
- obj[k] = newValue;
-}
-function pushPath(object, path, newValue, concat) {
- var _getLastOfPath2 = getLastOfPath(object, path, Object),
- obj = _getLastOfPath2.obj,
- k = _getLastOfPath2.k;
- obj[k] = obj[k] || [];
- if (concat) obj[k] = obj[k].concat(newValue);
- if (!concat) obj[k].push(newValue);
-}
-function getPath(object, path) {
- var _getLastOfPath3 = getLastOfPath(object, path),
- obj = _getLastOfPath3.obj,
- k = _getLastOfPath3.k;
+module.exports = function formatArguments(transform, startIndex, synthContext) {
+ const defaultArgs = transform.transform.inputs
+ const userArgs = transform.userArgs
+ const { generators } = transform.synth
+ const { src } = generators // depends on synth having src() function
+ return defaultArgs.map((input, index) => {
+ const typedArg = {
+ value: input.default,
+ type: input.type, //
+ isUniform: false,
+ name: input.name,
+ vecLen: 0
+ // generateGlsl: null // function for creating glsl
+ }
- if (!obj) return undefined;
- return obj[k];
-}
-function getPathWithDefaults(data, defaultData, key) {
- var value = getPath(data, key);
+ if (typedArg.type === 'float') typedArg.value = ensure_decimal_dot(input.default)
+ if (input.type.startsWith('vec')) {
+ try {
+ typedArg.vecLen = Number.parseInt(input.type.substr(3))
+ } catch (e) {
+ console.log(`Error determining length of vector input type ${input.type} (${input.name})`)
+ }
+ }
- if (value !== undefined) {
- return value;
- }
+ // if user has input something for this argument
+ if (userArgs.length > index) {
+ typedArg.value = userArgs[index]
+ // do something if a composite or transform
- return getPath(defaultData, key);
-}
-function deepExtend(target, source, overwrite) {
- for (var prop in source) {
- if (prop !== '__proto__' && prop !== 'constructor') {
- if (prop in target) {
- if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
- if (overwrite) target[prop] = source[prop];
- } else {
- deepExtend(target[prop], source[prop], overwrite);
+ if (typeof userArgs[index] === 'function') {
+ // if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar
+ // typedArg.value = (context, props, batchId) => (fillArrayWithDefaults(userArgs[index](props), typedArg.vecLen))
+ // } else {
+ typedArg.value = (context, props, batchId) => {
+ try {
+ return userArgs[index](props)
+ } catch (e) {
+ console.log('ERROR', e)
+ return input.default
+ }
}
- } else {
- target[prop] = source[prop];
+ // }
+
+ typedArg.isUniform = true
+ } else if (userArgs[index].constructor === Array) {
+ // if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar
+ // typedArg.isUniform = true
+ // typedArg.value = fillArrayWithDefaults(typedArg.value, typedArg.vecLen)
+ // } else {
+ // console.log("is Array")
+ typedArg.value = (context, props, batchId) => arrayUtils.getValue(userArgs[index])(props)
+ typedArg.isUniform = true
+ // }
}
}
- }
- return target;
-}
-function regexEscape(str) {
- return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
-}
-var _entityMap = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": ''',
- '/': '/'
-};
-function escape(data) {
- if (typeof data === 'string') {
- return data.replace(/[&<>"'\/]/g, function (s) {
- return _entityMap[s];
- });
- }
+ if (startIndex < 0) {
+ } else {
+ if (typedArg.value && typedArg.value.transforms) {
+ const final_transform = typedArg.value.transforms[typedArg.value.transforms.length - 1]
- return data;
+ if (final_transform.transform.glsl_return_type !== input.type) {
+ const defaults = DEFAULT_CONVERSIONS[input.type]
+ if (typeof defaults !== 'undefined') {
+ const default_def = defaults[final_transform.transform.glsl_return_type]
+ if (typeof default_def !== 'undefined') {
+ const { name, args } = default_def
+ typedArg.value = typedArg.value[name](...args)
+ }
+ }
+ }
+
+ typedArg.isUniform = false
+ } else if (typedArg.type === 'float' && typeof typedArg.value === 'number') {
+ typedArg.value = ensure_decimal_dot(typedArg.value)
+ } else if (typedArg.type.startsWith('vec') && typeof typedArg.value === 'object' && Array.isArray(typedArg.value)) {
+ typedArg.isUniform = false
+ typedArg.value = `${typedArg.type}(${typedArg.value.map(ensure_decimal_dot).join(', ')})`
+ } else if (input.type === 'sampler2D') {
+ // typedArg.tex = typedArg.value
+ var x = typedArg.value
+ typedArg.value = () => (x.getTexture())
+ typedArg.isUniform = true
+ } else {
+ // if passing in a texture reference, when function asks for vec4, convert to vec4
+ if (typedArg.value.getTexture && input.type === 'vec4') {
+ var x1 = typedArg.value
+ typedArg.value = src(x1)
+ typedArg.isUniform = false
+ }
+ }
+
+ // add tp uniform array if is a function that will pass in a different value on each render frame,
+ // or a texture/ external source
+
+ if (typedArg.isUniform) {
+ typedArg.name += startIndex
+ // shaderParams.uniforms.push(typedArg)
+ }
+ }
+ return typedArg
+ })
}
-var isIE10 = typeof window !== 'undefined' && window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
-var chars = [' ', ',', '?', '!', ';'];
-function looksLikeObjectPath(key, nsSeparator, keySeparator) {
- nsSeparator = nsSeparator || '';
- keySeparator = keySeparator || '';
- var possibleChars = chars.filter(function (c) {
- return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0;
- });
- if (possibleChars.length === 0) return true;
- var r = new RegExp("(".concat(possibleChars.map(function (c) {
- return c === '?' ? '\\?' : c;
- }).join('|'), ")"));
- var matched = !r.test(key);
- if (!matched) {
- var ki = key.indexOf(keySeparator);
- if (ki > 0 && !r.test(key.substring(0, ki))) {
- matched = true;
- }
- }
+},{"./lib/array-utils.js":76}],70:[function(require,module,exports){
+const formatArguments = require('./format-arguments.js')
- return matched;
-}
+// Add extra functionality to Array.prototype for generating sequences in time
+const arrayUtils = require('./lib/array-utils.js')
-function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
+// converts a tree of javascript functions to a shader
+module.exports = function (transforms) {
+ var shaderParams = {
+ uniforms: [], // list of uniforms used in shader
+ glslFunctions: [], // list of functions used in shader
+ fragColor: ''
+ }
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+ var gen = generateGlsl(transforms, shaderParams)('st')
+ shaderParams.fragColor = gen
+ // remove uniforms with duplicate names
+ let uniforms = {}
+ shaderParams.uniforms.forEach((uniform) => uniforms[uniform.name] = uniform)
+ shaderParams.uniforms = Object.values(uniforms)
+ return shaderParams
-function deepFind(obj, path) {
- var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
- if (!obj) return undefined;
- if (obj[path]) return obj[path];
- var paths = path.split(keySeparator);
- var current = obj;
+}
- for (var i = 0; i < paths.length; ++i) {
- if (!current) return undefined;
- if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
- return undefined;
- }
+// recursive function for generating shader string from object containing functions and user arguments. Order of functions in string depends on type of function
+// to do: improve variable names
+function generateGlsl (transforms, shaderParams) {
+ // transform function that outputs a shader string corresponding to gl_FragColor
+ var fragColor = () => ''
+ // var uniforms = []
+ // var glslFunctions = []
+ transforms.forEach((transform) => {
+ var inputs = formatArguments(transform, shaderParams.uniforms.length)
+ inputs.forEach((input) => {
+ if(input.isUniform) shaderParams.uniforms.push(input)
+ })
- if (current[paths[i]] === undefined) {
- var j = 2;
- var p = paths.slice(i, i + j).join(keySeparator);
- var mix = current[p];
+ // add new glsl function to running list of functions
+ if(!contains(transform, shaderParams.glslFunctions)) shaderParams.glslFunctions.push(transform)
- while (mix === undefined && paths.length > i + j) {
- j++;
- p = paths.slice(i, i + j).join(keySeparator);
- mix = current[p];
- }
+ // current function for generating frag color shader code
+ var f0 = fragColor
+ if (transform.transform.type === 'src') {
+ fragColor = (uv) => `${shaderString(uv, transform.name, inputs, shaderParams)}`
+ } else if (transform.transform.type === 'coord') {
+ fragColor = (uv) => `${f0(`${shaderString(uv, transform.name, inputs, shaderParams)}`)}`
+ } else if (transform.transform.type === 'color') {
+ fragColor = (uv) => `${shaderString(`${f0(uv)}`, transform.name, inputs, shaderParams)}`
+ } else if (transform.transform.type === 'combine') {
+ // combining two generated shader strings (i.e. for blend, mult, add funtions)
+ var f1 = inputs[0].value && inputs[0].value.transforms ?
+ (uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` :
+ (inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value)
+ fragColor = (uv) => `${shaderString(`${f0(uv)}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}`
+ } else if (transform.transform.type === 'combineCoord') {
+ // combining two generated shader strings (i.e. for modulate functions)
+ var f1 = inputs[0].value && inputs[0].value.transforms ?
+ (uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` :
+ (inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value)
+ fragColor = (uv) => `${f0(`${shaderString(`${uv}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}`)}`
- if (mix === undefined) return undefined;
- if (path.endsWith(p)) {
- if (typeof mix === 'string') return mix;
- if (p && typeof mix[p] === 'string') return mix[p];
- }
+ }
+ })
+// console.log(fragColor)
+ // break;
+ return fragColor
+}
- var joinedPath = paths.slice(i + j).join(keySeparator);
- if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
- return undefined;
+// assembles a shader string containing the arguments and the function name, i.e. 'osc(uv, frequency)'
+function shaderString (uv, method, inputs, shaderParams) {
+ const str = inputs.map((input) => {
+ if (input.isUniform) {
+ return input.name
+ } else if (input.value && input.value.transforms) {
+ // this by definition needs to be a generator, hence we start with 'st' as the initial value for generating the glsl fragment
+ return `${generateGlsl(input.value.transforms, shaderParams)('st')}`
}
+ return input.value
+ }).reduce((p, c) => `${p}, ${c}`, '')
- current = current[paths[i]];
- }
+ return `${method}(${uv}${str})`
+}
- return current;
+// merge two arrays and remove duplicates
+function mergeArrays (a, b) {
+ return a.concat(b.filter(function (item) {
+ return a.indexOf(item) < 0;
+ }))
}
-var ResourceStore = function (_EventEmitter) {
- _inherits__default['default'](ResourceStore, _EventEmitter);
+// check whether array
+function contains(object, arr) {
+ for(var i = 0; i < arr.length; i++){
+ if(object.name == arr[i].name) return true
+ }
+ return false
+}
- var _super = _createSuper(ResourceStore);
- function ResourceStore(data) {
- var _this;
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
- ns: ['translation'],
- defaultNS: 'translation'
- };
- _classCallCheck__default['default'](this, ResourceStore);
+},{"./format-arguments.js":69,"./lib/array-utils.js":76}],71:[function(require,module,exports){
+const GlslSource = require('./glsl-source.js')
- _this = _super.call(this);
+class GeneratorFactory {
+ constructor ({
+ defaultUniforms,
+ defaultOutput,
+ extendTransforms = [],
+ changeListener = (() => {})
+ } = {}
+ ) {
+ this.defaultOutput = defaultOutput
+ this.defaultUniforms = defaultUniforms
+ this.changeListener = changeListener
+ this.extendTransforms = extendTransforms
+ this.generators = {}
+ this.init()
+ }
+ init () {
+ this.glslTransforms = {}
+ this.generators = Object.entries(this.generators).reduce((prev, [method, transform]) => {
+ this.changeListener({type: 'remove', synth: this, method})
+ return prev
+ }, {})
- if (isIE10) {
- EventEmitter.call(_assertThisInitialized__default['default'](_this));
- }
+ this.sourceClass = (() => {
+ return class extends GlslSource {
+ }
+ })()
- _this.data = data || {};
- _this.options = options;
+ let functions = require('./glsl/glsl-functions.js')()
- if (_this.options.keySeparator === undefined) {
- _this.options.keySeparator = '.';
+ // add user definied transforms
+ if (Array.isArray(this.extendTransforms)) {
+ functions.concat(this.extendTransforms)
+ } else if (typeof this.extendTransforms === 'object' && this.extendTransforms.type) {
+ functions.push(this.extendTransforms)
}
- if (_this.options.ignoreJSONStructure === undefined) {
- _this.options.ignoreJSONStructure = true;
+ return functions.map((transform) => this.setFunction(transform))
+ }
+
+ _addMethod (method, transform) {
+ const self = this
+ this.glslTransforms[method] = transform
+ if (transform.type === 'src') {
+ const func = (...args) => new this.sourceClass({
+ name: method,
+ transform: transform,
+ userArgs: args,
+ defaultOutput: this.defaultOutput,
+ defaultUniforms: this.defaultUniforms,
+ synth: self
+ })
+ this.generators[method] = func
+ this.changeListener({type: 'add', synth: this, method})
+ return func
+ } else {
+ this.sourceClass.prototype[method] = function (...args) {
+ this.transforms.push({name: method, transform: transform, userArgs: args, synth: self})
+ return this
+ }
}
+ return undefined
+ }
- return _this;
+ setFunction(obj) {
+ var processedGlsl = processGlsl(obj)
+ if(processedGlsl) this._addMethod(obj.name, processedGlsl)
}
+}
- _createClass__default['default'](ResourceStore, [{
- key: "addNamespaces",
- value: function addNamespaces(ns) {
- if (this.options.ns.indexOf(ns) < 0) {
- this.options.ns.push(ns);
- }
- }
- }, {
- key: "removeNamespaces",
- value: function removeNamespaces(ns) {
- var index = this.options.ns.indexOf(ns);
+const typeLookup = {
+ 'src': {
+ returnType: 'vec4',
+ args: ['vec2 _st']
+ },
+ 'coord': {
+ returnType: 'vec2',
+ args: ['vec2 _st']
+ },
+ 'color': {
+ returnType: 'vec4',
+ args: ['vec4 _c0']
+ },
+ 'combine': {
+ returnType: 'vec4',
+ args: ['vec4 _c0', 'vec4 _c1']
+ },
+ 'combineCoord': {
+ returnType: 'vec2',
+ args: ['vec2 _st', 'vec4 _c0']
+ }
+}
+// expects glsl of format
+// {
+// name: 'osc', // name that will be used to access function as well as within glsl
+// type: 'src', // can be src: vec4(vec2 _st), coord: vec2(vec2 _st), color: vec4(vec4 _c0), combine: vec4(vec4 _c0, vec4 _c1), combineCoord: vec2(vec2 _st, vec4 _c0)
+// inputs: [
+// {
+// name: 'freq',
+// type: 'float', // 'float' //, 'texture', 'vec4'
+// default: 0.2
+// },
+// {
+// name: 'sync',
+// type: 'float',
+// default: 0.1
+// },
+// {
+// name: 'offset',
+// type: 'float',
+// default: 0.0
+// }
+// ],
+ // glsl: `
+ // vec2 st = _st;
+ // float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5;
+ // float g = sin((st.x+time*sync)*freq)*0.5 + 0.5;
+ // float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5;
+ // return vec4(r, g, b, 1.0);
+ // `
+// }
- if (index > -1) {
- this.options.ns.splice(index, 1);
- }
- }
- }, {
- key: "getResource",
- value: function getResource(lng, ns, key) {
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
- var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
- var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
- var path = [lng, ns];
- if (key && typeof key !== 'string') path = path.concat(key);
- if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
+// // generates glsl function:
+// `vec4 osc(vec2 _st, float freq, float sync, float offset){
+// vec2 st = _st;
+// float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5;
+// float g = sin((st.x+time*sync)*freq)*0.5 + 0.5;
+// float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5;
+// return vec4(r, g, b, 1.0);
+// }`
- if (lng.indexOf('.') > -1) {
- path = lng.split('.');
- }
+function processGlsl(obj) {
+ let t = typeLookup[obj.type]
+ if(t) {
+ let baseArgs = t.args.map((arg) => arg).join(", ")
+ // @todo: make sure this works for all input types, add validation
+ let customArgs = obj.inputs.map((input) => `${input.type} ${input.name}`).join(', ')
+ let args = `${baseArgs}${customArgs.length > 0 ? ', '+ customArgs: ''}`
+// console.log('args are ', args)
- var result = getPath(this.data, path);
- if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
- return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
- }
- }, {
- key: "addResource",
- value: function addResource(lng, ns, key, value) {
- var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
- silent: false
- };
- var keySeparator = this.options.keySeparator;
- if (keySeparator === undefined) keySeparator = '.';
- var path = [lng, ns];
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
+ let glslFunction =
+`
+ ${t.returnType} ${obj.name}(${args}) {
+ ${obj.glsl}
+ }
+`
- if (lng.indexOf('.') > -1) {
- path = lng.split('.');
- value = ns;
- ns = path[1];
- }
+ // add extra input to beginning for backward combatibility @todo update compiler so this is no longer necessary
+ if(obj.type === 'combine' || obj.type === 'combineCoord') obj.inputs.unshift({
+ name: 'color',
+ type: 'vec4'
+ })
+ return Object.assign({}, obj, { glsl: glslFunction})
+ } else {
+ console.warn(`type ${obj.type} not recognized`, obj)
+ }
- this.addNamespaces(ns);
- setPath(this.data, path, value);
- if (!options.silent) this.emit('added', lng, ns, key, value);
- }
- }, {
- key: "addResources",
- value: function addResources(lng, ns, resources) {
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
- silent: false
- };
+}
- for (var m in resources) {
- if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
- silent: true
- });
- }
+module.exports = GeneratorFactory
- if (!options.silent) this.emit('added', lng, ns, resources);
- }
- }, {
- key: "addResourceBundle",
- value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
- var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
- silent: false
- };
- var path = [lng, ns];
+},{"./glsl-source.js":72,"./glsl/glsl-functions.js":73}],72:[function(require,module,exports){
+const generateGlsl = require('./generate-glsl.js')
+// const formatArguments = require('./glsl-utils.js').formatArguments
- if (lng.indexOf('.') > -1) {
- path = lng.split('.');
- deep = resources;
- resources = ns;
- ns = path[1];
- }
+// const glslTransforms = require('./glsl/composable-glsl-functions.js')
+const utilityGlsl = require('./glsl/utility-functions.js')
- this.addNamespaces(ns);
- var pack = getPath(this.data, path) || {};
+var GlslSource = function (obj) {
+ this.transforms = []
+ this.transforms.push(obj)
+ this.defaultOutput = obj.defaultOutput
+ this.synth = obj.synth
+ this.type = 'GlslSource'
+ this.defaultUniforms = obj.defaultUniforms
+ return this
+}
- if (deep) {
- deepExtend(pack, resources, overwrite);
- } else {
- pack = _objectSpread$1(_objectSpread$1({}, pack), resources);
- }
+GlslSource.prototype.addTransform = function (obj) {
+ this.transforms.push(obj)
+}
- setPath(this.data, path, pack);
- if (!options.silent) this.emit('added', lng, ns, resources);
- }
- }, {
- key: "removeResourceBundle",
- value: function removeResourceBundle(lng, ns) {
- if (this.hasResourceBundle(lng, ns)) {
- delete this.data[lng][ns];
- }
+GlslSource.prototype.out = function (_output) {
+ var output = _output || this.defaultOutput
+ var glsl = this.glsl(output)
+ this.synth.currentFunctions = []
+ // output.renderPasses(glsl)
+ if(output) try{
+ output.render(glsl)
+ } catch (error) {
+ console.log('shader could not compile', error)
+ }
+}
- this.removeNamespaces(ns);
- this.emit('removed', lng, ns);
- }
- }, {
- key: "hasResourceBundle",
- value: function hasResourceBundle(lng, ns) {
- return this.getResource(lng, ns) !== undefined;
- }
- }, {
- key: "getResourceBundle",
- value: function getResourceBundle(lng, ns) {
- if (!ns) ns = this.options.defaultNS;
- if (this.options.compatibilityAPI === 'v1') return _objectSpread$1(_objectSpread$1({}, {}), this.getResource(lng, ns));
- return this.getResource(lng, ns);
- }
- }, {
- key: "getDataByLanguage",
- value: function getDataByLanguage(lng) {
- return this.data[lng];
- }
- }, {
- key: "hasLanguageSomeTranslations",
- value: function hasLanguageSomeTranslations(lng) {
- var data = this.getDataByLanguage(lng);
- var n = data && Object.keys(data) || [];
- return !!n.find(function (v) {
- return data[v] && Object.keys(data[v]).length > 0;
- });
+GlslSource.prototype.glsl = function () {
+ //var output = _output || this.defaultOutput
+ var self = this
+ // uniforms included in all shaders
+// this.defaultUniforms = output.uniforms
+ var passes = []
+ var transforms = []
+// console.log('output', output)
+ this.transforms.forEach((transform) => {
+ if(transform.transform.type === 'renderpass'){
+ // if (transforms.length > 0) passes.push(this.compile(transforms, output))
+ // transforms = []
+ // var uniforms = {}
+ // const inputs = formatArguments(transform, -1)
+ // inputs.forEach((uniform) => { uniforms[uniform.name] = uniform.value })
+ //
+ // passes.push({
+ // frag: transform.transform.frag,
+ // uniforms: Object.assign({}, self.defaultUniforms, uniforms)
+ // })
+ // transforms.push({name: 'prev', transform: glslTransforms['prev'], synth: this.synth})
+ console.warn('no support for renderpass')
+ } else {
+ transforms.push(transform)
}
- }, {
- key: "toJSON",
- value: function toJSON() {
- return this.data;
+ })
+
+ if (transforms.length > 0) passes.push(this.compile(transforms))
+
+ return passes
+}
+
+GlslSource.prototype.compile = function (transforms) {
+ var shaderInfo = generateGlsl(transforms, this.synth)
+ var uniforms = {}
+ shaderInfo.uniforms.forEach((uniform) => { uniforms[uniform.name] = uniform.value })
+
+ var frag = `
+ precision ${this.defaultOutput.precision} float;
+ ${Object.values(shaderInfo.uniforms).map((uniform) => {
+ let type = uniform.type
+ switch (uniform.type) {
+ case 'texture':
+ type = 'sampler2D'
+ break
}
- }]);
+ return `
+ uniform ${type} ${uniform.name};`
+ }).join('')}
+ uniform float time;
+ uniform vec2 resolution;
+ varying vec2 uv;
+ uniform sampler2D prevBuffer;
- return ResourceStore;
-}(EventEmitter);
+ ${Object.values(utilityGlsl).map((transform) => {
+ // console.log(transform.glsl)
+ return `
+ ${transform.glsl}
+ `
+ }).join('')}
-var postProcessor = {
- processors: {},
- addPostProcessor: function addPostProcessor(module) {
- this.processors[module.name] = module;
- },
- handle: function handle(processors, value, key, options, translator) {
- var _this = this;
+ ${shaderInfo.glslFunctions.map((transform) => {
+ return `
+ ${transform.transform.glsl}
+ `
+ }).join('')}
- processors.forEach(function (processor) {
- if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
- });
- return value;
+ void main () {
+ vec4 c = vec4(1, 0, 0, 1);
+ vec2 st = gl_FragCoord.xy/resolution.xy;
+ gl_FragColor = ${shaderInfo.fragColor};
}
-};
+ `
-function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
+ return {
+ frag: frag,
+ uniforms: Object.assign({}, this.defaultUniforms, uniforms)
+ }
-function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+}
-function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
+module.exports = GlslSource
-function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
-var checkedLoadedFor = {};
+},{"./generate-glsl.js":70,"./glsl/utility-functions.js":74}],73:[function(require,module,exports){
+/*
+Format for adding functions to hydra. For each entry in this file, hydra automatically generates a glsl function and javascript function with the same name. You can also ass functions dynamically using setFunction(object).
-var Translator = function (_EventEmitter) {
- _inherits__default['default'](Translator, _EventEmitter);
+{
+ name: 'osc', // name that will be used to access function in js as well as in glsl
+ type: 'src', // can be 'src', 'color', 'combine', 'combineCoords'. see below for more info
+ inputs: [
+ {
+ name: 'freq',
+ type: 'float',
+ default: 0.2
+ },
+ {
+ name: 'sync',
+ type: 'float',
+ default: 0.1
+ },
+ {
+ name: 'offset',
+ type: 'float',
+ default: 0.0
+ }
+ ],
+ glsl: `
+ vec2 st = _st;
+ float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5;
+ float g = sin((st.x+time*sync)*freq)*0.5 + 0.5;
+ float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5;
+ return vec4(r, g, b, 1.0);
+ `
+}
- var _super = _createSuper$1(Translator);
+// The above code generates the glsl function:
+`vec4 osc(vec2 _st, float freq, float sync, float offset){
+ vec2 st = _st;
+ float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5;
+ float g = sin((st.x+time*sync)*freq)*0.5 + 0.5;
+ float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5;
+ return vec4(r, g, b, 1.0);
+}`
- function Translator(services) {
- var _this;
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+Types and default arguments for hydra functions.
+The value in the 'type' field lets the parser know which type the function will be returned as well as default arguments.
- _classCallCheck__default['default'](this, Translator);
+const types = {
+ 'src': {
+ returnType: 'vec4',
+ args: ['vec2 _st']
+ },
+ 'coord': {
+ returnType: 'vec2',
+ args: ['vec2 _st']
+ },
+ 'color': {
+ returnType: 'vec4',
+ args: ['vec4 _c0']
+ },
+ 'combine': {
+ returnType: 'vec4',
+ args: ['vec4 _c0', 'vec4 _c1']
+ },
+ 'combineCoord': {
+ returnType: 'vec2',
+ args: ['vec2 _st', 'vec4 _c0']
+ }
+}
- _this = _super.call(this);
+*/
- if (isIE10) {
- EventEmitter.call(_assertThisInitialized__default['default'](_this));
+module.exports = () => [
+ {
+ name: 'noise',
+ type: 'src',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scale',
+ default: 10,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0.1,
}
-
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized__default['default'](_this));
- _this.options = options;
-
- if (_this.options.keySeparator === undefined) {
- _this.options.keySeparator = '.';
+ ],
+ glsl:
+` return vec4(vec3(_noise(vec3(_st*scale, offset*time))), 1.0);`
+},
+{
+ name: 'voronoi',
+ type: 'src',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scale',
+ default: 5,
+ },
+{
+ type: 'float',
+ name: 'speed',
+ default: 0.3,
+ },
+{
+ type: 'float',
+ name: 'blending',
+ default: 0.3,
}
-
- _this.logger = baseLogger.create('translator');
- return _this;
- }
-
- _createClass__default['default'](Translator, [{
- key: "changeLanguage",
- value: function changeLanguage(lng) {
- if (lng) this.language = lng;
+ ],
+ glsl:
+` vec3 color = vec3(.0);
+ // Scale
+ _st *= scale;
+ // Tile the space
+ vec2 i_st = floor(_st);
+ vec2 f_st = fract(_st);
+ float m_dist = 10.; // minimun distance
+ vec2 m_point; // minimum point
+ for (int j=-1; j<=1; j++ ) {
+ for (int i=-1; i<=1; i++ ) {
+ vec2 neighbor = vec2(float(i),float(j));
+ vec2 p = i_st + neighbor;
+ vec2 point = fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453);
+ point = 0.5 + 0.5*sin(time*speed + 6.2831*point);
+ vec2 diff = neighbor + point - f_st;
+ float dist = length(diff);
+ if( dist < m_dist ) {
+ m_dist = dist;
+ m_point = point;
+ }
+ }
+ }
+ // Assign a color using the closest point position
+ color += dot(m_point,vec2(.3,.6));
+ color *= 1.0 - blending*m_dist;
+ return vec4(color, 1.0);`
+},
+{
+ name: 'osc',
+ type: 'src',
+ inputs: [
+ {
+ type: 'float',
+ name: 'frequency',
+ default: 60,
+ },
+{
+ type: 'float',
+ name: 'sync',
+ default: 0.1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
}
- }, {
- key: "exists",
- value: function exists(key) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
- interpolation: {}
- };
-
- if (key === undefined || key === null) {
- return false;
- }
-
- var resolved = this.resolve(key, options);
- return resolved && resolved.res !== undefined;
+ ],
+ glsl:
+` vec2 st = _st;
+ float r = sin((st.x-offset/frequency+time*sync)*frequency)*0.5 + 0.5;
+ float g = sin((st.x+time*sync)*frequency)*0.5 + 0.5;
+ float b = sin((st.x+offset/frequency+time*sync)*frequency)*0.5 + 0.5;
+ return vec4(r, g, b, 1.0);`
+},
+{
+ name: 'shape',
+ type: 'src',
+ inputs: [
+ {
+ type: 'float',
+ name: 'sides',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'radius',
+ default: 0.3,
+ },
+{
+ type: 'float',
+ name: 'smoothing',
+ default: 0.01,
}
- }, {
- key: "extractFromKey",
- value: function extractFromKey(key, options) {
- var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
- if (nsSeparator === undefined) nsSeparator = ':';
- var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
- var namespaces = options.ns || this.options.defaultNS || [];
- var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
- var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
-
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
- var m = key.match(this.interpolator.nestingRegexp);
-
- if (m && m.length > 0) {
- return {
- key: key,
- namespaces: namespaces
- };
- }
-
- var parts = key.split(nsSeparator);
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
- key = parts.join(keySeparator);
- }
-
- if (typeof namespaces === 'string') namespaces = [namespaces];
- return {
- key: key,
- namespaces: namespaces
- };
+ ],
+ glsl:
+` vec2 st = _st * 2. - 1.;
+ // Angle and radius from the current pixel
+ float a = atan(st.x,st.y)+3.1416;
+ float r = (2.*3.1416)/sides;
+ float d = cos(floor(.5+a/r)*r-a)*length(st);
+ return vec4(vec3(1.0-smoothstep(radius,radius + smoothing + 0.0000001,d)), 1.0);`
+},
+{
+ name: 'gradient',
+ type: 'src',
+ inputs: [
+ {
+ type: 'float',
+ name: 'speed',
+ default: 0,
+ }
+ ],
+ glsl:
+` return vec4(_st, sin(time*speed), 1.0);`
+},
+{
+ name: 'src',
+ type: 'src',
+ inputs: [
+ {
+ type: 'sampler2D',
+ name: 'tex',
+ default: NaN,
+ }
+ ],
+ glsl:
+` // vec2 uv = gl_FragCoord.xy/vec2(1280., 720.);
+ return texture2D(tex, fract(_st));`
+},
+{
+ name: 'solid',
+ type: 'src',
+ inputs: [
+ {
+ type: 'float',
+ name: 'r',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'g',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'b',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'a',
+ default: 1,
+ }
+ ],
+ glsl:
+` return vec4(r, g, b, a);`
+},
+{
+ name: 'rotate',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'angle',
+ default: 10,
+ },
+{
+ type: 'float',
+ name: 'speed',
+ default: 0,
+ }
+ ],
+ glsl:
+` vec2 xy = _st - vec2(0.5);
+ float ang = angle + speed *time;
+ xy = mat2(cos(ang),-sin(ang), sin(ang),cos(ang))*xy;
+ xy += 0.5;
+ return xy;`
+},
+{
+ name: 'scale',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1.5,
+ },
+{
+ type: 'float',
+ name: 'xMult',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'yMult',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offsetX',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'offsetY',
+ default: 0.5,
+ }
+ ],
+ glsl:
+` vec2 xy = _st - vec2(offsetX, offsetY);
+ xy*=(1.0/vec2(amount*xMult, amount*yMult));
+ xy+=vec2(offsetX, offsetY);
+ return xy;
+ `
+},
+{
+ name: 'pixelate',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'pixelX',
+ default: 20,
+ },
+{
+ type: 'float',
+ name: 'pixelY',
+ default: 20,
+ }
+ ],
+ glsl:
+` vec2 xy = vec2(pixelX, pixelY);
+ return (floor(_st * xy) + 0.5)/xy;`
+},
+{
+ name: 'posterize',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'bins',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'gamma',
+ default: 0.6,
+ }
+ ],
+ glsl:
+` vec4 c2 = pow(_c0, vec4(gamma));
+ c2 *= vec4(bins);
+ c2 = floor(c2);
+ c2/= vec4(bins);
+ c2 = pow(c2, vec4(1.0/gamma));
+ return vec4(c2.xyz, _c0.a);`
+},
+{
+ name: 'shift',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'r',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'g',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'b',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'a',
+ default: 0,
+ }
+ ],
+ glsl:
+` vec4 c2 = vec4(_c0);
+ c2.r = fract(c2.r + r);
+ c2.g = fract(c2.g + g);
+ c2.b = fract(c2.b + b);
+ c2.a = fract(c2.a + a);
+ return vec4(c2.rgba);`
+},
+{
+ name: 'repeat',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'repeatX',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'repeatY',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'offsetX',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'offsetY',
+ default: 0,
+ }
+ ],
+ glsl:
+` vec2 st = _st * vec2(repeatX, repeatY);
+ st.x += step(1., mod(st.y,2.0)) * offsetX;
+ st.y += step(1., mod(st.x,2.0)) * offsetY;
+ return fract(st);`
+},
+{
+ name: 'modulateRepeat',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'repeatX',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'repeatY',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'offsetX',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'offsetY',
+ default: 0.5,
}
- }, {
- key: "translate",
- value: function translate(keys, options, lastKey) {
- var _this2 = this;
-
- if (_typeof__default['default'](options) !== 'object' && this.options.overloadTranslationOptionHandler) {
- options = this.options.overloadTranslationOptionHandler(arguments);
- }
-
- if (!options) options = {};
- if (keys === undefined || keys === null) return '';
- if (!Array.isArray(keys)) keys = [String(keys)];
- var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
-
- var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
- key = _this$extractFromKey.key,
- namespaces = _this$extractFromKey.namespaces;
-
- var namespace = namespaces[namespaces.length - 1];
- var lng = options.lng || this.language;
- var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
-
- if (lng && lng.toLowerCase() === 'cimode') {
- if (appendNamespaceToCIMode) {
- var nsSeparator = options.nsSeparator || this.options.nsSeparator;
- return namespace + nsSeparator + key;
- }
-
- return key;
- }
-
- var resolved = this.resolve(keys, options);
- var res = resolved && resolved.res;
- var resUsedKey = resolved && resolved.usedKey || key;
- var resExactUsedKey = resolved && resolved.exactUsedKey || key;
- var resType = Object.prototype.toString.apply(res);
- var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
- var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
- var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
- var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
-
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
- if (!options.returnObjects && !this.options.returnObjects) {
- if (!this.options.returnedObjectHandler) {
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
- }
-
- return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$2(_objectSpread$2({}, options), {}, {
- ns: namespaces
- })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
- }
-
- if (keySeparator) {
- var resTypeIsArray = resType === '[object Array]';
- var copy = resTypeIsArray ? [] : {};
- var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
-
- for (var m in res) {
- if (Object.prototype.hasOwnProperty.call(res, m)) {
- var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
- copy[m] = this.translate(deepKey, _objectSpread$2(_objectSpread$2({}, options), {
- joinArrays: false,
- ns: namespaces
- }));
- if (copy[m] === deepKey) copy[m] = res[m];
- }
- }
-
- res = copy;
- }
- } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
- res = res.join(joinArrays);
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
- } else {
- var usedDefault = false;
- var usedKey = false;
- var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
- var hasDefaultValue = Translator.hasDefaultValue(options);
- var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
- var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
-
- if (!this.isValidLookup(res) && hasDefaultValue) {
- usedDefault = true;
- res = defaultValue;
- }
-
- if (!this.isValidLookup(res)) {
- usedKey = true;
- res = key;
- }
-
- var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
- var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
- var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
-
- if (usedKey || usedDefault || updateMissing) {
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
-
- if (keySeparator) {
- var fk = this.resolve(key, _objectSpread$2(_objectSpread$2({}, options), {}, {
- keySeparator: false
- }));
- if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
- }
-
- var lngs = [];
- var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
-
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
- for (var i = 0; i < fallbackLngs.length; i++) {
- lngs.push(fallbackLngs[i]);
- }
- } else if (this.options.saveMissingTo === 'all') {
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
- } else {
- lngs.push(options.lng || this.language);
- }
-
- var send = function send(l, k, specificDefaultValue) {
- var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
-
- if (_this2.options.missingKeyHandler) {
- _this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
- } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
- _this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
- }
-
- _this2.emit('missingKey', l, namespace, k, res);
- };
-
- if (this.options.saveMissing) {
- if (this.options.saveMissingPlurals && needsPluralHandling) {
- lngs.forEach(function (language) {
- _this2.pluralResolver.getSuffixes(language).forEach(function (suffix) {
- send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
- });
- });
- } else {
- send(lngs, key, defaultValue);
- }
- }
- }
-
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key);
-
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
- if (this.options.compatibilityAPI !== 'v1') {
- res = this.options.parseMissingKeyHandler(key, usedDefault ? res : undefined);
- } else {
- res = this.options.parseMissingKeyHandler(res);
- }
- }
- }
-
- return res;
+ ],
+ glsl:
+` vec2 st = _st * vec2(repeatX, repeatY);
+ st.x += step(1., mod(st.y,2.0)) + _c0.r * offsetX;
+ st.y += step(1., mod(st.x,2.0)) + _c0.g * offsetY;
+ return fract(st);`
+},
+{
+ name: 'repeatX',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'reps',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
}
- }, {
- key: "extendTranslation",
- value: function extendTranslation(res, key, options, resolved, lastKey) {
- var _this3 = this;
-
- if (this.i18nFormat && this.i18nFormat.parse) {
- res = this.i18nFormat.parse(res, options, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
- resolved: resolved
- });
- } else if (!options.skipInterpolation) {
- if (options.interpolation) this.interpolator.init(_objectSpread$2(_objectSpread$2({}, options), {
- interpolation: _objectSpread$2(_objectSpread$2({}, this.options.interpolation), options.interpolation)
- }));
- var skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
- var nestBef;
-
- if (skipOnVariables) {
- var nb = res.match(this.interpolator.nestingRegexp);
- nestBef = nb && nb.length;
- }
-
- var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
- if (this.options.interpolation.defaultVariables) data = _objectSpread$2(_objectSpread$2({}, this.options.interpolation.defaultVariables), data);
- res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
-
- if (skipOnVariables) {
- var na = res.match(this.interpolator.nestingRegexp);
- var nestAft = na && na.length;
- if (nestBef < nestAft) options.nest = false;
- }
-
- if (options.nest !== false) res = this.interpolator.nest(res, function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- if (lastKey && lastKey[0] === args[0] && !options.context) {
- _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
-
- return null;
- }
-
- return _this3.translate.apply(_this3, args.concat([key]));
- }, options);
- if (options.interpolation) this.interpolator.reset();
- }
-
- var postProcess = options.postProcess || this.options.postProcess;
- var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
-
- if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$2({
- i18nResolved: resolved
- }, options) : options, this);
- }
-
- return res;
+ ],
+ glsl:
+` vec2 st = _st * vec2(reps, 1.0);
+ // float f = mod(_st.y,2.0);
+ st.y += step(1., mod(st.x,2.0))* offset;
+ return fract(st);`
+},
+{
+ name: 'modulateRepeatX',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'reps',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0.5,
}
- }, {
- key: "resolve",
- value: function resolve(keys) {
- var _this4 = this;
-
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var found;
- var usedKey;
- var exactUsedKey;
- var usedLng;
- var usedNS;
- if (typeof keys === 'string') keys = [keys];
- keys.forEach(function (k) {
- if (_this4.isValidLookup(found)) return;
-
- var extracted = _this4.extractFromKey(k, options);
-
- var key = extracted.key;
- usedKey = key;
- var namespaces = extracted.namespaces;
- if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
- var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
-
- var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
-
- var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
- var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
- namespaces.forEach(function (ns) {
- if (_this4.isValidLookup(found)) return;
- usedNS = ns;
-
- if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
- checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
-
- _this4.logger.warn("key \"".concat(usedKey, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace \"").concat(usedNS, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
- }
-
- codes.forEach(function (code) {
- if (_this4.isValidLookup(found)) return;
- usedLng = code;
- var finalKeys = [key];
-
- if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
- _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
- } else {
- var pluralSuffix;
- if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options);
- var zeroSuffix = '_zero';
-
- if (needsPluralHandling) {
- finalKeys.push(key + pluralSuffix);
-
- if (needsZeroSuffixLookup) {
- finalKeys.push(key + zeroSuffix);
- }
- }
-
- if (needsContextHandling) {
- var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
- finalKeys.push(contextKey);
-
- if (needsPluralHandling) {
- finalKeys.push(contextKey + pluralSuffix);
-
- if (needsZeroSuffixLookup) {
- finalKeys.push(contextKey + zeroSuffix);
- }
- }
- }
- }
-
- var possibleKey;
-
- while (possibleKey = finalKeys.pop()) {
- if (!_this4.isValidLookup(found)) {
- exactUsedKey = possibleKey;
- found = _this4.getResource(code, ns, possibleKey, options);
- }
- }
- });
- });
- });
- return {
- res: found,
- usedKey: usedKey,
- exactUsedKey: exactUsedKey,
- usedLng: usedLng,
- usedNS: usedNS
- };
+ ],
+ glsl:
+` vec2 st = _st * vec2(reps, 1.0);
+ // float f = mod(_st.y,2.0);
+ st.y += step(1., mod(st.x,2.0)) + _c0.r * offset;
+ return fract(st);`
+},
+{
+ name: 'repeatY',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'reps',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
}
- }, {
- key: "isValidLookup",
- value: function isValidLookup(res) {
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
+ ],
+ glsl:
+` vec2 st = _st * vec2(1.0, reps);
+ // float f = mod(_st.y,2.0);
+ st.x += step(1., mod(st.y,2.0))* offset;
+ return fract(st);`
+},
+{
+ name: 'modulateRepeatY',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'reps',
+ default: 3,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0.5,
}
- }, {
- key: "getResource",
- value: function getResource(code, ns, key) {
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
- if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
- return this.resourceStore.getResource(code, ns, key, options);
+ ],
+ glsl:
+` vec2 st = _st * vec2(reps, 1.0);
+ // float f = mod(_st.y,2.0);
+ st.x += step(1., mod(st.y,2.0)) + _c0.r * offset;
+ return fract(st);`
+},
+{
+ name: 'kaleid',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'nSides',
+ default: 4,
}
- }], [{
- key: "hasDefaultValue",
- value: function hasDefaultValue(options) {
- var prefix = 'defaultValue';
-
- for (var option in options) {
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
- return true;
- }
- }
-
- return false;
+ ],
+ glsl:
+` vec2 st = _st;
+ st -= 0.5;
+ float r = length(st);
+ float a = atan(st.y, st.x);
+ float pi = 2.*3.1416;
+ a = mod(a,pi/nSides);
+ a = abs(a-pi/nSides/2.);
+ return r*vec2(cos(a), sin(a));`
+},
+{
+ name: 'modulateKaleid',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'nSides',
+ default: 4,
}
- }]);
-
- return Translator;
-}(EventEmitter);
-
-function capitalize(string) {
- return string.charAt(0).toUpperCase() + string.slice(1);
-}
-
-var LanguageUtil = function () {
- function LanguageUtil(options) {
- _classCallCheck__default['default'](this, LanguageUtil);
-
- this.options = options;
- this.supportedLngs = this.options.supportedLngs || false;
- this.logger = baseLogger.create('languageUtils');
- }
-
- _createClass__default['default'](LanguageUtil, [{
- key: "getScriptPartFromCode",
- value: function getScriptPartFromCode(code) {
- if (!code || code.indexOf('-') < 0) return null;
- var p = code.split('-');
- if (p.length === 2) return null;
- p.pop();
- if (p[p.length - 1].toLowerCase() === 'x') return null;
- return this.formatLanguageCode(p.join('-'));
+ ],
+ glsl:
+` vec2 st = _st - 0.5;
+ float r = length(st);
+ float a = atan(st.y, st.x);
+ float pi = 2.*3.1416;
+ a = mod(a,pi/nSides);
+ a = abs(a-pi/nSides/2.);
+ return (_c0.r+r)*vec2(cos(a), sin(a));`
+},
+{
+ name: 'scroll',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scrollX',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'scrollY',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'speedX',
+ default: 0,
+ },
+{
+ type: 'float',
+ name: 'speedY',
+ default: 0,
+ }
+ ],
+ glsl:
+`
+ _st.x += scrollX + time*speedX;
+ _st.y += scrollY + time*speedY;
+ return fract(_st);`
+},
+{
+ name: 'scrollX',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scrollX',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'speed',
+ default: 0,
}
- }, {
- key: "getLanguagePartFromCode",
- value: function getLanguagePartFromCode(code) {
- if (!code || code.indexOf('-') < 0) return code;
- var p = code.split('-');
- return this.formatLanguageCode(p[0]);
+ ],
+ glsl:
+` _st.x += scrollX + time*speed;
+ return fract(_st);`
+},
+{
+ name: 'modulateScrollX',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scrollX',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'speed',
+ default: 0,
}
- }, {
- key: "formatLanguageCode",
- value: function formatLanguageCode(code) {
- if (typeof code === 'string' && code.indexOf('-') > -1) {
- var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
- var p = code.split('-');
-
- if (this.options.lowerCaseLng) {
- p = p.map(function (part) {
- return part.toLowerCase();
- });
- } else if (p.length === 2) {
- p[0] = p[0].toLowerCase();
- p[1] = p[1].toUpperCase();
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
- } else if (p.length === 3) {
- p[0] = p[0].toLowerCase();
- if (p[1].length === 2) p[1] = p[1].toUpperCase();
- if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
- if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
- }
-
- return p.join('-');
- }
-
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
+ ],
+ glsl:
+` _st.x += _c0.r*scrollX + time*speed;
+ return fract(_st);`
+},
+{
+ name: 'scrollY',
+ type: 'coord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scrollY',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'speed',
+ default: 0,
}
- }, {
- key: "isSupportedCode",
- value: function isSupportedCode(code) {
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
- code = this.getLanguagePartFromCode(code);
- }
-
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
+ ],
+ glsl:
+` _st.y += scrollY + time*speed;
+ return fract(_st);`
+},
+{
+ name: 'modulateScrollY',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scrollY',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'speed',
+ default: 0,
}
- }, {
- key: "getBestMatchFromCodes",
- value: function getBestMatchFromCodes(codes) {
- var _this = this;
-
- if (!codes) return null;
- var found;
- codes.forEach(function (code) {
- if (found) return;
-
- var cleanedLng = _this.formatLanguageCode(code);
-
- if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;
- });
-
- if (!found && this.options.supportedLngs) {
- codes.forEach(function (code) {
- if (found) return;
-
- var lngOnly = _this.getLanguagePartFromCode(code);
-
- if (_this.isSupportedCode(lngOnly)) return found = lngOnly;
- found = _this.options.supportedLngs.find(function (supportedLng) {
- if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
- });
- });
- }
-
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
- return found;
+ ],
+ glsl:
+` _st.y += _c0.r*scrollY + time*speed;
+ return fract(_st);`
+},
+{
+ name: 'add',
+ type: 'combine',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1,
}
- }, {
- key: "getFallbackCodes",
- value: function getFallbackCodes(fallbacks, code) {
- if (!fallbacks) return [];
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
- if (typeof fallbacks === 'string') fallbacks = [fallbacks];
- if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
- if (!code) return fallbacks["default"] || [];
- var found = fallbacks[code];
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
- if (!found) found = fallbacks["default"];
- return found || [];
+ ],
+ glsl:
+` return (_c0+_c1)*amount + _c0*(1.0-amount);`
+},
+{
+ name: 'sub',
+ type: 'combine',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1,
}
- }, {
- key: "toResolveHierarchy",
- value: function toResolveHierarchy(code, fallbackCode) {
- var _this2 = this;
-
- var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
- var codes = [];
-
- var addCode = function addCode(c) {
- if (!c) return;
-
- if (_this2.isSupportedCode(c)) {
- codes.push(c);
- } else {
- _this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c));
- }
- };
-
- if (typeof code === 'string' && code.indexOf('-') > -1) {
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
- } else if (typeof code === 'string') {
- addCode(this.formatLanguageCode(code));
- }
+ ],
+ glsl:
+` return (_c0-_c1)*amount + _c0*(1.0-amount);`
+},
+{
+ name: 'layer',
+ type: 'combine',
+ inputs: [
- fallbackCodes.forEach(function (fc) {
- if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));
- });
- return codes;
+ ],
+ glsl:
+` return vec4(mix(_c0.rgb, _c1.rgb, _c1.a), _c0.a+_c1.a);`
+},
+{
+ name: 'blend',
+ type: 'combine',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 0.5,
}
- }]);
-
- return LanguageUtil;
-}();
-
-var sets = [{
- lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
- nr: [1, 2],
- fc: 1
-}, {
- lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
- nr: [1, 2],
- fc: 2
-}, {
- lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
- nr: [1],
- fc: 3
-}, {
- lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
- nr: [1, 2, 5],
- fc: 4
-}, {
- lngs: ['ar'],
- nr: [0, 1, 2, 3, 11, 100],
- fc: 5
-}, {
- lngs: ['cs', 'sk'],
- nr: [1, 2, 5],
- fc: 6
-}, {
- lngs: ['csb', 'pl'],
- nr: [1, 2, 5],
- fc: 7
-}, {
- lngs: ['cy'],
- nr: [1, 2, 3, 8],
- fc: 8
-}, {
- lngs: ['fr'],
- nr: [1, 2],
- fc: 9
-}, {
- lngs: ['ga'],
- nr: [1, 2, 3, 7, 11],
- fc: 10
-}, {
- lngs: ['gd'],
- nr: [1, 2, 3, 20],
- fc: 11
-}, {
- lngs: ['is'],
- nr: [1, 2],
- fc: 12
-}, {
- lngs: ['jv'],
- nr: [0, 1],
- fc: 13
-}, {
- lngs: ['kw'],
- nr: [1, 2, 3, 4],
- fc: 14
-}, {
- lngs: ['lt'],
- nr: [1, 2, 10],
- fc: 15
-}, {
- lngs: ['lv'],
- nr: [1, 2, 0],
- fc: 16
-}, {
- lngs: ['mk'],
- nr: [1, 2],
- fc: 17
-}, {
- lngs: ['mnk'],
- nr: [0, 1, 2],
- fc: 18
-}, {
- lngs: ['mt'],
- nr: [1, 2, 11, 20],
- fc: 19
-}, {
- lngs: ['or'],
- nr: [2, 1],
- fc: 2
-}, {
- lngs: ['ro'],
- nr: [1, 2, 20],
- fc: 20
-}, {
- lngs: ['sl'],
- nr: [5, 1, 2, 3],
- fc: 21
-}, {
- lngs: ['he', 'iw'],
- nr: [1, 2, 20, 21],
- fc: 22
-}];
-var _rulesPluralsTypes = {
- 1: function _(n) {
- return Number(n > 1);
- },
- 2: function _(n) {
- return Number(n != 1);
- },
- 3: function _(n) {
- return 0;
- },
- 4: function _(n) {
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
- },
- 5: function _(n) {
- return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
- },
- 6: function _(n) {
- return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
- },
- 7: function _(n) {
- return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
- },
- 8: function _(n) {
- return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
- },
- 9: function _(n) {
- return Number(n >= 2);
- },
- 10: function _(n) {
- return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
- },
- 11: function _(n) {
- return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
- },
- 12: function _(n) {
- return Number(n % 10 != 1 || n % 100 == 11);
- },
- 13: function _(n) {
- return Number(n !== 0);
- },
- 14: function _(n) {
- return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
- },
- 15: function _(n) {
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
- },
- 16: function _(n) {
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
- },
- 17: function _(n) {
- return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
- },
- 18: function _(n) {
- return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
- },
- 19: function _(n) {
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
- },
- 20: function _(n) {
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
- },
- 21: function _(n) {
- return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
- },
- 22: function _(n) {
- return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
- }
-};
-var deprecatedJsonVersions = ['v1', 'v2', 'v3'];
-var suffixesOrder = {
- zero: 0,
- one: 1,
- two: 2,
- few: 3,
- many: 4,
- other: 5
-};
-
-function createRules() {
- var rules = {};
- sets.forEach(function (set) {
- set.lngs.forEach(function (l) {
- rules[l] = {
- numbers: set.nr,
- plurals: _rulesPluralsTypes[set.fc]
- };
- });
- });
- return rules;
-}
-
-var PluralResolver = function () {
- function PluralResolver(languageUtils) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- _classCallCheck__default['default'](this, PluralResolver);
-
- this.languageUtils = languageUtils;
- this.options = options;
- this.logger = baseLogger.create('pluralResolver');
-
- if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === 'v4') && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
- this.options.compatibilityJSON = 'v3';
- this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
+ ],
+ glsl:
+` return _c0*(1.0-amount)+_c1*amount;`
+},
+{
+ name: 'mult',
+ type: 'combine',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1,
}
+ ],
+ glsl:
+` return _c0*(1.0-amount)+(_c0*_c1)*amount;`
+},
+{
+ name: 'diff',
+ type: 'combine',
+ inputs: [
- this.rules = createRules();
- }
-
- _createClass__default['default'](PluralResolver, [{
- key: "addRule",
- value: function addRule(lng, obj) {
- this.rules[lng] = obj;
+ ],
+ glsl:
+` return vec4(abs(_c0.rgb-_c1.rgb), max(_c0.a, _c1.a));`
+},
+{
+ name: 'modulate',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 0.1,
}
- }, {
- key: "getRule",
- value: function getRule(code) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- if (this.shouldUseIntlApi()) {
- try {
- return new Intl.PluralRules(code, {
- type: options.ordinal ? 'ordinal' : 'cardinal'
- });
- } catch (_unused) {
- return;
- }
- }
-
- return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
+ ],
+ glsl:
+` // return fract(st+(_c0.xy-0.5)*amount);
+ return _st + _c0.xy*amount;`
+},
+{
+ name: 'modulateScale',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'multiple',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 1,
}
- }, {
- key: "needsPlural",
- value: function needsPlural(code) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var rule = this.getRule(code, options);
-
- if (this.shouldUseIntlApi()) {
- return rule && rule.resolvedOptions().pluralCategories.length > 1;
- }
-
- return rule && rule.numbers.length > 1;
+ ],
+ glsl:
+` vec2 xy = _st - vec2(0.5);
+ xy*=(1.0/vec2(offset + multiple*_c0.r, offset + multiple*_c0.g));
+ xy+=vec2(0.5);
+ return xy;`
+},
+{
+ name: 'modulatePixelate',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'multiple',
+ default: 10,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 3,
}
- }, {
- key: "getPluralFormsOfKey",
- value: function getPluralFormsOfKey(code, key) {
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- return this.getSuffixes(code, options).map(function (suffix) {
- return "".concat(key).concat(suffix);
- });
+ ],
+ glsl:
+` vec2 xy = vec2(offset + _c0.x*multiple, offset + _c0.y*multiple);
+ return (floor(_st * xy) + 0.5)/xy;`
+},
+{
+ name: 'modulateRotate',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'multiple',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
}
- }, {
- key: "getSuffixes",
- value: function getSuffixes(code) {
- var _this = this;
-
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var rule = this.getRule(code, options);
-
- if (!rule) {
- return [];
- }
-
- if (this.shouldUseIntlApi()) {
- return rule.resolvedOptions().pluralCategories.sort(function (pluralCategory1, pluralCategory2) {
- return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
- }).map(function (pluralCategory) {
- return "".concat(_this.options.prepend).concat(pluralCategory);
- });
- }
-
- return rule.numbers.map(function (number) {
- return _this.getSuffix(code, number, options);
- });
+ ],
+ glsl:
+` vec2 xy = _st - vec2(0.5);
+ float angle = offset + _c0.x * multiple;
+ xy = mat2(cos(angle),-sin(angle), sin(angle),cos(angle))*xy;
+ xy += 0.5;
+ return xy;`
+},
+{
+ name: 'modulateHue',
+ type: 'combineCoord',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1,
}
- }, {
- key: "getSuffix",
- value: function getSuffix(code, count) {
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- var rule = this.getRule(code, options);
-
- if (rule) {
- if (this.shouldUseIntlApi()) {
- return "".concat(this.options.prepend).concat(rule.select(count));
- }
-
- return this.getSuffixRetroCompatible(rule, count);
- }
-
- this.logger.warn("no plural rule found for: ".concat(code));
- return '';
+ ],
+ glsl:
+` return _st + (vec2(_c0.g - _c0.r, _c0.b - _c0.g) * amount * 1.0/resolution);`
+},
+{
+ name: 'invert',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1,
}
- }, {
- key: "getSuffixRetroCompatible",
- value: function getSuffixRetroCompatible(rule, count) {
- var _this2 = this;
-
- var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
- var suffix = rule.numbers[idx];
-
- if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
- if (suffix === 2) {
- suffix = 'plural';
- } else if (suffix === 1) {
- suffix = '';
- }
- }
-
- var returnSuffix = function returnSuffix() {
- return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
- };
-
- if (this.options.compatibilityJSON === 'v1') {
- if (suffix === 1) return '';
- if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
- return returnSuffix();
- } else if (this.options.compatibilityJSON === 'v2') {
- return returnSuffix();
- } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
- return returnSuffix();
- }
-
- return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
+ ],
+ glsl:
+` return vec4((1.0-_c0.rgb)*amount + _c0.rgb*(1.0-amount), _c0.a);`
+},
+{
+ name: 'contrast',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 1.6,
}
- }, {
- key: "shouldUseIntlApi",
- value: function shouldUseIntlApi() {
- return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
+ ],
+ glsl:
+` vec4 c = (_c0-vec4(0.5))*vec4(amount) + vec4(0.5);
+ return vec4(c.rgb, _c0.a);`
+},
+{
+ name: 'brightness',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 0.4,
}
- }]);
-
- return PluralResolver;
-}();
-
-function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-
-function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-
-var Interpolator = function () {
- function Interpolator() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck__default['default'](this, Interpolator);
-
- this.logger = baseLogger.create('interpolator');
- this.options = options;
-
- this.format = options.interpolation && options.interpolation.format || function (value) {
- return value;
- };
+ ],
+ glsl:
+` return vec4(_c0.rgb + vec3(amount), _c0.a);`
+},
+{
+ name: 'mask',
+ type: 'combine',
+ inputs: [
- this.init(options);
- }
+ ],
+ glsl:
+ ` float a = _luminance(_c1.rgb);
+ return vec4(_c0.rgb*a, a*_c0.a);`
+},
- _createClass__default['default'](Interpolator, [{
- key: "init",
- value: function init() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- if (!options.interpolation) options.interpolation = {
- escapeValue: true
- };
- var iOpts = options.interpolation;
- this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
- this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
- this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
- this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
- this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
- this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
- this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
- this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
- this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
- this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
- this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
- this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
- this.resetRegExp();
+{
+ name: 'luma',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'threshold',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'tolerance',
+ default: 0.1,
}
- }, {
- key: "reset",
- value: function reset() {
- if (this.options) this.init(this.options);
+ ],
+ glsl:
+` float a = smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb));
+ return vec4(_c0.rgb*a, a);`
+},
+{
+ name: 'thresh',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'threshold',
+ default: 0.5,
+ },
+{
+ type: 'float',
+ name: 'tolerance',
+ default: 0.04,
}
- }, {
- key: "resetRegExp",
- value: function resetRegExp() {
- var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
- this.regexp = new RegExp(regexpStr, 'g');
- var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
- this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
- var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
- this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
+ ],
+ glsl:
+` return vec4(vec3(smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb))), _c0.a);`
+},
+{
+ name: 'color',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'r',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'g',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'b',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'a',
+ default: 1,
}
- }, {
- key: "interpolate",
- value: function interpolate(str, data, lng, options) {
- var _this = this;
-
- var match;
- var value;
- var replaces;
- var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
-
- function regexSafe(val) {
- return val.replace(/\$/g, '$$$$');
- }
-
- var handleFormat = function handleFormat(key) {
- if (key.indexOf(_this.formatSeparator) < 0) {
- var path = getPathWithDefaults(data, defaultData, key);
- return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
- interpolationkey: key
- })) : path;
- }
-
- var p = key.split(_this.formatSeparator);
- var k = p.shift().trim();
- var f = p.join(_this.formatSeparator).trim();
- return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
- interpolationkey: k
- }));
- };
-
- this.resetRegExp();
- var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
- var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
- var todos = [{
- regex: this.regexpUnescape,
- safeValue: function safeValue(val) {
- return regexSafe(val);
- }
- }, {
- regex: this.regexp,
- safeValue: function safeValue(val) {
- return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
- }
- }];
- todos.forEach(function (todo) {
- replaces = 0;
-
- while (match = todo.regex.exec(str)) {
- var matchedVar = match[1].trim();
- value = handleFormat(matchedVar);
-
- if (value === undefined) {
- if (typeof missingInterpolationHandler === 'function') {
- var temp = missingInterpolationHandler(str, match, options);
- value = typeof temp === 'string' ? temp : '';
- } else if (options && options.hasOwnProperty(matchedVar)) {
- value = '';
- } else if (skipOnVariables) {
- value = match[0];
- continue;
- } else {
- _this.logger.warn("missed to pass in variable ".concat(matchedVar, " for interpolating ").concat(str));
-
- value = '';
- }
- } else if (typeof value !== 'string' && !_this.useRawValueToEscape) {
- value = makeString(value);
- }
-
- var safeValue = todo.safeValue(value);
- str = str.replace(match[0], safeValue);
-
- if (skipOnVariables) {
- todo.regex.lastIndex += safeValue.length;
- todo.regex.lastIndex -= match[0].length;
- } else {
- todo.regex.lastIndex = 0;
- }
-
- replaces++;
-
- if (replaces >= _this.maxReplaces) {
- break;
- }
- }
- });
- return str;
+ ],
+ glsl:
+` vec4 c = vec4(r, g, b, a);
+ vec4 pos = step(0.0, c); // detect whether negative
+ // if > 0, return r * _c0
+ // if < 0 return (1.0-r) * _c0
+ return vec4(mix((1.0-_c0)*abs(c), c*_c0, pos));`
+},
+{
+ name: 'saturate',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 2,
}
- }, {
- key: "nest",
- value: function nest(str, fc) {
- var _this2 = this;
-
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- var match;
- var value;
-
- var clonedOptions = _objectSpread$3({}, options);
-
- clonedOptions.applyPostProcessor = false;
- delete clonedOptions.defaultValue;
-
- function handleHasOptions(key, inheritedOptions) {
- var sep = this.nestingOptionsSeparator;
- if (key.indexOf(sep) < 0) return key;
- var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
- var optionsString = "{".concat(c[1]);
- key = c[0];
- optionsString = this.interpolate(optionsString, clonedOptions);
- optionsString = optionsString.replace(/'/g, '"');
-
- try {
- clonedOptions = JSON.parse(optionsString);
- if (inheritedOptions) clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions);
- } catch (e) {
- this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
- return "".concat(key).concat(sep).concat(optionsString);
- }
-
- delete clonedOptions.defaultValue;
- return key;
- }
-
- while (match = this.nestingRegexp.exec(str)) {
- var formatters = [];
- var doReduce = false;
-
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
- var r = match[1].split(this.formatSeparator).map(function (elem) {
- return elem.trim();
- });
- match[1] = r.shift();
- formatters = r;
- doReduce = true;
- }
-
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
- if (value && match[0] === str && typeof value !== 'string') return value;
- if (typeof value !== 'string') value = makeString(value);
-
- if (!value) {
- this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
- value = '';
- }
-
- if (doReduce) {
- value = formatters.reduce(function (v, f) {
- return _this2.format(v, f, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, {
- interpolationkey: match[1].trim()
- }));
- }, value.trim());
- }
-
- str = str.replace(match[0], value);
- this.regexp.lastIndex = 0;
- }
-
- return str;
+ ],
+ glsl:
+` const vec3 W = vec3(0.2125, 0.7154, 0.0721);
+ vec3 intensity = vec3(dot(_c0.rgb, W));
+ return vec4(mix(intensity, _c0.rgb, amount), _c0.a);`
+},
+{
+ name: 'hue',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'hue',
+ default: 0.4,
}
- }]);
-
- return Interpolator;
-}();
-
-function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-
-function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-
-function parseFormatStr(formatStr) {
- var formatName = formatStr.toLowerCase().trim();
- var formatOptions = {};
-
- if (formatStr.indexOf('(') > -1) {
- var p = formatStr.split('(');
- formatName = p[0].toLowerCase().trim();
- var optStr = p[1].substring(0, p[1].length - 1);
-
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
- if (!formatOptions.range) formatOptions.range = optStr.trim();
- } else {
- var opts = optStr.split(';');
- opts.forEach(function (opt) {
- if (!opt) return;
-
- var _opt$split = opt.split(':'),
- _opt$split2 = _toArray__default['default'](_opt$split),
- key = _opt$split2[0],
- rest = _opt$split2.slice(1);
-
- var val = rest.join(':');
- if (val.trim() === 'false') formatOptions[key.trim()] = false;
- if (val.trim() === 'true') formatOptions[key.trim()] = true;
- if (!isNaN(val.trim())) formatOptions[key.trim()] = parseInt(val.trim(), 10);
- if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val.trim();
- });
+ ],
+ glsl:
+` vec3 c = _rgbToHsv(_c0.rgb);
+ c.r += hue;
+ // c.r = fract(c.r);
+ return vec4(_hsvToRgb(c), _c0.a);`
+},
+{
+ name: 'colorama',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'amount',
+ default: 0.005,
}
- }
-
- return {
- formatName: formatName,
- formatOptions: formatOptions
- };
-}
-
-var Formatter = function () {
- function Formatter() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck__default['default'](this, Formatter);
-
- this.logger = baseLogger.create('formatter');
- this.options = options;
- this.formats = {
- number: function number(val, lng, options) {
- return new Intl.NumberFormat(lng, options).format(val);
- },
- currency: function currency(val, lng, options) {
- return new Intl.NumberFormat(lng, _objectSpread$4(_objectSpread$4({}, options), {}, {
- style: 'currency'
- })).format(val);
- },
- datetime: function datetime(val, lng, options) {
- return new Intl.DateTimeFormat(lng, _objectSpread$4({}, options)).format(val);
- },
- relativetime: function relativetime(val, lng, options) {
- return new Intl.RelativeTimeFormat(lng, _objectSpread$4({}, options)).format(val, options.range || 'day');
- },
- list: function list(val, lng, options) {
- return new Intl.ListFormat(lng, _objectSpread$4({}, options)).format(val);
- }
- };
- this.init(options);
- }
+ ],
+ glsl:
+` vec3 c = _rgbToHsv(_c0.rgb);
+ c += vec3(amount);
+ c = _hsvToRgb(c);
+ c = fract(c);
+ return vec4(c, _c0.a);`
+},
+{
+ name: 'prev',
+ type: 'src',
+ inputs: [
- _createClass__default['default'](Formatter, [{
- key: "init",
- value: function init(services) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
- interpolation: {}
- };
- var iOpts = options.interpolation;
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
+ ],
+ glsl:
+` return texture2D(prevBuffer, fract(_st));`
+},
+{
+ name: 'sum',
+ type: 'color',
+ inputs: [
+ {
+ type: 'vec4',
+ name: 'scale',
+ default: 1,
}
- }, {
- key: "add",
- value: function add(name, fc) {
- this.formats[name.toLowerCase().trim()] = fc;
+ ],
+ glsl:
+` vec4 v = _c0 * s;
+ return v.r + v.g + v.b + v.a;
+ }
+ float sum(vec2 _st, vec4 s) { // vec4 is not a typo, because argument type is not overloaded
+ vec2 v = _st.xy * s.xy;
+ return v.x + v.y;`
+},
+{
+ name: 'r',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scale',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
}
- }, {
- key: "format",
- value: function format(value, _format, lng, options) {
- var _this = this;
-
- var formats = _format.split(this.formatSeparator);
-
- var result = formats.reduce(function (mem, f) {
- var _parseFormatStr = parseFormatStr(f),
- formatName = _parseFormatStr.formatName,
- formatOptions = _parseFormatStr.formatOptions;
-
- if (_this.formats[formatName]) {
- var formatted = mem;
-
- try {
- var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
- var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
- formatted = _this.formats[formatName](mem, l, _objectSpread$4(_objectSpread$4(_objectSpread$4({}, formatOptions), options), valOptions));
- } catch (error) {
- _this.logger.warn(error);
- }
-
- return formatted;
- } else {
- _this.logger.warn("there was no format function for ".concat(formatName));
- }
-
- return mem;
- }, value);
- return result;
+ ],
+ glsl:
+` return vec4(_c0.r * scale + offset);`
+},
+{
+ name: 'g',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scale',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
}
- }]);
+ ],
+ glsl:
+` return vec4(_c0.g * scale + offset);`
+},
+{
+ name: 'b',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scale',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
+ }
+ ],
+ glsl:
+` return vec4(_c0.b * scale + offset);`
+},
+{
+ name: 'a',
+ type: 'color',
+ inputs: [
+ {
+ type: 'float',
+ name: 'scale',
+ default: 1,
+ },
+{
+ type: 'float',
+ name: 'offset',
+ default: 0,
+ }
+ ],
+ glsl:
+` return vec4(_c0.a * scale + offset);`
+}
+]
- return Formatter;
-}();
+},{}],74:[function(require,module,exports){
+// functions that are only used within other functions
-function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
+module.exports = {
+ _luminance: {
+ type: 'util',
+ glsl: `float _luminance(vec3 rgb){
+ const vec3 W = vec3(0.2125, 0.7154, 0.0721);
+ return dot(rgb, W);
+ }`
+ },
+ _noise: {
+ type: 'util',
+ glsl: `
+ // Simplex 3D Noise
+ // by Ian McEwan, Ashima Arts
+ vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);}
+ vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}
-function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+ float _noise(vec3 v){
+ const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;
+ const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
-function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
+ // First corner
+ vec3 i = floor(v + dot(v, C.yyy) );
+ vec3 x0 = v - i + dot(i, C.xxx) ;
-function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+ // Other corners
+ vec3 g = step(x0.yzx, x0.xyz);
+ vec3 l = 1.0 - g;
+ vec3 i1 = min( g.xyz, l.zxy );
+ vec3 i2 = max( g.xyz, l.zxy );
-function remove(arr, what) {
- var found = arr.indexOf(what);
+ // x0 = x0 - 0. + 0.0 * C
+ vec3 x1 = x0 - i1 + 1.0 * C.xxx;
+ vec3 x2 = x0 - i2 + 2.0 * C.xxx;
+ vec3 x3 = x0 - 1. + 3.0 * C.xxx;
- while (found !== -1) {
- arr.splice(found, 1);
- found = arr.indexOf(what);
- }
-}
+ // Permutations
+ i = mod(i, 289.0 );
+ vec4 p = permute( permute( permute(
+ i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
+ + i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
+ + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
-var Connector = function (_EventEmitter) {
- _inherits__default['default'](Connector, _EventEmitter);
+ // Gradients
+ // ( N*N points uniformly over a square, mapped onto an octahedron.)
+ float n_ = 1.0/7.0; // N=7
+ vec3 ns = n_ * D.wyz - D.xzx;
- var _super = _createSuper$2(Connector);
+ vec4 j = p - 49.0 * floor(p * ns.z *ns.z); // mod(p,N*N)
- function Connector(backend, store, services) {
- var _this;
+ vec4 x_ = floor(j * ns.z);
+ vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+ vec4 x = x_ *ns.x + ns.yyyy;
+ vec4 y = y_ *ns.x + ns.yyyy;
+ vec4 h = 1.0 - abs(x) - abs(y);
- _classCallCheck__default['default'](this, Connector);
+ vec4 b0 = vec4( x.xy, y.xy );
+ vec4 b1 = vec4( x.zw, y.zw );
- _this = _super.call(this);
+ vec4 s0 = floor(b0)*2.0 + 1.0;
+ vec4 s1 = floor(b1)*2.0 + 1.0;
+ vec4 sh = -step(h, vec4(0.0));
- if (isIE10) {
- EventEmitter.call(_assertThisInitialized__default['default'](_this));
- }
+ vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
+ vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
- _this.backend = backend;
- _this.store = store;
- _this.services = services;
- _this.languageUtils = services.languageUtils;
- _this.options = options;
- _this.logger = baseLogger.create('backendConnector');
- _this.state = {};
- _this.queue = [];
+ vec3 p0 = vec3(a0.xy,h.x);
+ vec3 p1 = vec3(a0.zw,h.y);
+ vec3 p2 = vec3(a1.xy,h.z);
+ vec3 p3 = vec3(a1.zw,h.w);
- if (_this.backend && _this.backend.init) {
- _this.backend.init(services, options.backend, options);
- }
+ //Normalise gradients
+ vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
+ p0 *= norm.x;
+ p1 *= norm.y;
+ p2 *= norm.z;
+ p3 *= norm.w;
- return _this;
+ // Mix final noise value
+ vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
+ m = m * m;
+ return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
+ dot(p2,x2), dot(p3,x3) ) );
}
+ `
+ },
- _createClass__default['default'](Connector, [{
- key: "queueLoad",
- value: function queueLoad(languages, namespaces, options, callback) {
- var _this2 = this;
-
- var toLoad = [];
- var pending = [];
- var toLoadLanguages = [];
- var toLoadNamespaces = [];
- languages.forEach(function (lng) {
- var hasAllNamespaces = true;
- namespaces.forEach(function (ns) {
- var name = "".concat(lng, "|").concat(ns);
-
- if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
- _this2.state[name] = 2;
- } else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
- if (pending.indexOf(name) < 0) pending.push(name);
- } else {
- _this2.state[name] = 1;
- hasAllNamespaces = false;
- if (pending.indexOf(name) < 0) pending.push(name);
- if (toLoad.indexOf(name) < 0) toLoad.push(name);
- if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns);
- }
- });
- if (!hasAllNamespaces) toLoadLanguages.push(lng);
- });
-
- if (toLoad.length || pending.length) {
- this.queue.push({
- pending: pending,
- loaded: {},
- errors: [],
- callback: callback
- });
- }
-
- return {
- toLoad: toLoad,
- pending: pending,
- toLoadLanguages: toLoadLanguages,
- toLoadNamespaces: toLoadNamespaces
- };
- }
- }, {
- key: "loaded",
- value: function loaded(name, err, data) {
- var s = name.split('|');
- var lng = s[0];
- var ns = s[1];
- if (err) this.emit('failedLoading', lng, ns, err);
-
- if (data) {
- this.store.addResourceBundle(lng, ns, data);
- }
-
- this.state[name] = err ? -1 : 2;
- var loaded = {};
- this.queue.forEach(function (q) {
- pushPath(q.loaded, [lng], ns);
- remove(q.pending, name);
- if (err) q.errors.push(err);
- if (q.pending.length === 0 && !q.done) {
- Object.keys(q.loaded).forEach(function (l) {
- if (!loaded[l]) loaded[l] = [];
+ _rgbToHsv: {
+ type: 'util',
+ glsl: `vec3 _rgbToHsv(vec3 c){
+ vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
+ vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
+ vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
- if (q.loaded[l].length) {
- q.loaded[l].forEach(function (ns) {
- if (loaded[l].indexOf(ns) < 0) loaded[l].push(ns);
- });
- }
- });
- q.done = true;
+ float d = q.x - min(q.w, q.y);
+ float e = 1.0e-10;
+ return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
+ }`
+ },
+ _hsvToRgb: {
+ type: 'util',
+ glsl: `vec3 _hsvToRgb(vec3 c){
+ vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
+ vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
+ return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
+ }`
+ }
+}
- if (q.errors.length) {
- q.callback(q.errors);
- } else {
- q.callback();
- }
- }
- });
- this.emit('loaded', loaded);
- this.queue = this.queue.filter(function (q) {
- return !q.done;
- });
- }
- }, {
- key: "read",
- value: function read(lng, ns, fcName) {
- var _this3 = this;
+},{}],75:[function(require,module,exports){
+const Webcam = require('./lib/webcam.js')
+const Screen = require('./lib/screenmedia.js')
- var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
- var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 350;
- var callback = arguments.length > 5 ? arguments[5] : undefined;
- if (!lng.length) return callback(null, {});
- return this.backend[fcName](lng, ns, function (err, data) {
- if (err && data && tried < 5) {
- setTimeout(function () {
- _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
- }, wait);
- return;
- }
+class HydraSource {
+ constructor ({ regl, width, height, pb, label = ""}) {
+ this.label = label
+ this.regl = regl
+ this.src = null
+ this.dynamic = true
+ this.width = width
+ this.height = height
+ this.tex = this.regl.texture({
+ // shape: [width, height]
+ shape: [ 1, 1 ]
+ })
+ this.pb = pb
+ }
- callback(err, data);
- });
+ init (opts) {
+ if (opts.src) {
+ this.src = opts.src
+ this.tex = this.regl.texture(this.src)
}
- }, {
- key: "prepareLoading",
- value: function prepareLoading(languages, namespaces) {
- var _this4 = this;
-
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- var callback = arguments.length > 3 ? arguments[3] : undefined;
-
- if (!this.backend) {
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
- return callback && callback();
- }
+ if (opts.dynamic) this.dynamic = opts.dynamic
+ }
- if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
- if (typeof namespaces === 'string') namespaces = [namespaces];
- var toLoad = this.queueLoad(languages, namespaces, options, callback);
+ initCam (index) {
+ const self = this
+ Webcam(index)
+ .then(response => {
+ self.src = response.video
+ self.dynamic = true
+ self.tex = self.regl.texture(self.src)
+ })
+ .catch(err => console.log('could not get camera', err))
+ }
- if (!toLoad.toLoad.length) {
- if (!toLoad.pending.length) callback();
- return null;
- }
+ initVideo (url = '') {
+ // const self = this
+ const vid = document.createElement('video')
+ vid.crossOrigin = 'anonymous'
+ vid.autoplay = true
+ vid.loop = true
+ vid.muted = true // mute in order to load without user interaction
+ const onload = vid.addEventListener('loadeddata', () => {
+ this.src = vid
+ vid.play()
+ this.tex = this.regl.texture(this.src)
+ this.dynamic = true
+ })
+ vid.src = url
+ }
- toLoad.toLoad.forEach(function (name) {
- _this4.loadOne(name);
- });
- }
- }, {
- key: "load",
- value: function load(languages, namespaces, callback) {
- this.prepareLoading(languages, namespaces, {}, callback);
- }
- }, {
- key: "reload",
- value: function reload(languages, namespaces, callback) {
- this.prepareLoading(languages, namespaces, {
- reload: true
- }, callback);
+ initImage (url = '') {
+ const img = document.createElement('img')
+ img.crossOrigin = 'anonymous'
+ img.src = url
+ img.onload = () => {
+ this.src = img
+ this.dynamic = false
+ this.tex = this.regl.texture(this.src)
}
- }, {
- key: "loadOne",
- value: function loadOne(name) {
- var _this5 = this;
+ }
- var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
- var s = name.split('|');
- var lng = s[0];
- var ns = s[1];
- this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
- if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
- if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
+ initStream (streamName) {
+ // console.log("initing stream!", streamName)
+ let self = this
+ if (streamName && this.pb) {
+ this.pb.initSource(streamName)
- _this5.loaded(name, err, data);
- });
+ this.pb.on('got video', function (nick, video) {
+ if (nick === streamName) {
+ self.src = video
+ self.dynamic = true
+ self.tex = self.regl.texture(self.src)
+ }
+ })
}
- }, {
- key: "saveMissing",
- value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
- var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
+ }
- if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
- this.logger.warn("did not save key \"".concat(key, "\" as the namespace \"").concat(namespace, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
- return;
- }
+ initScreen () {
+ const self = this
+ Screen()
+ .then(function (response) {
+ self.src = response.video
+ self.tex = self.regl.texture(self.src)
+ self.dynamic = true
+ // console.log("received screen input")
+ })
+ .catch(err => console.log('could not get screen', err))
+ }
- if (key === undefined || key === null || key === '') return;
+ resize (width, height) {
+ this.width = width
+ this.height = height
+ }
- if (this.backend && this.backend.create) {
- this.backend.create(languages, namespace, key, fallbackValue, null, _objectSpread$5(_objectSpread$5({}, options), {}, {
- isUpdate: isUpdate
- }));
+ clear () {
+ if (this.src && this.src.srcObject) {
+ if (this.src.srcObject.getTracks) {
+ this.src.srcObject.getTracks().forEach(track => track.stop())
}
-
- if (!languages || !languages[0]) return;
- this.store.addResource(languages[0], namespace, key, fallbackValue);
}
- }]);
-
- return Connector;
-}(EventEmitter);
+ this.src = null
+ this.tex = this.regl.texture({ shape: [ 1, 1 ] })
+ }
-function get() {
- return {
- debug: false,
- initImmediate: true,
- ns: ['translation'],
- defaultNS: ['translation'],
- fallbackLng: ['dev'],
- fallbackNS: false,
- supportedLngs: false,
- nonExplicitSupportedLngs: false,
- load: 'all',
- preload: false,
- simplifyPluralSuffix: true,
- keySeparator: '.',
- nsSeparator: ':',
- pluralSeparator: '_',
- contextSeparator: '_',
- partialBundledLanguages: false,
- saveMissing: false,
- updateMissing: false,
- saveMissingTo: 'fallback',
- saveMissingPlurals: true,
- missingKeyHandler: false,
- missingInterpolationHandler: false,
- postProcess: false,
- postProcessPassResolved: false,
- returnNull: true,
- returnEmptyString: true,
- returnObjects: false,
- joinArrays: false,
- returnedObjectHandler: false,
- parseMissingKeyHandler: false,
- appendNamespaceToMissingKey: false,
- appendNamespaceToCIMode: false,
- overloadTranslationOptionHandler: function handle(args) {
- var ret = {};
- if (_typeof__default['default'](args[1]) === 'object') ret = args[1];
- if (typeof args[1] === 'string') ret.defaultValue = args[1];
- if (typeof args[2] === 'string') ret.tDescription = args[2];
+ tick (time) {
+ // console.log(this.src, this.tex.width, this.tex.height)
+ if (this.src !== null && this.dynamic === true) {
+ if (this.src.videoWidth && this.src.videoWidth !== this.tex.width) {
+ console.log(
+ this.src.videoWidth,
+ this.src.videoHeight,
+ this.tex.width,
+ this.tex.height
+ )
+ this.tex.resize(this.src.videoWidth, this.src.videoHeight)
+ }
- if (_typeof__default['default'](args[2]) === 'object' || _typeof__default['default'](args[3]) === 'object') {
- var options = args[3] || args[2];
- Object.keys(options).forEach(function (key) {
- ret[key] = options[key];
- });
+ if (this.src.width && this.src.width !== this.tex.width) {
+ this.tex.resize(this.src.width, this.src.height)
}
- return ret;
- },
- interpolation: {
- escapeValue: true,
- format: function format(value, _format, lng, options) {
- return value;
- },
- prefix: '{{',
- suffix: '}}',
- formatSeparator: ',',
- unescapePrefix: '-',
- nestingPrefix: '$t(',
- nestingSuffix: ')',
- nestingOptionsSeparator: ',',
- maxReplaces: 1000,
- skipOnVariables: true
+ this.tex.subimage(this.src)
}
- };
-}
-function transformOptions(options) {
- if (typeof options.ns === 'string') options.ns = [options.ns];
- if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
- if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
-
- if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
}
- return options;
+ getTexture () {
+ return this.tex
+ }
}
-function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-
-function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-
-function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
+module.exports = HydraSource
-function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+},{"./lib/screenmedia.js":82,"./lib/webcam.js":84}],76:[function(require,module,exports){
+// WIP utils for working with arrays
+// Possibly should be integrated with lfo extension, etc.
+// to do: transform time rather than array values, similar to working with coordinates in hydra
-function noop() {}
+var easing = require('./easing-functions.js')
-function bindMemberFunctions(inst) {
- var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
- mems.forEach(function (mem) {
- if (typeof inst[mem] === 'function') {
- inst[mem] = inst[mem].bind(inst);
- }
- });
+var map = (num, in_min, in_max, out_min, out_max) => {
+ return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
-var I18n = function (_EventEmitter) {
- _inherits__default['default'](I18n, _EventEmitter);
-
- var _super = _createSuper$3(I18n);
-
- function I18n() {
- var _this;
+module.exports = {
+ init: () => {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var callback = arguments.length > 1 ? arguments[1] : undefined;
+ Array.prototype.fast = function(speed = 1) {
+ this._speed = speed
+ return this
+ }
- _classCallCheck__default['default'](this, I18n);
+ Array.prototype.smooth = function(smooth = 1) {
+ this._smooth = smooth
+ return this
+ }
- _this = _super.call(this);
+ Array.prototype.ease = function(ease = 'linear') {
+ if (typeof ease == 'function') {
+ this._smooth = 1
+ this._ease = ease
+ }
+ else if (easing[ease]){
+ this._smooth = 1
+ this._ease = easing[ease]
+ }
+ return this
+ }
- if (isIE10) {
- EventEmitter.call(_assertThisInitialized__default['default'](_this));
+ Array.prototype.offset = function(offset = 0.5) {
+ this._offset = offset%1.0
+ return this
}
- _this.options = transformOptions(options);
- _this.services = {};
- _this.logger = baseLogger;
- _this.modules = {
- external: []
- };
- bindMemberFunctions(_assertThisInitialized__default['default'](_this));
+ // Array.prototype.bounce = function() {
+ // this.modifiers.bounce = true
+ // return this
+ // }
- if (callback && !_this.isInitialized && !options.isClone) {
- if (!_this.options.initImmediate) {
- _this.init(options, callback);
+ Array.prototype.fit = function(low = 0, high =1) {
+ let lowest = Math.min(...this)
+ let highest = Math.max(...this)
+ var newArr = this.map((num) => map(num, lowest, highest, low, high))
+ newArr._speed = this._speed
+ newArr._smooth = this._smooth
+ newArr._ease = this._ease
+ return newArr
+ }
+ },
- return _possibleConstructorReturn__default['default'](_this, _assertThisInitialized__default['default'](_this));
- }
+ getValue: (arr = []) => ({time, bpm}) =>{
+ let speed = arr._speed ? arr._speed : 1
+ let smooth = arr._smooth ? arr._smooth : 0
+ let index = time * speed * (bpm / 60) + (arr._offset || 0)
- setTimeout(function () {
- _this.init(options, callback);
- }, 0);
+ if (smooth!==0) {
+ let ease = arr._ease ? arr._ease : easing['linear']
+ let _index = index - (smooth / 2)
+ let currValue = arr[Math.floor(_index % (arr.length))]
+ let nextValue = arr[Math.floor((_index + 1) % (arr.length))]
+ let t = Math.min((_index%1)/smooth,1)
+ return ease(t) * (nextValue - currValue) + currValue
+ }
+ else {
+ return arr[Math.floor(index % (arr.length))]
}
-
- return _this;
}
+}
- _createClass__default['default'](I18n, [{
- key: "init",
- value: function init() {
- var _this2 = this;
-
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var callback = arguments.length > 1 ? arguments[1] : undefined;
+},{"./easing-functions.js":78}],77:[function(require,module,exports){
+const Meyda = require('meyda')
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
+class Audio {
+ constructor ({
+ numBins = 4,
+ cutoff = 2,
+ smooth = 0.4,
+ max = 15,
+ scale = 10,
+ isDrawing = false
+ }) {
+ this.vol = 0
+ this.scale = scale
+ this.max = max
+ this.cutoff = cutoff
+ this.smooth = smooth
+ this.setBins(numBins)
- if (!options.defaultNS && options.ns) {
- if (typeof options.ns === 'string') {
- options.defaultNS = options.ns;
- } else if (options.ns.indexOf('translation') < 0) {
- options.defaultNS = options.ns[0];
- }
- }
+ // beat detection from: https://github.com/therewasaguy/p5-music-viz/blob/gh-pages/demos/01d_beat_detect_amplitude/sketch.js
+ this.beat = {
+ holdFrames: 20,
+ threshold: 40,
+ _cutoff: 0, // adaptive based on sound state
+ decay: 0.98,
+ _framesSinceBeat: 0 // keeps track of frames
+ }
- var defOpts = get();
- this.options = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, defOpts), this.options), transformOptions(options));
+ this.onBeat = () => {
+ // console.log("beat")
+ }
- if (this.options.compatibilityAPI !== 'v1') {
- this.options.interpolation = _objectSpread$6(_objectSpread$6({}, defOpts.interpolation), this.options.interpolation);
- }
+ this.canvas = document.createElement('canvas')
+ this.canvas.width = 100
+ this.canvas.height = 80
+ this.canvas.style.width = "100px"
+ this.canvas.style.height = "80px"
+ this.canvas.style.position = 'absolute'
+ this.canvas.style.right = '0px'
+ this.canvas.style.bottom = '0px'
+ document.body.appendChild(this.canvas)
- if (options.keySeparator !== undefined) {
- this.options.userDefinedKeySeparator = options.keySeparator;
- }
+ this.isDrawing = isDrawing
+ this.ctx = this.canvas.getContext('2d')
+ this.ctx.fillStyle="#DFFFFF"
+ this.ctx.strokeStyle="#0ff"
+ this.ctx.lineWidth=0.5
+ if(window.navigator.mediaDevices) {
+ window.navigator.mediaDevices.getUserMedia({video: false, audio: true})
+ .then((stream) => {
+ // console.log('got mic stream', stream)
+ this.stream = stream
+ this.context = new AudioContext()
+ // this.context = new AudioContext()
+ let audio_stream = this.context.createMediaStreamSource(stream)
- if (options.nsSeparator !== undefined) {
- this.options.userDefinedNsSeparator = options.nsSeparator;
- }
+ // console.log(this.context)
+ this.meyda = Meyda.createMeydaAnalyzer({
+ audioContext: this.context,
+ source: audio_stream,
+ featureExtractors: [
+ 'loudness',
+ // 'perceptualSpread',
+ // 'perceptualSharpness',
+ // 'spectralCentroid'
+ ]
+ })
+ })
+ .catch((err) => console.log('ERROR', err))
+ }
+ }
- function createClassOnDemand(ClassOrObject) {
- if (!ClassOrObject) return null;
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
- return ClassOrObject;
+ detectBeat (level) {
+ //console.log(level, this.beat._cutoff)
+ if (level > this.beat._cutoff && level > this.beat.threshold) {
+ this.onBeat()
+ this.beat._cutoff = level *1.2
+ this.beat._framesSinceBeat = 0
+ } else {
+ if (this.beat._framesSinceBeat <= this.beat.holdFrames){
+ this.beat._framesSinceBeat ++;
+ } else {
+ this.beat._cutoff *= this.beat.decay
+ this.beat._cutoff = Math.max( this.beat._cutoff, this.beat.threshold);
}
+ }
+ }
- if (!this.options.isClone) {
- if (this.modules.logger) {
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
- } else {
- baseLogger.init(null, this.options);
- }
-
- var formatter;
-
- if (this.modules.formatter) {
- formatter = this.modules.formatter;
- } else if (typeof Intl !== 'undefined') {
- formatter = Formatter;
- }
+ tick() {
+ if(this.meyda){
+ var features = this.meyda.get()
+ if(features && features !== null){
+ this.vol = features.loudness.total
+ this.detectBeat(this.vol)
+ // reduce loudness array to number of bins
+ const reducer = (accumulator, currentValue) => accumulator + currentValue;
+ let spacing = Math.floor(features.loudness.specific.length/this.bins.length)
+ this.prevBins = this.bins.slice(0)
+ this.bins = this.bins.map((bin, index) => {
+ return features.loudness.specific.slice(index * spacing, (index + 1)*spacing).reduce(reducer)
+ }).map((bin, index) => {
+ // map to specified range
- var lu = new LanguageUtil(this.options);
- this.store = new ResourceStore(this.options.resources, this.options);
- var s = this.services;
- s.logger = baseLogger;
- s.resourceStore = this.store;
- s.languageUtils = lu;
- s.pluralResolver = new PluralResolver(lu, {
- prepend: this.options.pluralSeparator,
- compatibilityJSON: this.options.compatibilityJSON,
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
- });
+ // return (bin * (1.0 - this.smooth) + this.prevBins[index] * this.smooth)
+ return (bin * (1.0 - this.settings[index].smooth) + this.prevBins[index] * this.settings[index].smooth)
+ })
+ // var y = this.canvas.height - scale*this.settings[index].cutoff
+ // this.ctx.beginPath()
+ // this.ctx.moveTo(index*spacing, y)
+ // this.ctx.lineTo((index+1)*spacing, y)
+ // this.ctx.stroke()
+ //
+ // var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff)
+ this.fft = this.bins.map((bin, index) => (
+ // Math.max(0, (bin - this.cutoff) / (this.max - this.cutoff))
+ Math.max(0, (bin - this.settings[index].cutoff)/this.settings[index].scale)
+ ))
+ if(this.isDrawing) this.draw()
+ }
+ }
+ }
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
- s.formatter = createClassOnDemand(formatter);
- s.formatter.init(s, this.options);
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
- }
+ setCutoff (cutoff) {
+ this.cutoff = cutoff
+ this.settings = this.settings.map((el) => {
+ el.cutoff = cutoff
+ return el
+ })
+ }
- s.interpolator = new Interpolator(this.options);
- s.utils = {
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
- };
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
- s.backendConnector.on('*', function (event) {
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
+ setSmooth (smooth) {
+ this.smooth = smooth
+ this.settings = this.settings.map((el) => {
+ el.smooth = smooth
+ return el
+ })
+ }
- _this2.emit.apply(_this2, [event].concat(args));
- });
+ setBins (numBins) {
+ this.bins = Array(numBins).fill(0)
+ this.prevBins = Array(numBins).fill(0)
+ this.fft = Array(numBins).fill(0)
+ this.settings = Array(numBins).fill(0).map(() => ({
+ cutoff: this.cutoff,
+ scale: this.scale,
+ smooth: this.smooth
+ }))
+ // to do: what to do in non-global mode?
+ this.bins.forEach((bin, index) => {
+ window['a' + index] = (scale = 1, offset = 0) => () => (a.fft[index] * scale + offset)
+ })
+ // console.log(this.settings)
+ }
- if (this.modules.languageDetector) {
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
- s.languageDetector.init(s, this.options.detection, this.options);
- }
+ setScale(scale){
+ this.scale = scale
+ this.settings = this.settings.map((el) => {
+ el.scale = scale
+ return el
+ })
+ }
- if (this.modules.i18nFormat) {
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
- if (s.i18nFormat.init) s.i18nFormat.init(this);
- }
+ setMax(max) {
+ this.max = max
+ console.log('set max is deprecated')
+ }
+ hide() {
+ this.isDrawing = false
+ this.canvas.style.display = 'none'
+ }
- this.translator = new Translator(this.services, this.options);
- this.translator.on('*', function (event) {
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
- args[_key2 - 1] = arguments[_key2];
- }
+ show() {
+ this.isDrawing = true
+ this.canvas.style.display = 'block'
- _this2.emit.apply(_this2, [event].concat(args));
- });
- this.modules.external.forEach(function (m) {
- if (m.init) m.init(_this2);
- });
- }
+ }
- this.format = this.options.interpolation.format;
- if (!callback) callback = noop;
+ draw () {
+ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
+ var spacing = this.canvas.width / this.bins.length
+ var scale = this.canvas.height / (this.max * 2)
+ // console.log(this.bins)
+ this.bins.forEach((bin, index) => {
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
- var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
- }
+ var height = bin * scale
- if (!this.services.languageDetector && !this.options.lng) {
- this.logger.warn('init: no languageDetector is used and no lng is defined');
- }
+ this.ctx.fillRect(index * spacing, this.canvas.height - height, spacing, height)
- var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
- storeApi.forEach(function (fcName) {
- _this2[fcName] = function () {
- var _this2$store;
+ // console.log(this.settings[index])
+ var y = this.canvas.height - scale*this.settings[index].cutoff
+ this.ctx.beginPath()
+ this.ctx.moveTo(index*spacing, y)
+ this.ctx.lineTo((index+1)*spacing, y)
+ this.ctx.stroke()
- return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
- };
- });
- var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
- storeApiChained.forEach(function (fcName) {
- _this2[fcName] = function () {
- var _this2$store2;
+ var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff)
+ this.ctx.beginPath()
+ this.ctx.moveTo(index*spacing, yMax)
+ this.ctx.lineTo((index+1)*spacing, yMax)
+ this.ctx.stroke()
+ })
- (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
- return _this2;
- };
- });
- var deferred = defer();
+ /*var y = this.canvas.height - scale*this.cutoff
+ this.ctx.beginPath()
+ this.ctx.moveTo(0, y)
+ this.ctx.lineTo(this.canvas.width, y)
+ this.ctx.stroke()
+ var yMax = this.canvas.height - scale*this.max
+ this.ctx.beginPath()
+ this.ctx.moveTo(0, yMax)
+ this.ctx.lineTo(this.canvas.width, yMax)
+ this.ctx.stroke()*/
+ }
+}
- var load = function load() {
- var finish = function finish(err, t) {
- if (_this2.isInitialized && !_this2.initializedStoreOnce) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');
- _this2.isInitialized = true;
- if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);
+module.exports = Audio
- _this2.emit('initialized', _this2.options);
+},{"meyda":92}],78:[function(require,module,exports){
+// from https://gist.github.com/gre/1650294
- deferred.resolve(t);
- callback(err, t);
- };
+module.exports = {
+ // no easing, no acceleration
+ linear: function (t) { return t },
+ // accelerating from zero velocity
+ easeInQuad: function (t) { return t*t },
+ // decelerating to zero velocity
+ easeOutQuad: function (t) { return t*(2-t) },
+ // acceleration until halfway, then deceleration
+ easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
+ // accelerating from zero velocity
+ easeInCubic: function (t) { return t*t*t },
+ // decelerating to zero velocity
+ easeOutCubic: function (t) { return (--t)*t*t+1 },
+ // acceleration until halfway, then deceleration
+ easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 },
+ // accelerating from zero velocity
+ easeInQuart: function (t) { return t*t*t*t },
+ // decelerating to zero velocity
+ easeOutQuart: function (t) { return 1-(--t)*t*t*t },
+ // acceleration until halfway, then deceleration
+ easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t },
+ // accelerating from zero velocity
+ easeInQuint: function (t) { return t*t*t*t*t },
+ // decelerating to zero velocity
+ easeOutQuint: function (t) { return 1+(--t)*t*t*t*t },
+ // acceleration until halfway, then deceleration
+ easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t },
+ // sin shape
+ sin: function (t) { return (1 + Math.sin(Math.PI*t-Math.PI/2))/2 }
+}
- if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));
+},{}],79:[function(require,module,exports){
+// https://github.com/mikolalysenko/mouse-event
- _this2.changeLanguage(_this2.options.lng, finish);
- };
+'use strict'
- if (this.options.resources || !this.options.initImmediate) {
- load();
- } else {
- setTimeout(load, 0);
+function mouseButtons(ev) {
+ if(typeof ev === 'object') {
+ if('buttons' in ev) {
+ return ev.buttons
+ } else if('which' in ev) {
+ var b = ev.which
+ if(b === 2) {
+ return 4
+ } else if(b === 3) {
+ return 2
+ } else if(b > 0) {
+ return 1<<(b-1)
}
+ } else if('button' in ev) {
+ var b = ev.button
+ if(b === 1) {
+ return 4
+ } else if(b === 2) {
+ return 2
+ } else if(b >= 0) {
+ return 1< 1 && arguments[1] !== undefined ? arguments[1] : noop;
- var usedCallback = callback;
- var usedLng = typeof language === 'string' ? language : this.language;
- if (typeof language === 'function') usedCallback = language;
+function mouseRelativeY(ev) {
+ if(typeof ev === 'object') {
+ if('pageY' in ev) {
+ return ev.pageY
+ }
+ }
+ return 0
+}
+exports.y = mouseRelativeY
- if (!this.options.resources || this.options.partialBundledLanguages) {
- if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
- var toLoad = [];
+},{}],80:[function(require,module,exports){
+// based on https://github.com/mikolalysenko/mouse-change
- var append = function append(lng) {
- if (!lng) return;
+'use strict'
- var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
+module.exports = mouseListen
- lngs.forEach(function (l) {
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
- });
- };
+var mouse = require('./mouse-event.js')
- if (!usedLng) {
- var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
- fallbacks.forEach(function (l) {
- return append(l);
- });
- } else {
- append(usedLng);
- }
+function mouseListen (element, callback) {
+ if (!callback) {
+ callback = element
+ element = window
+ }
- if (this.options.preload) {
- this.options.preload.forEach(function (l) {
- return append(l);
- });
- }
+ var buttonState = 0
+ var x = 0
+ var y = 0
+ var mods = {
+ shift: false,
+ alt: false,
+ control: false,
+ meta: false
+ }
+ var attached = false
- this.services.backendConnector.load(toLoad, this.options.ns, usedCallback);
- } else {
- usedCallback(null);
- }
+ function updateMods (ev) {
+ var changed = false
+ if ('altKey' in ev) {
+ changed = changed || ev.altKey !== mods.alt
+ mods.alt = !!ev.altKey
}
- }, {
- key: "reloadResources",
- value: function reloadResources(lngs, ns, callback) {
- var deferred = defer();
- if (!lngs) lngs = this.languages;
- if (!ns) ns = this.options.ns;
- if (!callback) callback = noop;
- this.services.backendConnector.reload(lngs, ns, function (err) {
- deferred.resolve();
- callback(err);
- });
- return deferred;
+ if ('shiftKey' in ev) {
+ changed = changed || ev.shiftKey !== mods.shift
+ mods.shift = !!ev.shiftKey
}
- }, {
- key: "use",
- value: function use(module) {
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
+ if ('ctrlKey' in ev) {
+ changed = changed || ev.ctrlKey !== mods.control
+ mods.control = !!ev.ctrlKey
+ }
+ if ('metaKey' in ev) {
+ changed = changed || ev.metaKey !== mods.meta
+ mods.meta = !!ev.metaKey
+ }
+ return changed
+ }
- if (module.type === 'backend') {
- this.modules.backend = module;
- }
+ function handleEvent (nextButtons, ev) {
+ var nextX = mouse.x(ev)
+ var nextY = mouse.y(ev)
+ if ('buttons' in ev) {
+ nextButtons = ev.buttons | 0
+ }
+ if (nextButtons !== buttonState ||
+ nextX !== x ||
+ nextY !== y ||
+ updateMods(ev)) {
+ buttonState = nextButtons | 0
+ x = nextX || 0
+ y = nextY || 0
+ callback && callback(buttonState, x, y, mods)
+ }
+ }
- if (module.type === 'logger' || module.log && module.warn && module.error) {
- this.modules.logger = module;
- }
+ function clearState (ev) {
+ handleEvent(0, ev)
+ }
- if (module.type === 'languageDetector') {
- this.modules.languageDetector = module;
- }
+ function handleBlur () {
+ if (buttonState ||
+ x ||
+ y ||
+ mods.shift ||
+ mods.alt ||
+ mods.meta ||
+ mods.control) {
+ x = y = 0
+ buttonState = 0
+ mods.shift = mods.alt = mods.control = mods.meta = false
+ callback && callback(0, 0, 0, mods)
+ }
+ }
- if (module.type === 'i18nFormat') {
- this.modules.i18nFormat = module;
- }
+ function handleMods (ev) {
+ if (updateMods(ev)) {
+ callback && callback(buttonState, x, y, mods)
+ }
+ }
- if (module.type === 'postProcessor') {
- postProcessor.addPostProcessor(module);
- }
+ function handleMouseMove (ev) {
+ if (mouse.buttons(ev) === 0) {
+ handleEvent(0, ev)
+ } else {
+ handleEvent(buttonState, ev)
+ }
+ }
- if (module.type === 'formatter') {
- this.modules.formatter = module;
- }
+ function handleMouseDown (ev) {
+ handleEvent(buttonState | mouse.buttons(ev), ev)
+ }
- if (module.type === '3rdParty') {
- this.modules.external.push(module);
- }
+ function handleMouseUp (ev) {
+ handleEvent(buttonState & ~mouse.buttons(ev), ev)
+ }
- return this;
+ function attachListeners () {
+ if (attached) {
+ return
}
- }, {
- key: "changeLanguage",
- value: function changeLanguage(lng, callback) {
- var _this4 = this;
+ attached = true
- this.isLanguageChangingTo = lng;
- var deferred = defer();
- this.emit('languageChanging', lng);
+ element.addEventListener('mousemove', handleMouseMove)
- var setLngProps = function setLngProps(l) {
- _this4.language = l;
- _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
- _this4.resolvedLanguage = undefined;
- if (['cimode', 'dev'].indexOf(l) > -1) return;
+ element.addEventListener('mousedown', handleMouseDown)
- for (var li = 0; li < _this4.languages.length; li++) {
- var lngInLngs = _this4.languages[li];
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
+ element.addEventListener('mouseup', handleMouseUp)
- if (_this4.store.hasLanguageSomeTranslations(lngInLngs)) {
- _this4.resolvedLanguage = lngInLngs;
- break;
- }
- }
- };
+ element.addEventListener('mouseleave', clearState)
+ element.addEventListener('mouseenter', clearState)
+ element.addEventListener('mouseout', clearState)
+ element.addEventListener('mouseover', clearState)
- var done = function done(err, l) {
- if (l) {
- setLngProps(l);
+ element.addEventListener('blur', handleBlur)
- _this4.translator.changeLanguage(l);
+ element.addEventListener('keyup', handleMods)
+ element.addEventListener('keydown', handleMods)
+ element.addEventListener('keypress', handleMods)
- _this4.isLanguageChangingTo = undefined;
+ if (element !== window) {
+ window.addEventListener('blur', handleBlur)
- _this4.emit('languageChanged', l);
+ window.addEventListener('keyup', handleMods)
+ window.addEventListener('keydown', handleMods)
+ window.addEventListener('keypress', handleMods)
+ }
+ }
- _this4.logger.log('languageChanged', l);
- } else {
- _this4.isLanguageChangingTo = undefined;
- }
+ function detachListeners () {
+ if (!attached) {
+ return
+ }
+ attached = false
- deferred.resolve(function () {
- return _this4.t.apply(_this4, arguments);
- });
- if (callback) callback(err, function () {
- return _this4.t.apply(_this4, arguments);
- });
- };
+ element.removeEventListener('mousemove', handleMouseMove)
- var setLng = function setLng(lngs) {
- if (!lng && !lngs && _this4.services.languageDetector) lngs = [];
- var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
+ element.removeEventListener('mousedown', handleMouseDown)
- if (l) {
- if (!_this4.language) {
- setLngProps(l);
- }
+ element.removeEventListener('mouseup', handleMouseUp)
- if (!_this4.translator.language) _this4.translator.changeLanguage(l);
- if (_this4.services.languageDetector) _this4.services.languageDetector.cacheUserLanguage(l);
- }
+ element.removeEventListener('mouseleave', clearState)
+ element.removeEventListener('mouseenter', clearState)
+ element.removeEventListener('mouseout', clearState)
+ element.removeEventListener('mouseover', clearState)
- _this4.loadResources(l, function (err) {
- done(err, l);
- });
- };
+ element.removeEventListener('blur', handleBlur)
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
- setLng(this.services.languageDetector.detect());
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
- this.services.languageDetector.detect(setLng);
- } else {
- setLng(lng);
- }
+ element.removeEventListener('keyup', handleMods)
+ element.removeEventListener('keydown', handleMods)
+ element.removeEventListener('keypress', handleMods)
- return deferred;
+ if (element !== window) {
+ window.removeEventListener('blur', handleBlur)
+
+ window.removeEventListener('keyup', handleMods)
+ window.removeEventListener('keydown', handleMods)
+ window.removeEventListener('keypress', handleMods)
}
- }, {
- key: "getFixedT",
- value: function getFixedT(lng, ns, keyPrefix) {
- var _this5 = this;
+ }
- var fixedT = function fixedT(key, opts) {
- var options;
+ // Attach listeners
+ attachListeners()
- if (_typeof__default['default'](opts) !== 'object') {
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
- rest[_key3 - 2] = arguments[_key3];
- }
+ var result = {
+ element: element
+ }
- options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
+ Object.defineProperties(result, {
+ enabled: {
+ get: function () { return attached },
+ set: function (f) {
+ if (f) {
+ attachListeners()
} else {
- options = _objectSpread$6({}, opts);
+ detachListeners()
}
+ },
+ enumerable: true
+ },
+ buttons: {
+ get: function () { return buttonState },
+ enumerable: true
+ },
+ x: {
+ get: function () { return x },
+ enumerable: true
+ },
+ y: {
+ get: function () { return y },
+ enumerable: true
+ },
+ mods: {
+ get: function () { return mods },
+ enumerable: true
+ }
+ })
- options.lng = options.lng || fixedT.lng;
- options.lngs = options.lngs || fixedT.lngs;
- options.ns = options.ns || fixedT.ns;
- var keySeparator = _this5.options.keySeparator || '.';
- var resultKey = keyPrefix ? "".concat(keyPrefix).concat(keySeparator).concat(key) : key;
- return _this5.t(resultKey, options);
- };
+ return result
+}
- if (typeof lng === 'string') {
- fixedT.lng = lng;
- } else {
- fixedT.lngs = lng;
- }
+},{"./mouse-event.js":79}],81:[function(require,module,exports){
+// attempt custom evaluation sandbox for hydra functions
+// for now, just avoids polluting the global namespace
+// should probably be replaced with an abstract syntax tree
- fixedT.ns = ns;
- fixedT.keyPrefix = keyPrefix;
- return fixedT;
- }
- }, {
- key: "t",
- value: function t() {
- var _this$translator;
+module.exports = (parent) => {
+ var initialCode = ``
- return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
- }
- }, {
- key: "exists",
- value: function exists() {
- var _this$translator2;
+ var sandbox = createSandbox(initialCode)
- return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
- }
- }, {
- key: "setDefaultNamespace",
- value: function setDefaultNamespace(ns) {
- this.options.defaultNS = ns;
+ var addToContext = (name, object) => {
+ initialCode += `
+ var ${name} = ${object}
+ `
+ sandbox = createSandbox(initialCode)
+ }
+
+
+ return {
+ addToContext: addToContext,
+ eval: (code) => sandbox.eval(code)
+ }
+
+ function createSandbox (initial) {
+ eval(initial)
+ // optional params
+ var localEval = function (code) {
+ eval(code)
}
- }, {
- key: "hasLoadedNamespace",
- value: function hasLoadedNamespace(ns) {
- var _this6 = this;
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ // API/data for end-user
+ return {
+ eval: localEval
+ }
+ }
+}
- if (!this.isInitialized) {
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
- return false;
- }
+},{}],82:[function(require,module,exports){
- if (!this.languages || !this.languages.length) {
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
- return false;
- }
+module.exports = function (options) {
+ return new Promise(function(resolve, reject) {
+ // async function startCapture(displayMediaOptions) {
+ navigator.mediaDevices.getDisplayMedia(options).then((stream) => {
+ const video = document.createElement('video')
+ video.srcObject = stream
+ video.addEventListener('loadedmetadata', () => {
+ video.play()
+ resolve({video: video})
+ })
+ }).catch((err) => reject(err))
+ })
+}
- var lng = this.resolvedLanguage || this.languages[0];
- var fallbackLng = this.options ? this.options.fallbackLng : false;
- var lastLng = this.languages[this.languages.length - 1];
- if (lng.toLowerCase() === 'cimode') return true;
+},{}],83:[function(require,module,exports){
+class VideoRecorder {
+ constructor(stream) {
+ this.mediaSource = new MediaSource()
+ this.stream = stream
- var loadNotPending = function loadNotPending(l, n) {
- var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
+ // testing using a recording as input
+ this.output = document.createElement('video')
+ this.output.autoplay = true
+ this.output.loop = true
- return loadState === -1 || loadState === 2;
- };
+ let self = this
+ this.mediaSource.addEventListener('sourceopen', () => {
+ console.log('MediaSource opened');
+ self.sourceBuffer = self.mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
+ console.log('Source buffer: ', sourceBuffer);
+ })
+ }
- if (options.precheck) {
- var preResult = options.precheck(this, loadNotPending);
- if (preResult !== undefined) return preResult;
- }
+ start() {
+ // let options = {mimeType: 'video/webm'};
- if (this.hasResourceBundle(lng, ns)) return true;
- if (!this.services.backendConnector.backend) return true;
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
- return false;
- }
- }, {
- key: "loadNamespaces",
- value: function loadNamespaces(ns, callback) {
- var _this7 = this;
+// let options = {mimeType: 'video/webm;codecs=h264'};
+ let options = {mimeType: 'video/webm;codecs=vp9'};
- var deferred = defer();
+ this.recordedBlobs = []
+ try {
+ this.mediaRecorder = new MediaRecorder(this.stream, options)
+ } catch (e0) {
+ console.log('Unable to create MediaRecorder with options Object: ', e0)
+ try {
+ options = {mimeType: 'video/webm,codecs=vp9'}
+ this.mediaRecorder = new MediaRecorder(this.stream, options)
+ } catch (e1) {
+ console.log('Unable to create MediaRecorder with options Object: ', e1)
+ try {
+ options = 'video/vp8' // Chrome 47
+ this.mediaRecorder = new MediaRecorder(this.stream, options)
+ } catch (e2) {
+ alert('MediaRecorder is not supported by this browser.\n\n' +
+ 'Try Firefox 29 or later, or Chrome 47 or later, ' +
+ 'with Enable experimental Web Platform features enabled from chrome://flags.')
+ console.error('Exception while creating MediaRecorder:', e2)
+ return
+ }
+ }
+ }
+ console.log('Created MediaRecorder', this.mediaRecorder, 'with options', options);
+ this.mediaRecorder.onstop = this._handleStop.bind(this)
+ this.mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this)
+ this.mediaRecorder.start(100) // collect 100ms of data
+ console.log('MediaRecorder started', this.mediaRecorder)
+ }
- if (!this.options.ns) {
- callback && callback();
- return Promise.resolve();
- }
+
+ stop(){
+ this.mediaRecorder.stop()
+ }
- if (typeof ns === 'string') ns = [ns];
- ns.forEach(function (n) {
- if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
- });
- this.loadResources(function (err) {
- deferred.resolve();
- if (callback) callback(err);
- });
- return deferred;
- }
- }, {
- key: "loadLanguages",
- value: function loadLanguages(lngs, callback) {
- var deferred = defer();
- if (typeof lngs === 'string') lngs = [lngs];
- var preloaded = this.options.preload || [];
- var newLngs = lngs.filter(function (lng) {
- return preloaded.indexOf(lng) < 0;
- });
+ _handleStop() {
+ //const superBuffer = new Blob(recordedBlobs, {type: 'video/webm'})
+ // const blob = new Blob(this.recordedBlobs, {type: 'video/webm;codecs=h264'})
+ const blob = new Blob(this.recordedBlobs, {type: this.mediaRecorder.mimeType})
+ const url = window.URL.createObjectURL(blob)
+ this.output.src = url
- if (!newLngs.length) {
- if (callback) callback();
- return Promise.resolve();
- }
+ const a = document.createElement('a')
+ a.style.display = 'none'
+ a.href = url
+ let d = new Date()
+ a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.webm`
+ document.body.appendChild(a)
+ a.click()
+ setTimeout(() => {
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(url);
+ }, 300);
+ }
- this.options.preload = preloaded.concat(newLngs);
- this.loadResources(function (err) {
- deferred.resolve();
- if (callback) callback(err);
- });
- return deferred;
- }
- }, {
- key: "dir",
- value: function dir(lng) {
- if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
- if (!lng) return 'rtl';
- var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
- return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
+ _handleDataAvailable(event) {
+ if (event.data && event.data.size > 0) {
+ this.recordedBlobs.push(event.data);
}
- }, {
- key: "cloneInstance",
- value: function cloneInstance() {
- var _this8 = this;
+ }
+}
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
+module.exports = VideoRecorder
- var mergedOptions = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, this.options), options), {
- isClone: true
- });
+},{}],84:[function(require,module,exports){
+//const enumerateDevices = require('enumerate-devices')
- var clone = new I18n(mergedOptions);
- var membersToCopy = ['store', 'services', 'language'];
- membersToCopy.forEach(function (m) {
- clone[m] = _this8[m];
- });
- clone.services = _objectSpread$6({}, this.services);
- clone.services.utils = {
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
- };
- clone.translator = new Translator(clone.services, clone.options);
- clone.translator.on('*', function (event) {
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
- args[_key4 - 1] = arguments[_key4];
+module.exports = function (deviceId) {
+ return navigator.mediaDevices.enumerateDevices()
+ .then(devices => devices.filter(devices => devices.kind === 'videoinput'))
+ .then(cameras => {
+ let constraints = { audio: false, video: true}
+ if (cameras[deviceId]) {
+ constraints['video'] = {
+ deviceId: { exact: cameras[deviceId].deviceId }
}
+ }
+ // console.log(cameras)
+ return window.navigator.mediaDevices.getUserMedia(constraints)
+ })
+ .then(stream => {
+ const video = document.createElement('video')
+ video.setAttribute('autoplay', '')
+ video.setAttribute('muted', '')
+ video.setAttribute('playsinline', '')
+ // video.src = window.URL.createObjectURL(stream)
+ video.srcObject = stream
+ return new Promise((resolve, reject) => {
+ video.addEventListener('loadedmetadata', () => {
+ video.play().then(() => resolve({video: video}))
+ })
+ })
+ })
+ .catch(console.log.bind(console))
+}
- clone.emit.apply(clone, [event].concat(args));
- });
- clone.init(mergedOptions, callback);
- clone.translator.options = clone.options;
- clone.translator.backendConnector.services.utils = {
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
- };
- return clone;
- }
- }, {
- key: "toJSON",
- value: function toJSON() {
- return {
- options: this.options,
- store: this.store,
- language: this.language,
- languages: this.languages,
- resolvedLanguage: this.resolvedLanguage
- };
- }
- }]);
+},{}],85:[function(require,module,exports){
+//const transforms = require('./glsl-transforms.js')
- return I18n;
-}(EventEmitter);
+var Output = function ({ regl, precision, label = "", width, height}) {
+ this.regl = regl
+ this.precision = precision
+ this.label = label
+ this.positionBuffer = this.regl.buffer([
+ [-2, 0],
+ [0, -2],
+ [2, 2]
+ ])
-_defineProperty__default['default'](I18n, "createInstance", function () {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var callback = arguments.length > 1 ? arguments[1] : undefined;
- return new I18n(options, callback);
-});
+ this.draw = () => {}
+ this.init()
+ this.pingPongIndex = 0
-var instance = I18n.createInstance();
-instance.createInstance = I18n.createInstance;
+ // for each output, create two fbos for pingponging
+ this.fbos = (Array(2)).fill().map(() => this.regl.framebuffer({
+ color: this.regl.texture({
+ mag: 'nearest',
+ width: width,
+ height: height,
+ format: 'rgba'
+ }),
+ depthStencil: false
+ }))
-module.exports = instance;
+ // array containing render passes
+// this.passes = []
+}
-},{"@babel/runtime/helpers/assertThisInitialized":31,"@babel/runtime/helpers/classCallCheck":32,"@babel/runtime/helpers/createClass":33,"@babel/runtime/helpers/defineProperty":34,"@babel/runtime/helpers/getPrototypeOf":35,"@babel/runtime/helpers/inherits":36,"@babel/runtime/helpers/possibleConstructorReturn":39,"@babel/runtime/helpers/toArray":41,"@babel/runtime/helpers/typeof":42}],83:[function(require,module,exports){
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- })
- }
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
+Output.prototype.resize = function(width, height) {
+ this.fbos.forEach((fbo) => {
+ fbo.resize(width, height)
+ })
+// console.log(this)
}
-},{}],84:[function(require,module,exports){
-(function webpackUniversalModuleDefinition(root, factory) {
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = factory();
- else if(typeof define === 'function' && define.amd)
- define([], factory);
- else if(typeof exports === 'object')
- exports["Meyda"] = factory();
- else
- root["Meyda"] = factory();
-})(window, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/ // The module cache
-/******/ var installedModules = {};
-/******/
-/******/ // The require function
-/******/ function __webpack_require__(moduleId) {
-/******/
-/******/ // Check if module is in cache
-/******/ if(installedModules[moduleId]) {
-/******/ return installedModules[moduleId].exports;
-/******/ }
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = installedModules[moduleId] = {
-/******/ i: moduleId,
-/******/ l: false,
-/******/ exports: {}
-/******/ };
-/******/
-/******/ // Execute the module function
-/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-/******/
-/******/ // Flag the module as loaded
-/******/ module.l = true;
-/******/
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
-/******/
-/******/
-/******/ // expose the modules object (__webpack_modules__)
-/******/ __webpack_require__.m = modules;
-/******/
-/******/ // expose the module cache
-/******/ __webpack_require__.c = installedModules;
-/******/
-/******/ // define getter function for harmony exports
-/******/ __webpack_require__.d = function(exports, name, getter) {
-/******/ if(!__webpack_require__.o(exports, name)) {
-/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
-/******/ }
-/******/ };
-/******/
-/******/ // define __esModule on exports
-/******/ __webpack_require__.r = function(exports) {
-/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
-/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
-/******/ }
-/******/ Object.defineProperty(exports, '__esModule', { value: true });
-/******/ };
-/******/
-/******/ // create a fake namespace object
-/******/ // mode & 1: value is a module id, require it
-/******/ // mode & 2: merge all properties of value into the ns
-/******/ // mode & 4: return value when already ns object
-/******/ // mode & 8|1: behave like require
-/******/ __webpack_require__.t = function(value, mode) {
-/******/ if(mode & 1) value = __webpack_require__(value);
-/******/ if(mode & 8) return value;
-/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
-/******/ var ns = Object.create(null);
-/******/ __webpack_require__.r(ns);
-/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
-/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
-/******/ return ns;
-/******/ };
-/******/
-/******/ // getDefaultExport function for compatibility with non-harmony modules
-/******/ __webpack_require__.n = function(module) {
-/******/ var getter = module && module.__esModule ?
-/******/ function getDefault() { return module['default']; } :
-/******/ function getModuleExports() { return module; };
-/******/ __webpack_require__.d(getter, 'a', getter);
-/******/ return getter;
-/******/ };
-/******/
-/******/ // Object.prototype.hasOwnProperty.call
-/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
-/******/
-/******/ // __webpack_public_path__
-/******/ __webpack_require__.p = "";
-/******/
-/******/
-/******/ // Load entry module and return exports
-/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js");
-/******/ })
-/************************************************************************/
-/******/ ({
-/***/ "./node_modules/assert/assert.js":
-/*!***************************************!*\
- !*** ./node_modules/assert/assert.js ***!
- \***************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+Output.prototype.getCurrent = function () {
+ return this.fbos[this.pingPongIndex]
+}
-"use strict";
-/* WEBPACK VAR INJECTION */(function(global) {
+Output.prototype.getTexture = function () {
+ var index = this.pingPongIndex ? 0 : 1
+ return this.fbos[index]
+}
-// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
-// original notice:
+Output.prototype.init = function () {
+// console.log('clearing')
+ this.transformIndex = 0
+ this.fragHeader = `
+ precision ${this.precision} float;
-/*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-function compare(a, b) {
- if (a === b) {
- return 0;
- }
+ uniform float time;
+ varying vec2 uv;
+ `
- var x = a.length;
- var y = b.length;
+ this.fragBody = ``
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i];
- y = b[i];
- break;
- }
- }
+ this.vert = `
+ precision ${this.precision} float;
+ attribute vec2 position;
+ varying vec2 uv;
- if (x < y) {
- return -1;
+ void main () {
+ uv = position;
+ gl_Position = vec4(2.0 * position - 1.0, 0, 1);
+ }`
+
+ this.attributes = {
+ position: this.positionBuffer
}
- if (y < x) {
- return 1;
+ this.uniforms = {
+ time: this.regl.prop('time'),
+ resolution: this.regl.prop('resolution')
}
- return 0;
+
+ this.frag = `
+ ${this.fragHeader}
+
+ void main () {
+ vec4 c = vec4(0, 0, 0, 0);
+ vec2 st = uv;
+ ${this.fragBody}
+ gl_FragColor = c;
+ }
+ `
+ return this
+}
+
+
+Output.prototype.render = function (passes) {
+ let pass = passes[0]
+ //console.log('pass', pass, this.pingPongIndex)
+ var self = this
+ var uniforms = Object.assign(pass.uniforms, { prevBuffer: () => {
+ //var index = this.pingPongIndex ? 0 : 1
+ // var index = self.pingPong[(passIndex+1)%2]
+ // console.log('ping pong', self.pingPongIndex)
+ return self.fbos[self.pingPongIndex]
+ }
+ })
+
+ self.draw = self.regl({
+ frag: pass.frag,
+ vert: self.vert,
+ attributes: self.attributes,
+ uniforms: uniforms,
+ count: 3,
+ framebuffer: () => {
+ self.pingPongIndex = self.pingPongIndex ? 0 : 1
+ return self.fbos[self.pingPongIndex]
+ }
+ })
}
-function isBuffer(b) {
- if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
- return global.Buffer.isBuffer(b);
- }
- return !!(b != null && b._isBuffer);
+
+
+Output.prototype.tick = function (props) {
+// console.log(props)
+ this.draw(props)
}
-// based on node assert, original notice:
+module.exports = Output
-// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
-//
-// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
-//
-// Originally from narwhal.js (http://narwhaljs.org)
-// Copyright (c) 2009 Thomas Robinson <280north.com>
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the 'Software'), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+},{}],86:[function(require,module,exports){
+module.exports = attributeToProperty
-var util = __webpack_require__(/*! util/ */ "./node_modules/webpack-stream/node_modules/util/util.js");
-var hasOwn = Object.prototype.hasOwnProperty;
-var pSlice = Array.prototype.slice;
-var functionsHaveNames = (function () {
- return function foo() {}.name === 'foo';
-}());
-function pToString (obj) {
- return Object.prototype.toString.call(obj);
+var transform = {
+ 'class': 'className',
+ 'for': 'htmlFor',
+ 'http-equiv': 'httpEquiv'
}
-function isView(arrbuf) {
- if (isBuffer(arrbuf)) {
- return false;
- }
- if (typeof global.ArrayBuffer !== 'function') {
- return false;
- }
- if (typeof ArrayBuffer.isView === 'function') {
- return ArrayBuffer.isView(arrbuf);
- }
- if (!arrbuf) {
- return false;
- }
- if (arrbuf instanceof DataView) {
- return true;
- }
- if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
- return true;
+
+function attributeToProperty (h) {
+ return function (tagName, attrs, children) {
+ for (var attr in attrs) {
+ if (attr in transform) {
+ attrs[transform[attr]] = attrs[attr]
+ delete attrs[attr]
+ }
+ }
+ return h(tagName, attrs, children)
}
- return false;
}
-// 1. The assert module provides functions that throw
-// AssertionError's when particular conditions are not met. The
-// assert module must conform to the following interface.
-var assert = module.exports = ok;
+},{}],87:[function(require,module,exports){
+var attrToProp = require('hyperscript-attribute-to-property')
-// 2. The AssertionError is defined in assert.
-// new assert.AssertionError({ message: message,
-// actual: actual,
-// expected: expected })
+var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4
+var ATTR_KEY = 5, ATTR_KEY_W = 6
+var ATTR_VALUE_W = 7, ATTR_VALUE = 8
+var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10
+var ATTR_EQ = 11, ATTR_BREAK = 12
+var COMMENT = 13
-var regex = /\s*function\s+([^\(\s]*)\s*/;
-// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
-function getName(func) {
- if (!util.isFunction(func)) {
- return;
- }
- if (functionsHaveNames) {
- return func.name;
+module.exports = function (h, opts) {
+ if (!opts) opts = {}
+ var concat = opts.concat || function (a, b) {
+ return String(a) + String(b)
}
- var str = func.toString();
- var match = str.match(regex);
- return match && match[1];
-}
-assert.AssertionError = function AssertionError(options) {
- this.name = 'AssertionError';
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- if (options.message) {
- this.message = options.message;
- this.generatedMessage = false;
- } else {
- this.message = getMessage(this);
- this.generatedMessage = true;
+ if (opts.attrToProp !== false) {
+ h = attrToProp(h)
}
- var stackStartFunction = options.stackStartFunction || fail;
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- } else {
- // non v8 browsers so we can have a stacktrace
- var err = new Error();
- if (err.stack) {
- var out = err.stack;
- // try to strip useless frames
- var fn_name = getName(stackStartFunction);
- var idx = out.indexOf('\n' + fn_name);
- if (idx >= 0) {
- // once we have located the function frame
- // we need to strip out everything before it (and its line)
- var next_line = out.indexOf('\n', idx + 1);
- out = out.substring(next_line + 1);
+ return function (strings) {
+ var state = TEXT, reg = ''
+ var arglen = arguments.length
+ var parts = []
+
+ for (var i = 0; i < strings.length; i++) {
+ if (i < arglen - 1) {
+ var arg = arguments[i+1]
+ var p = parse(strings[i])
+ var xstate = state
+ if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE
+ if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE
+ if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE
+ if (xstate === ATTR) xstate = ATTR_KEY
+ if (xstate === OPEN) {
+ if (reg === '/') {
+ p.push([ OPEN, '/', arg ])
+ reg = ''
+ } else {
+ p.push([ OPEN, arg ])
+ }
+ } else if (xstate === COMMENT && opts.comments) {
+ reg += String(arg)
+ } else if (xstate !== COMMENT) {
+ p.push([ VAR, xstate, arg ])
+ }
+ parts.push.apply(parts, p)
+ } else parts.push.apply(parts, parse(strings[i]))
+ }
+
+ var tree = [null,{},[]]
+ var stack = [[tree,-1]]
+ for (var i = 0; i < parts.length; i++) {
+ var cur = stack[stack.length-1][0]
+ var p = parts[i], s = p[0]
+ if (s === OPEN && /^\//.test(p[1])) {
+ var ix = stack[stack.length-1][1]
+ if (stack.length > 1) {
+ stack.pop()
+ stack[stack.length-1][0][2][ix] = h(
+ cur[0], cur[1], cur[2].length ? cur[2] : undefined
+ )
+ }
+ } else if (s === OPEN) {
+ var c = [p[1],{},[]]
+ cur[2].push(c)
+ stack.push([c,cur[2].length-1])
+ } else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) {
+ var key = ''
+ var copyKey
+ for (; i < parts.length; i++) {
+ if (parts[i][0] === ATTR_KEY) {
+ key = concat(key, parts[i][1])
+ } else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) {
+ if (typeof parts[i][2] === 'object' && !key) {
+ for (copyKey in parts[i][2]) {
+ if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) {
+ cur[1][copyKey] = parts[i][2][copyKey]
+ }
+ }
+ } else {
+ key = concat(key, parts[i][2])
+ }
+ } else break
+ }
+ if (parts[i][0] === ATTR_EQ) i++
+ var j = i
+ for (; i < parts.length; i++) {
+ if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) {
+ if (!cur[1][key]) cur[1][key] = strfn(parts[i][1])
+ else parts[i][1]==="" || (cur[1][key] = concat(cur[1][key], parts[i][1]));
+ } else if (parts[i][0] === VAR
+ && (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) {
+ if (!cur[1][key]) cur[1][key] = strfn(parts[i][2])
+ else parts[i][2]==="" || (cur[1][key] = concat(cur[1][key], parts[i][2]));
+ } else {
+ if (key.length && !cur[1][key] && i === j
+ && (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) {
+ // https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes
+ // empty string is falsy, not well behaved value in browser
+ cur[1][key] = key.toLowerCase()
+ }
+ if (parts[i][0] === CLOSE) {
+ i--
+ }
+ break
+ }
+ }
+ } else if (s === ATTR_KEY) {
+ cur[1][p[1]] = true
+ } else if (s === VAR && p[1] === ATTR_KEY) {
+ cur[1][p[2]] = true
+ } else if (s === CLOSE) {
+ if (selfClosing(cur[0]) && stack.length) {
+ var ix = stack[stack.length-1][1]
+ stack.pop()
+ stack[stack.length-1][0][2][ix] = h(
+ cur[0], cur[1], cur[2].length ? cur[2] : undefined
+ )
+ }
+ } else if (s === VAR && p[1] === TEXT) {
+ if (p[2] === undefined || p[2] === null) p[2] = ''
+ else if (!p[2]) p[2] = concat('', p[2])
+ if (Array.isArray(p[2][0])) {
+ cur[2].push.apply(cur[2], p[2])
+ } else {
+ cur[2].push(p[2])
+ }
+ } else if (s === TEXT) {
+ cur[2].push(p[1])
+ } else if (s === ATTR_EQ || s === ATTR_BREAK) {
+ // no-op
+ } else {
+ throw new Error('unhandled: ' + s)
}
+ }
- this.stack = out;
+ if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) {
+ tree[2].shift()
}
- }
-};
-// assert.AssertionError instanceof Error
-util.inherits(assert.AssertionError, Error);
+ if (tree[2].length > 2
+ || (tree[2].length === 2 && /\S/.test(tree[2][1]))) {
+ if (opts.createFragment) return opts.createFragment(tree[2])
+ throw new Error(
+ 'multiple root elements must be wrapped in an enclosing tag'
+ )
+ }
+ if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string'
+ && Array.isArray(tree[2][0][2])) {
+ tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2])
+ }
+ return tree[2][0]
-function truncate(s, n) {
- if (typeof s === 'string') {
- return s.length < n ? s : s.slice(0, n);
- } else {
- return s;
+ function parse (str) {
+ var res = []
+ if (state === ATTR_VALUE_W) state = ATTR
+ for (var i = 0; i < str.length; i++) {
+ var c = str.charAt(i)
+ if (state === TEXT && c === '<') {
+ if (reg.length) res.push([TEXT, reg])
+ reg = ''
+ state = OPEN
+ } else if (c === '>' && !quot(state) && state !== COMMENT) {
+ if (state === OPEN && reg.length) {
+ res.push([OPEN,reg])
+ } else if (state === ATTR_KEY) {
+ res.push([ATTR_KEY,reg])
+ } else if (state === ATTR_VALUE && reg.length) {
+ res.push([ATTR_VALUE,reg])
+ }
+ res.push([CLOSE])
+ reg = ''
+ state = TEXT
+ } else if (state === COMMENT && /-$/.test(reg) && c === '-') {
+ if (opts.comments) {
+ res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)])
+ }
+ reg = ''
+ state = TEXT
+ } else if (state === OPEN && /^!--$/.test(reg)) {
+ if (opts.comments) {
+ res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ])
+ }
+ reg = c
+ state = COMMENT
+ } else if (state === TEXT || state === COMMENT) {
+ reg += c
+ } else if (state === OPEN && c === '/' && reg.length) {
+ // no-op, self closing tag without a space
+ } else if (state === OPEN && /\s/.test(c)) {
+ if (reg.length) {
+ res.push([OPEN, reg])
+ }
+ reg = ''
+ state = ATTR
+ } else if (state === OPEN) {
+ reg += c
+ } else if (state === ATTR && /[^\s"'=/]/.test(c)) {
+ state = ATTR_KEY
+ reg = c
+ } else if (state === ATTR && /\s/.test(c)) {
+ if (reg.length) res.push([ATTR_KEY,reg])
+ res.push([ATTR_BREAK])
+ } else if (state === ATTR_KEY && /\s/.test(c)) {
+ res.push([ATTR_KEY,reg])
+ reg = ''
+ state = ATTR_KEY_W
+ } else if (state === ATTR_KEY && c === '=') {
+ res.push([ATTR_KEY,reg],[ATTR_EQ])
+ reg = ''
+ state = ATTR_VALUE_W
+ } else if (state === ATTR_KEY) {
+ reg += c
+ } else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') {
+ res.push([ATTR_EQ])
+ state = ATTR_VALUE_W
+ } else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) {
+ res.push([ATTR_BREAK])
+ if (/[\w-]/.test(c)) {
+ reg += c
+ state = ATTR_KEY
+ } else state = ATTR
+ } else if (state === ATTR_VALUE_W && c === '"') {
+ state = ATTR_VALUE_DQ
+ } else if (state === ATTR_VALUE_W && c === "'") {
+ state = ATTR_VALUE_SQ
+ } else if (state === ATTR_VALUE_DQ && c === '"') {
+ res.push([ATTR_VALUE,reg],[ATTR_BREAK])
+ reg = ''
+ state = ATTR
+ } else if (state === ATTR_VALUE_SQ && c === "'") {
+ res.push([ATTR_VALUE,reg],[ATTR_BREAK])
+ reg = ''
+ state = ATTR
+ } else if (state === ATTR_VALUE_W && !/\s/.test(c)) {
+ state = ATTR_VALUE
+ i--
+ } else if (state === ATTR_VALUE && /\s/.test(c)) {
+ res.push([ATTR_VALUE,reg],[ATTR_BREAK])
+ reg = ''
+ state = ATTR
+ } else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ
+ || state === ATTR_VALUE_DQ) {
+ reg += c
+ }
+ }
+ if (state === TEXT && reg.length) {
+ res.push([TEXT,reg])
+ reg = ''
+ } else if (state === ATTR_VALUE && reg.length) {
+ res.push([ATTR_VALUE,reg])
+ reg = ''
+ } else if (state === ATTR_VALUE_DQ && reg.length) {
+ res.push([ATTR_VALUE,reg])
+ reg = ''
+ } else if (state === ATTR_VALUE_SQ && reg.length) {
+ res.push([ATTR_VALUE,reg])
+ reg = ''
+ } else if (state === ATTR_KEY) {
+ res.push([ATTR_KEY,reg])
+ reg = ''
+ }
+ return res
+ }
}
-}
-function inspect(something) {
- if (functionsHaveNames || !util.isFunction(something)) {
- return util.inspect(something);
+
+ function strfn (x) {
+ if (typeof x === 'function') return x
+ else if (typeof x === 'string') return x
+ else if (x && typeof x === 'object') return x
+ else if (x === null || x === undefined) return x
+ else return concat('', x)
}
- var rawname = getName(something);
- var name = rawname ? ': ' + rawname : '';
- return '[Function' + name + ']';
}
-function getMessage(self) {
- return truncate(inspect(self.actual), 128) + ' ' +
- self.operator + ' ' +
- truncate(inspect(self.expected), 128);
+
+function quot (state) {
+ return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ
}
-// At present only the three keys mentioned above are used and
-// understood by the spec. Implementations or sub modules can pass
-// other keys to the AssertionError's constructor - they will be
-// ignored.
+var closeRE = RegExp('^(' + [
+ 'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed',
+ 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param',
+ 'source', 'track', 'wbr', '!--',
+ // SVG TAGS
+ 'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse',
+ 'feBlend', 'feColorMatrix', 'feComposite',
+ 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
+ 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR',
+ 'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology',
+ 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
+ 'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri',
+ 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath',
+ 'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view',
+ 'vkern'
+].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$')
+function selfClosing (tag) { return closeRE.test(tag) }
-// 3. All of the following functions must throw an AssertionError
-// when a corresponding condition is not met, with a message that
-// may be undefined if not provided. All assertion methods provide
-// both the actual and expected values to the assertion error for
-// display purposes.
+},{"hyperscript-attribute-to-property":86}],88:[function(require,module,exports){
+'use strict';
-function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
-}
+var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
+var _createClass = require('@babel/runtime/helpers/createClass');
-// EXTENSION! allows for well behaved errors defined elsewhere.
-assert.fail = fail;
+function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-// 4. Pure assertion tests whether a value is truthy, as determined
-// by !!guard.
-// assert.ok(guard, message_opt);
-// This statement is equivalent to assert.equal(true, !!guard,
-// message_opt);. To test strictly for the value true, use
-// assert.strictEqual(true, guard, message_opt);.
+var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
+var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
-function ok(value, message) {
- if (!value) fail(value, true, message, '==', assert.ok);
+var arr = [];
+var each = arr.forEach;
+var slice = arr.slice;
+function defaults(obj) {
+ each.call(slice.call(arguments, 1), function (source) {
+ if (source) {
+ for (var prop in source) {
+ if (obj[prop] === undefined) obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
}
-assert.ok = ok;
-
-// 5. The equality assertion tests shallow, coercive equality with
-// ==.
-// assert.equal(actual, expected, message_opt);
-assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
-};
+// eslint-disable-next-line no-control-regex
+var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
-// 6. The non-equality assertion tests for whether two objects are not equal
-// with != assert.notEqual(actual, expected, message_opt);
+var serializeCookie = function serializeCookie(name, val, options) {
+ var opt = options || {};
+ opt.path = opt.path || '/';
+ var value = encodeURIComponent(val);
+ var str = name + '=' + value;
-assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, '!=', assert.notEqual);
+ if (opt.maxAge > 0) {
+ var maxAge = opt.maxAge - 0;
+ if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
+ str += '; Max-Age=' + Math.floor(maxAge);
}
-};
-// 7. The equivalence assertion tests a deep equality relation.
-// assert.deepEqual(actual, expected, message_opt);
+ if (opt.domain) {
+ if (!fieldContentRegExp.test(opt.domain)) {
+ throw new TypeError('option domain is invalid');
+ }
-assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
+ str += '; Domain=' + opt.domain;
}
-};
-assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
+ if (opt.path) {
+ if (!fieldContentRegExp.test(opt.path)) {
+ throw new TypeError('option path is invalid');
+ }
+
+ str += '; Path=' + opt.path;
}
-};
-function _deepEqual(actual, expected, strict, memos) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
- } else if (isBuffer(actual) && isBuffer(expected)) {
- return compare(actual, expected) === 0;
+ if (opt.expires) {
+ if (typeof opt.expires.toUTCString !== 'function') {
+ throw new TypeError('option expires is invalid');
+ }
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (util.isDate(actual) && util.isDate(expected)) {
- return actual.getTime() === expected.getTime();
+ str += '; Expires=' + opt.expires.toUTCString();
+ }
- // 7.3 If the expected value is a RegExp object, the actual value is
- // equivalent if it is also a RegExp object with the same source and
- // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
- } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
- return actual.source === expected.source &&
- actual.global === expected.global &&
- actual.multiline === expected.multiline &&
- actual.lastIndex === expected.lastIndex &&
- actual.ignoreCase === expected.ignoreCase;
+ if (opt.httpOnly) str += '; HttpOnly';
+ if (opt.secure) str += '; Secure';
- // 7.4. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if ((actual === null || typeof actual !== 'object') &&
- (expected === null || typeof expected !== 'object')) {
- return strict ? actual === expected : actual == expected;
+ if (opt.sameSite) {
+ var sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
- // If both values are instances of typed arrays, wrap their underlying
- // ArrayBuffers in a Buffer each to increase performance
- // This optimization requires the arrays to have the same type as checked by
- // Object.prototype.toString (aka pToString). Never perform binary
- // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
- // bit patterns are not identical.
- } else if (isView(actual) && isView(expected) &&
- pToString(actual) === pToString(expected) &&
- !(actual instanceof Float32Array ||
- actual instanceof Float64Array)) {
- return compare(new Uint8Array(actual.buffer),
- new Uint8Array(expected.buffer)) === 0;
+ switch (sameSite) {
+ case true:
+ str += '; SameSite=Strict';
+ break;
- // 7.5 For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else if (isBuffer(actual) !== isBuffer(expected)) {
- return false;
- } else {
- memos = memos || {actual: [], expected: []};
+ case 'lax':
+ str += '; SameSite=Lax';
+ break;
- var actualIndex = memos.actual.indexOf(actual);
- if (actualIndex !== -1) {
- if (actualIndex === memos.expected.indexOf(expected)) {
- return true;
- }
- }
+ case 'strict':
+ str += '; SameSite=Strict';
+ break;
- memos.actual.push(actual);
- memos.expected.push(expected);
+ case 'none':
+ str += '; SameSite=None';
+ break;
- return objEquiv(actual, expected, strict, memos);
+ default:
+ throw new TypeError('option sameSite is invalid');
+ }
}
-}
-function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
-}
+ return str;
+};
-function objEquiv(a, b, strict, actualVisitedObjects) {
- if (a === null || a === undefined || b === null || b === undefined)
- return false;
- // if one is a primitive, the other must be same
- if (util.isPrimitive(a) || util.isPrimitive(b))
- return a === b;
- if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
- return false;
- var aIsArgs = isArguments(a);
- var bIsArgs = isArguments(b);
- if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
- return false;
- if (aIsArgs) {
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b, strict);
- }
- var ka = objectKeys(a);
- var kb = objectKeys(b);
- var key, i;
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length !== kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] !== kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
- return false;
- }
- return true;
-}
+var cookie = {
+ create: function create(name, value, minutes, domain) {
+ var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
+ path: '/',
+ sameSite: 'strict'
+ };
-// 8. The non-equivalence assertion tests for any deep inequality.
-// assert.notDeepEqual(actual, expected, message_opt);
+ if (minutes) {
+ cookieOptions.expires = new Date();
+ cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1000);
+ }
-assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
- }
-};
+ if (domain) cookieOptions.domain = domain;
+ document.cookie = serializeCookie(name, encodeURIComponent(value), cookieOptions);
+ },
+ read: function read(name) {
+ var nameEQ = name + '=';
+ var ca = document.cookie.split(';');
-assert.notDeepStrictEqual = notDeepStrictEqual;
-function notDeepStrictEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
- }
-}
+ for (var i = 0; i < ca.length; i++) {
+ var c = ca[i];
+ while (c.charAt(0) === ' ') {
+ c = c.substring(1, c.length);
+ }
-// 9. The strict equality assertion tests strict equality, as determined by ===.
-// assert.strictEqual(actual, expected, message_opt);
+ if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
+ }
-assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, '===', assert.strictEqual);
+ return null;
+ },
+ remove: function remove(name) {
+ this.create(name, '', -1);
}
};
+var cookie$1 = {
+ name: 'cookie',
+ lookup: function lookup(options) {
+ var found;
-// 10. The strict non-equality assertion tests for strict inequality, as
-// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
+ if (options.lookupCookie && typeof document !== 'undefined') {
+ var c = cookie.read(options.lookupCookie);
+ if (c) found = c;
+ }
-assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, '!==', assert.notStrictEqual);
+ return found;
+ },
+ cacheUserLanguage: function cacheUserLanguage(lng, options) {
+ if (options.lookupCookie && typeof document !== 'undefined') {
+ cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
+ }
}
};
-function expectedException(actual, expected) {
- if (!actual || !expected) {
- return false;
- }
+var querystring = {
+ name: 'querystring',
+ lookup: function lookup(options) {
+ var found;
- if (Object.prototype.toString.call(expected) == '[object RegExp]') {
- return expected.test(actual);
- }
+ if (typeof window !== 'undefined') {
+ var query = window.location.search.substring(1);
+ var params = query.split('&');
- try {
- if (actual instanceof expected) {
- return true;
+ for (var i = 0; i < params.length; i++) {
+ var pos = params[i].indexOf('=');
+
+ if (pos > 0) {
+ var key = params[i].substring(0, pos);
+
+ if (key === options.lookupQuerystring) {
+ found = params[i].substring(pos + 1);
+ }
+ }
+ }
}
- } catch (e) {
- // Ignore. The instanceof check doesn't work for arrow functions.
- }
- if (Error.isPrototypeOf(expected)) {
- return false;
+ return found;
}
+};
- return expected.call({}, actual) === true;
-}
+var hasLocalStorageSupport = null;
+
+var localStorageAvailable = function localStorageAvailable() {
+ if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
-function _tryBlock(block) {
- var error;
try {
- block();
+ hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
+ var testKey = 'i18next.translate.boo';
+ window.localStorage.setItem(testKey, 'foo');
+ window.localStorage.removeItem(testKey);
} catch (e) {
- error = e;
- }
- return error;
-}
-
-function _throws(shouldThrow, block, expected, message) {
- var actual;
-
- if (typeof block !== 'function') {
- throw new TypeError('"block" argument must be a function');
+ hasLocalStorageSupport = false;
}
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
+ return hasLocalStorageSupport;
+};
- actual = _tryBlock(block);
+var localStorage = {
+ name: 'localStorage',
+ lookup: function lookup(options) {
+ var found;
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
- (message ? ' ' + message : '.');
+ if (options.lookupLocalStorage && localStorageAvailable()) {
+ var lng = window.localStorage.getItem(options.lookupLocalStorage);
+ if (lng) found = lng;
+ }
- if (shouldThrow && !actual) {
- fail(actual, expected, 'Missing expected exception' + message);
+ return found;
+ },
+ cacheUserLanguage: function cacheUserLanguage(lng, options) {
+ if (options.lookupLocalStorage && localStorageAvailable()) {
+ window.localStorage.setItem(options.lookupLocalStorage, lng);
+ }
}
+};
- var userProvidedMessage = typeof message === 'string';
- var isUnwantedException = !shouldThrow && util.isError(actual);
- var isUnexpectedException = !shouldThrow && actual && !expected;
+var hasSessionStorageSupport = null;
- if ((isUnwantedException &&
- userProvidedMessage &&
- expectedException(actual, expected)) ||
- isUnexpectedException) {
- fail(actual, expected, 'Got unwanted exception' + message);
- }
+var sessionStorageAvailable = function sessionStorageAvailable() {
+ if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
- if ((shouldThrow && actual && expected &&
- !expectedException(actual, expected)) || (!shouldThrow && actual)) {
- throw actual;
+ try {
+ hasSessionStorageSupport = window !== 'undefined' && window.sessionStorage !== null;
+ var testKey = 'i18next.translate.boo';
+ window.sessionStorage.setItem(testKey, 'foo');
+ window.sessionStorage.removeItem(testKey);
+ } catch (e) {
+ hasSessionStorageSupport = false;
}
-}
-
-// 11. Expected to throw an error:
-// assert.throws(block, Error_opt, message_opt);
-assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws(true, block, error, message);
+ return hasSessionStorageSupport;
};
-// EXTENSION! This is annoying to write outside this module.
-assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws(false, block, error, message);
-};
+var sessionStorage = {
+ name: 'sessionStorage',
+ lookup: function lookup(options) {
+ var found;
-assert.ifError = function(err) { if (err) throw err; };
+ if (options.lookupSessionStorage && sessionStorageAvailable()) {
+ var lng = window.sessionStorage.getItem(options.lookupSessionStorage);
+ if (lng) found = lng;
+ }
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- if (hasOwn.call(obj, key)) keys.push(key);
+ return found;
+ },
+ cacheUserLanguage: function cacheUserLanguage(lng, options) {
+ if (options.lookupSessionStorage && sessionStorageAvailable()) {
+ window.sessionStorage.setItem(options.lookupSessionStorage, lng);
+ }
}
- return keys;
};
-/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack-stream/node_modules/webpack/buildin/global.js */ "./node_modules/webpack-stream/node_modules/webpack/buildin/global.js")))
+var navigator$1 = {
+ name: 'navigator',
+ lookup: function lookup(options) {
+ var found = [];
-/***/ }),
+ if (typeof navigator !== 'undefined') {
+ if (navigator.languages) {
+ // chrome only; not an array, so can't use .push.apply instead of iterating
+ for (var i = 0; i < navigator.languages.length; i++) {
+ found.push(navigator.languages[i]);
+ }
+ }
-/***/ "./node_modules/dct/index.js":
-/*!***********************************!*\
- !*** ./node_modules/dct/index.js ***!
- \***********************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+ if (navigator.userLanguage) {
+ found.push(navigator.userLanguage);
+ }
-module.exports = __webpack_require__(/*! ./src/dct.js */ "./node_modules/dct/src/dct.js");
+ if (navigator.language) {
+ found.push(navigator.language);
+ }
+ }
+ return found.length > 0 ? found : undefined;
+ }
+};
-/***/ }),
+var htmlTag = {
+ name: 'htmlTag',
+ lookup: function lookup(options) {
+ var found;
+ var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
-/***/ "./node_modules/dct/src/dct.js":
-/*!*************************************!*\
- !*** ./node_modules/dct/src/dct.js ***!
- \*************************************/
-/*! no static exports found */
-/***/ (function(module, exports) {
+ if (htmlTag && typeof htmlTag.getAttribute === 'function') {
+ found = htmlTag.getAttribute('lang');
+ }
-/*===========================================================================*\
- * Discrete Cosine Transform
- *
- * (c) Vail Systems. Joshua Jung and Ben Bryan. 2015
- *
- * This code is not designed to be highly optimized but as an educational
- * tool to understand the Mel-scale and its related coefficients used in
- * human speech analysis.
-\*===========================================================================*/
-var cosMap = null;
+ return found;
+ }
+};
-// Builds a cosine map for the given input size. This allows multiple input sizes to be memoized automagically
-// if you want to run the DCT over and over.
-var memoizeCosines = function(N) {
- cosMap = cosMap || {};
- cosMap[N] = new Array(N*N);
+var path = {
+ name: 'path',
+ lookup: function lookup(options) {
+ var found;
- var PI_N = Math.PI / N;
+ if (typeof window !== 'undefined') {
+ var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
- for (var k = 0; k < N; k++) {
- for (var n = 0; n < N; n++) {
- cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k);
+ if (language instanceof Array) {
+ if (typeof options.lookupFromPathIndex === 'number') {
+ if (typeof language[options.lookupFromPathIndex] !== 'string') {
+ return undefined;
+ }
+
+ found = language[options.lookupFromPathIndex].replace('/', '');
+ } else {
+ found = language[0].replace('/', '');
+ }
+ }
}
+
+ return found;
}
};
-function dct(signal, scale) {
- var L = signal.length;
- scale = scale || 2;
+var subdomain = {
+ name: 'subdomain',
+ lookup: function lookup(options) {
+ var found;
- if (!cosMap || !cosMap[L]) memoizeCosines(L);
+ if (typeof window !== 'undefined') {
+ var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
- var coefficients = signal.map(function () {return 0;});
+ if (language instanceof Array) {
+ if (typeof options.lookupFromSubdomainIndex === 'number') {
+ found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
+ } else {
+ found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
+ }
+ }
+ }
- return coefficients.map(function (__, ix) {
- return scale * signal.reduce(function (prev, cur, ix_, arr) {
- return prev + (cur * cosMap[L][ix_ + (ix * L)]);
- }, 0);
- });
+ return found;
+ }
};
-module.exports = dct;
-
-
-/***/ }),
+function getDefaults() {
+ return {
+ order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
+ lookupQuerystring: 'lng',
+ lookupCookie: 'i18next',
+ lookupLocalStorage: 'i18nextLng',
+ lookupSessionStorage: 'i18nextLng',
+ // cache user language
+ caches: ['localStorage'],
+ excludeCacheFor: ['cimode'] //cookieMinutes: 10,
+ //cookieDomain: 'myDomain'
-/***/ "./node_modules/fftjs/dist/fft.js":
-/*!****************************************!*\
- !*** ./node_modules/fftjs/dist/fft.js ***!
- \****************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+ };
+}
-"use strict";
+var Browser = /*#__PURE__*/function () {
+ function Browser(services) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ _classCallCheck__default['default'](this, Browser);
-var utils = __webpack_require__(/*! ./utils */ "./node_modules/fftjs/dist/utils.js");
+ this.type = 'languageDetector';
+ this.detectors = {};
+ this.init(services, options);
+ }
-// real to complex fft
-var fft = function fft(signal) {
+ _createClass__default['default'](Browser, [{
+ key: "init",
+ value: function init(services) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ this.services = services;
+ this.options = defaults(options, this.options || {}, getDefaults()); // backwards compatibility
- var complexSignal = {};
+ if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
+ this.i18nOptions = i18nOptions;
+ this.addDetector(cookie$1);
+ this.addDetector(querystring);
+ this.addDetector(localStorage);
+ this.addDetector(sessionStorage);
+ this.addDetector(navigator$1);
+ this.addDetector(htmlTag);
+ this.addDetector(path);
+ this.addDetector(subdomain);
+ }
+ }, {
+ key: "addDetector",
+ value: function addDetector(detector) {
+ this.detectors[detector.name] = detector;
+ }
+ }, {
+ key: "detect",
+ value: function detect(detectionOrder) {
+ var _this = this;
- if (signal.real === undefined || signal.imag === undefined) {
- complexSignal = utils.constructComplexArray(signal);
- } else {
- complexSignal.real = signal.real.slice();
- complexSignal.imag = signal.imag.slice();
- }
+ if (!detectionOrder) detectionOrder = this.options.order;
+ var detected = [];
+ detectionOrder.forEach(function (detectorName) {
+ if (_this.detectors[detectorName]) {
+ var lookup = _this.detectors[detectorName].lookup(_this.options);
- var N = complexSignal.real.length;
- var logN = Math.log2(N);
+ if (lookup && typeof lookup === 'string') lookup = [lookup];
+ if (lookup) detected = detected.concat(lookup);
+ }
+ });
+ if (this.services.languageUtils.getBestMatchFromCodes) return detected; // new i18next v19.5.0
- if (Math.round(logN) != logN) throw new Error('Input size must be a power of 2.');
+ return detected.length > 0 ? detected[0] : null; // a little backward compatibility
+ }
+ }, {
+ key: "cacheUserLanguage",
+ value: function cacheUserLanguage(lng, caches) {
+ var _this2 = this;
- if (complexSignal.real.length != complexSignal.imag.length) {
- throw new Error('Real and imaginary components must have the same length.');
- }
+ if (!caches) caches = this.options.caches;
+ if (!caches) return;
+ if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
+ caches.forEach(function (cacheName) {
+ if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
+ });
+ }
+ }]);
- var bitReversedIndices = utils.bitReverseArray(N);
+ return Browser;
+}();
- // sort array
- var ordered = {
- 'real': [],
- 'imag': []
- };
+Browser.type = 'languageDetector';
- for (var i = 0; i < N; i++) {
- ordered.real[bitReversedIndices[i]] = complexSignal.real[i];
- ordered.imag[bitReversedIndices[i]] = complexSignal.imag[i];
- }
+module.exports = Browser;
- for (var _i = 0; _i < N; _i++) {
- complexSignal.real[_i] = ordered.real[_i];
- complexSignal.imag[_i] = ordered.imag[_i];
- }
- // iterate over the number of stages
- for (var n = 1; n <= logN; n++) {
- var currN = Math.pow(2, n);
+},{"@babel/runtime/helpers/classCallCheck":11,"@babel/runtime/helpers/createClass":12}],89:[function(require,module,exports){
+'use strict';
- // find twiddle factors
- for (var k = 0; k < currN / 2; k++) {
- var twiddle = utils.euler(k, currN);
+var _typeof = require('@babel/runtime/helpers/typeof');
+var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
+var _createClass = require('@babel/runtime/helpers/createClass');
+var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
+var _inherits = require('@babel/runtime/helpers/inherits');
+var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
+var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
+var _defineProperty = require('@babel/runtime/helpers/defineProperty');
+var _toArray = require('@babel/runtime/helpers/toArray');
- // on each block of FT, implement the butterfly diagram
- for (var m = 0; m < N / currN; m++) {
- var currEvenIndex = currN * m + k;
- var currOddIndex = currN * m + k + currN / 2;
+function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
- var currEvenIndexSample = {
- 'real': complexSignal.real[currEvenIndex],
- 'imag': complexSignal.imag[currEvenIndex]
- };
- var currOddIndexSample = {
- 'real': complexSignal.real[currOddIndex],
- 'imag': complexSignal.imag[currOddIndex]
- };
+var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
+var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
+var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
+var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
+var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
+var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
+var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
+var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
+var _toArray__default = /*#__PURE__*/_interopDefaultLegacy(_toArray);
- var odd = utils.multiply(twiddle, currOddIndexSample);
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
- var subtractionResult = utils.subtract(currEvenIndexSample, odd);
- complexSignal.real[currOddIndex] = subtractionResult.real;
- complexSignal.imag[currOddIndex] = subtractionResult.imag;
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
- var additionResult = utils.add(odd, currEvenIndexSample);
- complexSignal.real[currEvenIndex] = additionResult.real;
- complexSignal.imag[currEvenIndex] = additionResult.imag;
- }
- }
+var consoleLogger = {
+ type: 'logger',
+ log: function log(args) {
+ this.output('log', args);
+ },
+ warn: function warn(args) {
+ this.output('warn', args);
+ },
+ error: function error(args) {
+ this.output('error', args);
+ },
+ output: function output(type, args) {
+ if (console && console[type]) console[type].apply(console, args);
}
-
- return complexSignal;
};
-// complex to real ifft
-var ifft = function ifft(signal) {
+var Logger = function () {
+ function Logger(concreteLogger) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- if (signal.real === undefined || signal.imag === undefined) {
- throw new Error("IFFT only accepts a complex input.");
+ _classCallCheck__default['default'](this, Logger);
+
+ this.init(concreteLogger, options);
}
- var N = signal.real.length;
+ _createClass__default['default'](Logger, [{
+ key: "init",
+ value: function init(concreteLogger) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ this.prefix = options.prefix || 'i18next:';
+ this.logger = concreteLogger || consoleLogger;
+ this.options = options;
+ this.debug = options.debug;
+ }
+ }, {
+ key: "setDebug",
+ value: function setDebug(bool) {
+ this.debug = bool;
+ }
+ }, {
+ key: "log",
+ value: function log() {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
- var complexSignal = {
- 'real': [],
- 'imag': []
- };
+ return this.forward(args, 'log', '', true);
+ }
+ }, {
+ key: "warn",
+ value: function warn() {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
- //take complex conjugate in order to be able to use the regular FFT for IFFT
- for (var i = 0; i < N; i++) {
- var currentSample = {
- 'real': signal.real[i],
- 'imag': signal.imag[i]
- };
+ return this.forward(args, 'warn', '', true);
+ }
+ }, {
+ key: "error",
+ value: function error() {
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
- var conjugateSample = utils.conj(currentSample);
- complexSignal.real[i] = conjugateSample.real;
- complexSignal.imag[i] = conjugateSample.imag;
- }
+ return this.forward(args, 'error', '');
+ }
+ }, {
+ key: "deprecate",
+ value: function deprecate() {
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
+ args[_key4] = arguments[_key4];
+ }
- //compute
- var X = fft(complexSignal);
+ return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
+ }
+ }, {
+ key: "forward",
+ value: function forward(args, lvl, prefix, debugOnly) {
+ if (debugOnly && !this.debug) return null;
+ if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
+ return this.logger[lvl](args);
+ }
+ }, {
+ key: "create",
+ value: function create(moduleName) {
+ return new Logger(this.logger, _objectSpread(_objectSpread({}, {
+ prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
+ }), this.options));
+ }
+ }]);
- //normalize
- complexSignal.real = X.real.map(function (val) {
- return val / N;
- });
+ return Logger;
+}();
- complexSignal.imag = X.imag.map(function (val) {
- return val / N;
- });
+var baseLogger = new Logger();
- return complexSignal;
-};
+var EventEmitter = function () {
+ function EventEmitter() {
+ _classCallCheck__default['default'](this, EventEmitter);
-module.exports = {
- fft: fft,
- ifft: ifft
-};
+ this.observers = {};
+ }
-/***/ }),
+ _createClass__default['default'](EventEmitter, [{
+ key: "on",
+ value: function on(events, listener) {
+ var _this = this;
-/***/ "./node_modules/fftjs/dist/utils.js":
-/*!******************************************!*\
- !*** ./node_modules/fftjs/dist/utils.js ***!
- \******************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+ events.split(' ').forEach(function (event) {
+ _this.observers[event] = _this.observers[event] || [];
-"use strict";
+ _this.observers[event].push(listener);
+ });
+ return this;
+ }
+ }, {
+ key: "off",
+ value: function off(event, listener) {
+ if (!this.observers[event]) return;
+ if (!listener) {
+ delete this.observers[event];
+ return;
+ }
-// memoization of the reversal of different lengths.
+ this.observers[event] = this.observers[event].filter(function (l) {
+ return l !== listener;
+ });
+ }
+ }, {
+ key: "emit",
+ value: function emit(event) {
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
-function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+ if (this.observers[event]) {
+ var cloned = [].concat(this.observers[event]);
+ cloned.forEach(function (observer) {
+ observer.apply(void 0, args);
+ });
+ }
-var memoizedReversal = {};
-var memoizedZeroBuffers = {};
+ if (this.observers['*']) {
+ var _cloned = [].concat(this.observers['*']);
-var constructComplexArray = function constructComplexArray(signal) {
- var complexSignal = {};
+ _cloned.forEach(function (observer) {
+ observer.apply(observer, [event].concat(args));
+ });
+ }
+ }
+ }]);
- complexSignal.real = signal.real === undefined ? signal.slice() : signal.real.slice();
+ return EventEmitter;
+}();
- var bufferSize = complexSignal.real.length;
+function defer() {
+ var res;
+ var rej;
+ var promise = new Promise(function (resolve, reject) {
+ res = resolve;
+ rej = reject;
+ });
+ promise.resolve = res;
+ promise.reject = rej;
+ return promise;
+}
+function makeString(object) {
+ if (object == null) return '';
+ return '' + object;
+}
+function copy(a, s, t) {
+ a.forEach(function (m) {
+ if (s[m]) t[m] = s[m];
+ });
+}
- if (memoizedZeroBuffers[bufferSize] === undefined) {
- memoizedZeroBuffers[bufferSize] = Array.apply(null, Array(bufferSize)).map(Number.prototype.valueOf, 0);
+function getLastOfPath(object, path, Empty) {
+ function cleanKey(key) {
+ return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
}
- complexSignal.imag = memoizedZeroBuffers[bufferSize].slice();
-
- return complexSignal;
-};
+ function canNotTraverseDeeper() {
+ return !object || typeof object === 'string';
+ }
-var bitReverseArray = function bitReverseArray(N) {
- if (memoizedReversal[N] === undefined) {
- var maxBinaryLength = (N - 1).toString(2).length; //get the binary length of the largest index.
- var templateBinary = '0'.repeat(maxBinaryLength); //create a template binary of that length.
- var reversed = {};
- for (var n = 0; n < N; n++) {
- var currBinary = n.toString(2); //get binary value of current index.
+ var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
- //prepend zeros from template to current binary. This makes binary values of all indices have the same length.
- currBinary = templateBinary.substr(currBinary.length) + currBinary;
+ while (stack.length > 1) {
+ if (canNotTraverseDeeper()) return {};
+ var key = cleanKey(stack.shift());
+ if (!object[key] && Empty) object[key] = new Empty();
- currBinary = [].concat(_toConsumableArray(currBinary)).reverse().join(''); //reverse
- reversed[n] = parseInt(currBinary, 2); //convert to decimal
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
+ object = object[key];
+ } else {
+ object = {};
}
- memoizedReversal[N] = reversed; //save
}
- return memoizedReversal[N];
-};
-
-// complex multiplication
-var multiply = function multiply(a, b) {
- return {
- 'real': a.real * b.real - a.imag * b.imag,
- 'imag': a.real * b.imag + a.imag * b.real
- };
-};
-// complex addition
-var add = function add(a, b) {
- return {
- 'real': a.real + b.real,
- 'imag': a.imag + b.imag
- };
-};
-
-// complex subtraction
-var subtract = function subtract(a, b) {
+ if (canNotTraverseDeeper()) return {};
return {
- 'real': a.real - b.real,
- 'imag': a.imag - b.imag
- };
-};
-
-// euler's identity e^x = cos(x) + sin(x)
-var euler = function euler(kn, N) {
- var x = -2 * Math.PI * kn / N;
- return { 'real': Math.cos(x), 'imag': Math.sin(x) };
-};
-
-// complex conjugate
-var conj = function conj(a) {
- a.imag *= -1;
- return a;
-};
-
-module.exports = {
- bitReverseArray: bitReverseArray,
- multiply: multiply,
- add: add,
- subtract: subtract,
- euler: euler,
- conj: conj,
- constructComplexArray: constructComplexArray
-};
-
-/***/ }),
-
-/***/ "./node_modules/inherits/inherits_browser.js":
-/*!***************************************************!*\
- !*** ./node_modules/inherits/inherits_browser.js ***!
- \***************************************************/
-/*! no static exports found */
-/***/ (function(module, exports) {
-
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
+ obj: object,
+ k: cleanKey(stack.shift())
};
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
}
+function setPath(object, path, newValue) {
+ var _getLastOfPath = getLastOfPath(object, path, Object),
+ obj = _getLastOfPath.obj,
+ k = _getLastOfPath.k;
-/***/ }),
-
-/***/ "./node_modules/process/browser.js":
-/*!*****************************************!*\
- !*** ./node_modules/process/browser.js ***!
- \*****************************************/
-/*! no static exports found */
-/***/ (function(module, exports) {
+ obj[k] = newValue;
+}
+function pushPath(object, path, newValue, concat) {
+ var _getLastOfPath2 = getLastOfPath(object, path, Object),
+ obj = _getLastOfPath2.obj,
+ k = _getLastOfPath2.k;
-// shim for using process in browser
-var process = module.exports = {};
+ obj[k] = obj[k] || [];
+ if (concat) obj[k] = obj[k].concat(newValue);
+ if (!concat) obj[k].push(newValue);
+}
+function getPath(object, path) {
+ var _getLastOfPath3 = getLastOfPath(object, path),
+ obj = _getLastOfPath3.obj,
+ k = _getLastOfPath3.k;
-// cached from whatever global is present so that test runners that stub it
-// don't break things. But we need to wrap it in a try catch in case it is
-// wrapped in strict mode code which doesn't define any globals. It's inside a
-// function because try/catches deoptimize in certain engines.
+ if (!obj) return undefined;
+ return obj[k];
+}
+function getPathWithDefaults(data, defaultData, key) {
+ var value = getPath(data, key);
-var cachedSetTimeout;
-var cachedClearTimeout;
+ if (value !== undefined) {
+ return value;
+ }
-function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
-}
-function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
+ return getPath(defaultData, key);
}
-(function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
-} ())
-function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
+function deepExtend(target, source, overwrite) {
+ for (var prop in source) {
+ if (prop !== '__proto__' && prop !== 'constructor') {
+ if (prop in target) {
+ if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
+ if (overwrite) target[prop] = source[prop];
+ } else {
+ deepExtend(target[prop], source[prop], overwrite);
}
+ } else {
+ target[prop] = source[prop];
+ }
}
+ }
+ return target;
+}
+function regexEscape(str) {
+ return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
+}
+var _entityMap = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": ''',
+ '/': '/'
+};
+function escape(data) {
+ if (typeof data === 'string') {
+ return data.replace(/[&<>"'\/]/g, function (s) {
+ return _entityMap[s];
+ });
+ }
+ return data;
}
-function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
+var isIE10 = typeof window !== 'undefined' && window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
+var chars = [' ', ',', '?', '!', ';'];
+function looksLikeObjectPath(key, nsSeparator, keySeparator) {
+ nsSeparator = nsSeparator || '';
+ keySeparator = keySeparator || '';
+ var possibleChars = chars.filter(function (c) {
+ return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0;
+ });
+ if (possibleChars.length === 0) return true;
+ var r = new RegExp("(".concat(possibleChars.map(function (c) {
+ return c === '?' ? '\\?' : c;
+ }).join('|'), ")"));
+ var matched = !r.test(key);
+ if (!matched) {
+ var ki = key.indexOf(keySeparator);
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
+ matched = true;
+ }
+ }
+ return matched;
}
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
-function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
-}
+function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
+function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
-}
+function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
-process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
-};
+function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
+function deepFind(obj, path) {
+ var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
+ if (!obj) return undefined;
+ if (obj[path]) return obj[path];
+ var paths = path.split(keySeparator);
+ var current = obj;
-function noop() {}
+ for (var i = 0; i < paths.length; ++i) {
+ if (!current) return undefined;
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-process.prependListener = noop;
-process.prependOnceListener = noop;
+ if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
+ return undefined;
+ }
-process.listeners = function (name) { return [] }
+ if (current[paths[i]] === undefined) {
+ var j = 2;
+ var p = paths.slice(i, i + j).join(keySeparator);
+ var mix = current[p];
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
+ while (mix === undefined && paths.length > i + j) {
+ j++;
+ p = paths.slice(i, i + j).join(keySeparator);
+ mix = current[p];
+ }
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
+ if (mix === undefined) return undefined;
+ if (path.endsWith(p)) {
+ if (typeof mix === 'string') return mix;
+ if (p && typeof mix[p] === 'string') return mix[p];
+ }
-/***/ }),
+ var joinedPath = paths.slice(i + j).join(keySeparator);
+ if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
+ return undefined;
+ }
-/***/ "./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js":
-/*!**********************************************************************************!*\
- !*** ./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js ***!
- \**********************************************************************************/
-/*! no static exports found */
-/***/ (function(module, exports) {
+ current = current[paths[i]];
+ }
-module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
+ return current;
}
-/***/ }),
+var ResourceStore = function (_EventEmitter) {
+ _inherits__default['default'](ResourceStore, _EventEmitter);
-/***/ "./node_modules/webpack-stream/node_modules/util/util.js":
-/*!***************************************************************!*\
- !*** ./node_modules/webpack-stream/node_modules/util/util.js ***!
- \***************************************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+ var _super = _createSuper(ResourceStore);
-/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ function ResourceStore(data) {
+ var _this;
-var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
- function getOwnPropertyDescriptors(obj) {
- var keys = Object.keys(obj);
- var descriptors = {};
- for (var i = 0; i < keys.length; i++) {
- descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
- }
- return descriptors;
- };
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
+ ns: ['translation'],
+ defaultNS: 'translation'
+ };
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
+ _classCallCheck__default['default'](this, ResourceStore);
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
+ _this = _super.call(this);
+
+ if (isIE10) {
+ EventEmitter.call(_assertThisInitialized__default['default'](_this));
}
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
+
+ _this.data = data || {};
+ _this.options = options;
+
+ if (_this.options.keySeparator === undefined) {
+ _this.options.keySeparator = '.';
}
- }
- return str;
-};
+ if (_this.options.ignoreJSONStructure === undefined) {
+ _this.options.ignoreJSONStructure = true;
+ }
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- if (typeof process !== 'undefined' && process.noDeprecation === true) {
- return fn;
+ return _this;
}
- // Allow for deprecating things in the process of starting up.
- if (typeof process === 'undefined') {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
+ _createClass__default['default'](ResourceStore, [{
+ key: "addNamespaces",
+ value: function addNamespaces(ns) {
+ if (this.options.ns.indexOf(ns) < 0) {
+ this.options.ns.push(ns);
+ }
+ }
+ }, {
+ key: "removeNamespaces",
+ value: function removeNamespaces(ns) {
+ var index = this.options.ns.indexOf(ns);
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
+ if (index > -1) {
+ this.options.ns.splice(index, 1);
}
- warned = true;
}
- return fn.apply(this, arguments);
- }
+ }, {
+ key: "getResource",
+ value: function getResource(lng, ns, key) {
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
+ var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
+ var path = [lng, ns];
+ if (key && typeof key !== 'string') path = path.concat(key);
+ if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
- return deprecated;
-};
+ if (lng.indexOf('.') > -1) {
+ path = lng.split('.');
+ }
+ var result = getPath(this.data, path);
+ if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
+ return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
+ }
+ }, {
+ key: "addResource",
+ value: function addResource(lng, ns, key, value) {
+ var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
+ silent: false
+ };
+ var keySeparator = this.options.keySeparator;
+ if (keySeparator === undefined) keySeparator = '.';
+ var path = [lng, ns];
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
+ if (lng.indexOf('.') > -1) {
+ path = lng.split('.');
+ value = ns;
+ ns = path[1];
+ }
+
+ this.addNamespaces(ns);
+ setPath(this.data, path, value);
+ if (!options.silent) this.emit('added', lng, ns, key, value);
+ }
+ }, {
+ key: "addResources",
+ value: function addResources(lng, ns, resources) {
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
+ silent: false
};
- } else {
- debugs[set] = function() {};
+
+ for (var m in resources) {
+ if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
+ silent: true
+ });
+ }
+
+ if (!options.silent) this.emit('added', lng, ns, resources);
}
- }
- return debugs[set];
-};
+ }, {
+ key: "addResourceBundle",
+ value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
+ var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
+ silent: false
+ };
+ var path = [lng, ns];
+ if (lng.indexOf('.') > -1) {
+ path = lng.split('.');
+ deep = resources;
+ resources = ns;
+ ns = path[1];
+ }
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
+ this.addNamespaces(ns);
+ var pack = getPath(this.data, path) || {};
+ if (deep) {
+ deepExtend(pack, resources, overwrite);
+ } else {
+ pack = _objectSpread$1(_objectSpread$1({}, pack), resources);
+ }
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
+ setPath(this.data, path, pack);
+ if (!options.silent) this.emit('added', lng, ns, resources);
+ }
+ }, {
+ key: "removeResourceBundle",
+ value: function removeResourceBundle(lng, ns) {
+ if (this.hasResourceBundle(lng, ns)) {
+ delete this.data[lng][ns];
+ }
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
+ this.removeNamespaces(ns);
+ this.emit('removed', lng, ns);
+ }
+ }, {
+ key: "hasResourceBundle",
+ value: function hasResourceBundle(lng, ns) {
+ return this.getResource(lng, ns) !== undefined;
+ }
+ }, {
+ key: "getResourceBundle",
+ value: function getResourceBundle(lng, ns) {
+ if (!ns) ns = this.options.defaultNS;
+ if (this.options.compatibilityAPI === 'v1') return _objectSpread$1(_objectSpread$1({}, {}), this.getResource(lng, ns));
+ return this.getResource(lng, ns);
+ }
+ }, {
+ key: "getDataByLanguage",
+ value: function getDataByLanguage(lng) {
+ return this.data[lng];
+ }
+ }, {
+ key: "hasLanguageSomeTranslations",
+ value: function hasLanguageSomeTranslations(lng) {
+ var data = this.getDataByLanguage(lng);
+ var n = data && Object.keys(data) || [];
+ return !!n.find(function (v) {
+ return data[v] && Object.keys(data[v]).length > 0;
+ });
+ }
+ }, {
+ key: "toJSON",
+ value: function toJSON() {
+ return this.data;
+ }
+ }]);
+ return ResourceStore;
+}(EventEmitter);
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
+var postProcessor = {
+ processors: {},
+ addPostProcessor: function addPostProcessor(module) {
+ this.processors[module.name] = module;
+ },
+ handle: function handle(processors, value, key, options, translator) {
+ var _this = this;
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
+ processors.forEach(function (processor) {
+ if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
+ });
+ return value;
}
-}
+};
+function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-function stylizeNoColor(str, styleType) {
- return str;
-}
+function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
-function arrayToHash(array) {
- var hash = {};
+function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+var checkedLoadedFor = {};
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
+var Translator = function (_EventEmitter) {
+ _inherits__default['default'](Translator, _EventEmitter);
- return hash;
-}
+ var _super = _createSuper$1(Translator);
+ function Translator(services) {
+ var _this;
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
+ _classCallCheck__default['default'](this, Translator);
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
+ _this = _super.call(this);
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
+ if (isIE10) {
+ EventEmitter.call(_assertThisInitialized__default['default'](_this));
+ }
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
+ copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized__default['default'](_this));
+ _this.options = options;
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
+ if (_this.options.keySeparator === undefined) {
+ _this.options.keySeparator = '.';
}
- }
-
- var base = '', array = false, braces = ['{', '}'];
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
+ _this.logger = baseLogger.create('translator');
+ return _this;
}
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
+ _createClass__default['default'](Translator, [{
+ key: "changeLanguage",
+ value: function changeLanguage(lng) {
+ if (lng) this.language = lng;
+ }
+ }, {
+ key: "exists",
+ value: function exists(key) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
+ interpolation: {}
+ };
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
+ if (key === undefined || key === null) {
+ return false;
+ }
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
+ var resolved = this.resolve(key, options);
+ return resolved && resolved.res !== undefined;
+ }
+ }, {
+ key: "extractFromKey",
+ value: function extractFromKey(key, options) {
+ var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
+ if (nsSeparator === undefined) nsSeparator = ':';
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
+ var namespaces = options.ns || this.options.defaultNS || [];
+ var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
+ var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
+ var m = key.match(this.interpolator.nestingRegexp);
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
+ if (m && m.length > 0) {
+ return {
+ key: key,
+ namespaces: namespaces
+ };
+ }
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
+ var parts = key.split(nsSeparator);
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
+ key = parts.join(keySeparator);
+ }
+
+ if (typeof namespaces === 'string') namespaces = [namespaces];
+ return {
+ key: key,
+ namespaces: namespaces
+ };
}
- }
+ }, {
+ key: "translate",
+ value: function translate(keys, options, lastKey) {
+ var _this2 = this;
- ctx.seen.push(value);
+ if (_typeof__default['default'](options) !== 'object' && this.options.overloadTranslationOptionHandler) {
+ options = this.options.overloadTranslationOptionHandler(arguments);
+ }
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
+ if (!options) options = {};
+ if (keys === undefined || keys === null) return '';
+ if (!Array.isArray(keys)) keys = [String(keys)];
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
- ctx.seen.pop();
+ var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
+ key = _this$extractFromKey.key,
+ namespaces = _this$extractFromKey.namespaces;
- return reduceToSingleString(output, base, braces);
-}
+ var namespace = namespaces[namespaces.length - 1];
+ var lng = options.lng || this.language;
+ var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
+ if (lng && lng.toLowerCase() === 'cimode') {
+ if (appendNamespaceToCIMode) {
+ var nsSeparator = options.nsSeparator || this.options.nsSeparator;
+ return namespace + nsSeparator + key;
+ }
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
+ return key;
+ }
+ var resolved = this.resolve(keys, options);
+ var res = resolved && resolved.res;
+ var resUsedKey = resolved && resolved.usedKey || key;
+ var resExactUsedKey = resolved && resolved.exactUsedKey || key;
+ var resType = Object.prototype.toString.apply(res);
+ var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
+ var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
+ var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
+ var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
+ if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
+ if (!options.returnObjects && !this.options.returnObjects) {
+ if (!this.options.returnedObjectHandler) {
+ this.logger.warn('accessing an object - but returnObjects options is not enabled!');
+ }
+ return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$2(_objectSpread$2({}, options), {}, {
+ ns: namespaces
+ })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
+ }
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
+ if (keySeparator) {
+ var resTypeIsArray = resType === '[object Array]';
+ var copy = resTypeIsArray ? [] : {};
+ var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
+ for (var m in res) {
+ if (Object.prototype.hasOwnProperty.call(res, m)) {
+ var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
+ copy[m] = this.translate(deepKey, _objectSpread$2(_objectSpread$2({}, options), {
+ joinArrays: false,
+ ns: namespaces
+ }));
+ if (copy[m] === deepKey) copy[m] = res[m];
+ }
+ }
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
+ res = copy;
+ }
+ } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
+ res = res.join(joinArrays);
+ if (res) res = this.extendTranslation(res, keys, options, lastKey);
} else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
+ var usedDefault = false;
+ var usedKey = false;
+ var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
+ var hasDefaultValue = Translator.hasDefaultValue(options);
+ var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
+ var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
+
+ if (!this.isValidLookup(res) && hasDefaultValue) {
+ usedDefault = true;
+ res = defaultValue;
}
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
- return name + ': ' + str;
-}
+ if (!this.isValidLookup(res)) {
+ usedKey = true;
+ res = key;
+ }
+ var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
+ var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
+ var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
+ if (usedKey || usedDefault || updateMissing) {
+ this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
+ if (keySeparator) {
+ var fk = this.resolve(key, _objectSpread$2(_objectSpread$2({}, options), {}, {
+ keySeparator: false
+ }));
+ if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
+ }
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
+ var lngs = [];
+ var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
+ if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
+ for (var i = 0; i < fallbackLngs.length; i++) {
+ lngs.push(fallbackLngs[i]);
+ }
+ } else if (this.options.saveMissingTo === 'all') {
+ lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
+ } else {
+ lngs.push(options.lng || this.language);
+ }
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-function isArray(ar) {
- return Array.isArray(ar);
-}
-exports.isArray = isArray;
+ var send = function send(l, k, specificDefaultValue) {
+ var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
+ if (_this2.options.missingKeyHandler) {
+ _this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
+ } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
+ _this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
+ }
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
+ _this2.emit('missingKey', l, namespace, k, res);
+ };
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
+ if (this.options.saveMissing) {
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
+ lngs.forEach(function (language) {
+ _this2.pluralResolver.getSuffixes(language).forEach(function (suffix) {
+ send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
+ });
+ });
+ } else {
+ send(lngs, key, defaultValue);
+ }
+ }
+ }
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
+ res = this.extendTranslation(res, keys, options, resolved, lastKey);
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key);
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(res);
+ }
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
+ return res;
+ }
+ }, {
+ key: "extendTranslation",
+ value: function extendTranslation(res, key, options, resolved, lastKey) {
+ var _this3 = this;
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
+ if (this.i18nFormat && this.i18nFormat.parse) {
+ res = this.i18nFormat.parse(res, options, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
+ resolved: resolved
+ });
+ } else if (!options.skipInterpolation) {
+ if (options.interpolation) this.interpolator.init(_objectSpread$2(_objectSpread$2({}, options), {
+ interpolation: _objectSpread$2(_objectSpread$2({}, this.options.interpolation), options.interpolation)
+ }));
+ var skipOnVariables = typeof res === 'string' && (options.interpolation && options.interpolation.skipOnVariables || this.options.interpolation.skipOnVariables);
+ var nestBef;
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
+ if (skipOnVariables) {
+ var nb = res.match(this.interpolator.nestingRegexp);
+ nestBef = nb && nb.length;
+ }
-function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
+ var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
+ if (this.options.interpolation.defaultVariables) data = _objectSpread$2(_objectSpread$2({}, this.options.interpolation.defaultVariables), data);
+ res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
+ if (skipOnVariables) {
+ var na = res.match(this.interpolator.nestingRegexp);
+ var nestAft = na && na.length;
+ if (nestBef < nestAft) options.nest = false;
+ }
-function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
+ if (options.nest !== false) res = this.interpolator.nest(res, function () {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
-function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
+ if (lastKey && lastKey[0] === args[0] && !options.context) {
+ _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
+ return null;
+ }
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
+ return _this3.translate.apply(_this3, args.concat([key]));
+ }, options);
+ if (options.interpolation) this.interpolator.reset();
+ }
-exports.isBuffer = __webpack_require__(/*! ./support/isBuffer */ "./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js");
+ var postProcess = options.postProcess || this.options.postProcess;
+ var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
+ if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$2({
+ i18nResolved: resolved
+ }, options) : options, this);
+ }
+ return res;
+ }
+ }, {
+ key: "resolve",
+ value: function resolve(keys) {
+ var _this4 = this;
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ var found;
+ var usedKey;
+ var exactUsedKey;
+ var usedLng;
+ var usedNS;
+ if (typeof keys === 'string') keys = [keys];
+ keys.forEach(function (k) {
+ if (_this4.isValidLookup(found)) return;
+ var extracted = _this4.extractFromKey(k, options);
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
+ var key = extracted.key;
+ usedKey = key;
+ var namespaces = extracted.namespaces;
+ if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
+ var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
+ var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
+ var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
+ var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
+ namespaces.forEach(function (ns) {
+ if (_this4.isValidLookup(found)) return;
+ usedNS = ns;
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
+ if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
+ checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
+ _this4.logger.warn("key \"".concat(usedKey, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace \"").concat(usedNS, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
+ }
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = __webpack_require__(/*! inherits */ "./node_modules/inherits/inherits_browser.js");
+ codes.forEach(function (code) {
+ if (_this4.isValidLookup(found)) return;
+ usedLng = code;
+ var finalKeys = [key];
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
+ if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
+ _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
+ } else {
+ var pluralSuffix;
+ if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options);
+ var zeroSuffix = '_zero';
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
-};
+ if (needsPluralHandling) {
+ finalKeys.push(key + pluralSuffix);
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
+ if (needsZeroSuffixLookup) {
+ finalKeys.push(key + zeroSuffix);
+ }
+ }
-var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
+ if (needsContextHandling) {
+ var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
+ finalKeys.push(contextKey);
-exports.promisify = function promisify(original) {
- if (typeof original !== 'function')
- throw new TypeError('The "original" argument must be of type Function');
+ if (needsPluralHandling) {
+ finalKeys.push(contextKey + pluralSuffix);
- if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
- var fn = original[kCustomPromisifiedSymbol];
- if (typeof fn !== 'function') {
- throw new TypeError('The "util.promisify.custom" argument must be of type Function');
- }
- Object.defineProperty(fn, kCustomPromisifiedSymbol, {
- value: fn, enumerable: false, writable: false, configurable: true
- });
- return fn;
- }
+ if (needsZeroSuffixLookup) {
+ finalKeys.push(contextKey + zeroSuffix);
+ }
+ }
+ }
+ }
- function fn() {
- var promiseResolve, promiseReject;
- var promise = new Promise(function (resolve, reject) {
- promiseResolve = resolve;
- promiseReject = reject;
- });
+ var possibleKey;
- var args = [];
- for (var i = 0; i < arguments.length; i++) {
- args.push(arguments[i]);
+ while (possibleKey = finalKeys.pop()) {
+ if (!_this4.isValidLookup(found)) {
+ exactUsedKey = possibleKey;
+ found = _this4.getResource(code, ns, possibleKey, options);
+ }
+ }
+ });
+ });
+ });
+ return {
+ res: found,
+ usedKey: usedKey,
+ exactUsedKey: exactUsedKey,
+ usedLng: usedLng,
+ usedNS: usedNS
+ };
}
- args.push(function (err, value) {
- if (err) {
- promiseReject(err);
- } else {
- promiseResolve(value);
+ }, {
+ key: "isValidLookup",
+ value: function isValidLookup(res) {
+ return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
+ }
+ }, {
+ key: "getResource",
+ value: function getResource(code, ns, key) {
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+ if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
+ return this.resourceStore.getResource(code, ns, key, options);
+ }
+ }], [{
+ key: "hasDefaultValue",
+ value: function hasDefaultValue(options) {
+ var prefix = 'defaultValue';
+
+ for (var option in options) {
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
+ return true;
+ }
}
- });
- try {
- original.apply(this, args);
- } catch (err) {
- promiseReject(err);
+ return false;
}
+ }]);
- return promise;
- }
-
- Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
+ return Translator;
+}(EventEmitter);
- if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
- value: fn, enumerable: false, writable: false, configurable: true
- });
- return Object.defineProperties(
- fn,
- getOwnPropertyDescriptors(original)
- );
+function capitalize(string) {
+ return string.charAt(0).toUpperCase() + string.slice(1);
}
-exports.promisify.custom = kCustomPromisifiedSymbol
-
-function callbackifyOnRejected(reason, cb) {
- // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
- // Because `null` is a special error value in callbacks which means "no error
- // occurred", we error-wrap so the callback consumer can distinguish between
- // "the promise rejected with null" or "the promise fulfilled with undefined".
- if (!reason) {
- var newReason = new Error('Promise was rejected with a falsy value');
- newReason.reason = reason;
- reason = newReason;
- }
- return cb(reason);
-}
+var LanguageUtil = function () {
+ function LanguageUtil(options) {
+ _classCallCheck__default['default'](this, LanguageUtil);
-function callbackify(original) {
- if (typeof original !== 'function') {
- throw new TypeError('The "original" argument must be of type Function');
+ this.options = options;
+ this.supportedLngs = this.options.supportedLngs || false;
+ this.logger = baseLogger.create('languageUtils');
}
- // We DO NOT return the promise as it gives the user a false sense that
- // the promise is actually somehow related to the callback's execution
- // and that the callback throwing will reject the promise.
- function callbackified() {
- var args = [];
- for (var i = 0; i < arguments.length; i++) {
- args.push(arguments[i]);
+ _createClass__default['default'](LanguageUtil, [{
+ key: "getScriptPartFromCode",
+ value: function getScriptPartFromCode(code) {
+ if (!code || code.indexOf('-') < 0) return null;
+ var p = code.split('-');
+ if (p.length === 2) return null;
+ p.pop();
+ if (p[p.length - 1].toLowerCase() === 'x') return null;
+ return this.formatLanguageCode(p.join('-'));
}
-
- var maybeCb = args.pop();
- if (typeof maybeCb !== 'function') {
- throw new TypeError('The last argument must be of type Function');
+ }, {
+ key: "getLanguagePartFromCode",
+ value: function getLanguagePartFromCode(code) {
+ if (!code || code.indexOf('-') < 0) return code;
+ var p = code.split('-');
+ return this.formatLanguageCode(p[0]);
}
- var self = this;
- var cb = function() {
- return maybeCb.apply(self, arguments);
- };
- // In true node style we process the callback on `nextTick` with all the
- // implications (stack, `uncaughtException`, `async_hooks`)
- original.apply(this, args)
- .then(function(ret) { process.nextTick(cb, null, ret) },
- function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });
- }
-
- Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
- Object.defineProperties(callbackified,
- getOwnPropertyDescriptors(original));
- return callbackified;
-}
-exports.callbackify = callbackify;
+ }, {
+ key: "formatLanguageCode",
+ value: function formatLanguageCode(code) {
+ if (typeof code === 'string' && code.indexOf('-') > -1) {
+ var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
+ var p = code.split('-');
-/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "./node_modules/process/browser.js")))
+ if (this.options.lowerCaseLng) {
+ p = p.map(function (part) {
+ return part.toLowerCase();
+ });
+ } else if (p.length === 2) {
+ p[0] = p[0].toLowerCase();
+ p[1] = p[1].toUpperCase();
+ if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
+ } else if (p.length === 3) {
+ p[0] = p[0].toLowerCase();
+ if (p[1].length === 2) p[1] = p[1].toUpperCase();
+ if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
+ if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
+ if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
+ }
-/***/ }),
+ return p.join('-');
+ }
-/***/ "./node_modules/webpack-stream/node_modules/webpack/buildin/global.js":
-/*!***********************************!*\
- !*** (webpack)/buildin/global.js ***!
- \***********************************/
-/*! no static exports found */
-/***/ (function(module, exports) {
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
+ }
+ }, {
+ key: "isSupportedCode",
+ value: function isSupportedCode(code) {
+ if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
+ code = this.getLanguagePartFromCode(code);
+ }
-var g;
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
+ }
+ }, {
+ key: "getBestMatchFromCodes",
+ value: function getBestMatchFromCodes(codes) {
+ var _this = this;
-// This works in non-strict mode
-g = (function() {
- return this;
-})();
+ if (!codes) return null;
+ var found;
+ codes.forEach(function (code) {
+ if (found) return;
-try {
- // This works if eval is allowed (see CSP)
- g = g || new Function("return this")();
-} catch (e) {
- // This works if the window reference is available
- if (typeof window === "object") g = window;
-}
+ var cleanedLng = _this.formatLanguageCode(code);
-// g can still be undefined, but nothing to do about it...
-// We return undefined, instead of nothing here, so it's
-// easier to handle this case. if(!global) { ...}
+ if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;
+ });
-module.exports = g;
+ if (!found && this.options.supportedLngs) {
+ codes.forEach(function (code) {
+ if (found) return;
+ var lngOnly = _this.getLanguagePartFromCode(code);
-/***/ }),
+ if (_this.isSupportedCode(lngOnly)) return found = lngOnly;
+ found = _this.options.supportedLngs.find(function (supportedLng) {
+ if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
+ });
+ });
+ }
-/***/ "./src/extractors/chroma.js":
-/*!**********************************!*\
- !*** ./src/extractors/chroma.js ***!
- \**********************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
+ return found;
+ }
+ }, {
+ key: "getFallbackCodes",
+ value: function getFallbackCodes(fallbacks, code) {
+ if (!fallbacks) return [];
+ if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
+ if (typeof fallbacks === 'string') fallbacks = [fallbacks];
+ if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
+ if (!code) return fallbacks["default"] || [];
+ var found = fallbacks[code];
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
+ if (!found) found = fallbacks["default"];
+ return found || [];
+ }
+ }, {
+ key: "toResolveHierarchy",
+ value: function toResolveHierarchy(code, fallbackCode) {
+ var _this2 = this;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
+ var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
+ var codes = [];
-function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
+ var addCode = function addCode(c) {
+ if (!c) return;
-function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
+ if (_this2.isSupportedCode(c)) {
+ codes.push(c);
+ } else {
+ _this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c));
+ }
+ };
-function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
+ if (typeof code === 'string' && code.indexOf('-') > -1) {
+ if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
+ if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
+ if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
+ } else if (typeof code === 'string') {
+ addCode(this.formatLanguageCode(code));
+ }
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ fallbackCodes.forEach(function (fc) {
+ if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));
+ });
+ return codes;
+ }
+ }]);
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.ampSpectrum) !== 'object') {
- throw new TypeError('Valid ampSpectrum is required to generate chroma');
- }
+ return LanguageUtil;
+}();
- if (_typeof(args.chromaFilterBank) !== 'object') {
- throw new TypeError('Valid chromaFilterBank is required to generate chroma');
+var sets = [{
+ lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
+ nr: [1, 2],
+ fc: 1
+}, {
+ lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
+ nr: [1, 2],
+ fc: 2
+}, {
+ lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
+ nr: [1],
+ fc: 3
+}, {
+ lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
+ nr: [1, 2, 5],
+ fc: 4
+}, {
+ lngs: ['ar'],
+ nr: [0, 1, 2, 3, 11, 100],
+ fc: 5
+}, {
+ lngs: ['cs', 'sk'],
+ nr: [1, 2, 5],
+ fc: 6
+}, {
+ lngs: ['csb', 'pl'],
+ nr: [1, 2, 5],
+ fc: 7
+}, {
+ lngs: ['cy'],
+ nr: [1, 2, 3, 8],
+ fc: 8
+}, {
+ lngs: ['fr'],
+ nr: [1, 2],
+ fc: 9
+}, {
+ lngs: ['ga'],
+ nr: [1, 2, 3, 7, 11],
+ fc: 10
+}, {
+ lngs: ['gd'],
+ nr: [1, 2, 3, 20],
+ fc: 11
+}, {
+ lngs: ['is'],
+ nr: [1, 2],
+ fc: 12
+}, {
+ lngs: ['jv'],
+ nr: [0, 1],
+ fc: 13
+}, {
+ lngs: ['kw'],
+ nr: [1, 2, 3, 4],
+ fc: 14
+}, {
+ lngs: ['lt'],
+ nr: [1, 2, 10],
+ fc: 15
+}, {
+ lngs: ['lv'],
+ nr: [1, 2, 0],
+ fc: 16
+}, {
+ lngs: ['mk'],
+ nr: [1, 2],
+ fc: 17
+}, {
+ lngs: ['mnk'],
+ nr: [0, 1, 2],
+ fc: 18
+}, {
+ lngs: ['mt'],
+ nr: [1, 2, 11, 20],
+ fc: 19
+}, {
+ lngs: ['or'],
+ nr: [2, 1],
+ fc: 2
+}, {
+ lngs: ['ro'],
+ nr: [1, 2, 20],
+ fc: 20
+}, {
+ lngs: ['sl'],
+ nr: [5, 1, 2, 3],
+ fc: 21
+}, {
+ lngs: ['he', 'iw'],
+ nr: [1, 2, 20, 21],
+ fc: 22
+}];
+var _rulesPluralsTypes = {
+ 1: function _(n) {
+ return Number(n > 1);
+ },
+ 2: function _(n) {
+ return Number(n != 1);
+ },
+ 3: function _(n) {
+ return 0;
+ },
+ 4: function _(n) {
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
+ },
+ 5: function _(n) {
+ return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
+ },
+ 6: function _(n) {
+ return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
+ },
+ 7: function _(n) {
+ return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
+ },
+ 8: function _(n) {
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
+ },
+ 9: function _(n) {
+ return Number(n >= 2);
+ },
+ 10: function _(n) {
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
+ },
+ 11: function _(n) {
+ return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
+ },
+ 12: function _(n) {
+ return Number(n % 10 != 1 || n % 100 == 11);
+ },
+ 13: function _(n) {
+ return Number(n !== 0);
+ },
+ 14: function _(n) {
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
+ },
+ 15: function _(n) {
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
+ },
+ 16: function _(n) {
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
+ },
+ 17: function _(n) {
+ return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
+ },
+ 18: function _(n) {
+ return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
+ },
+ 19: function _(n) {
+ return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
+ },
+ 20: function _(n) {
+ return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
+ },
+ 21: function _(n) {
+ return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
+ },
+ 22: function _(n) {
+ return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
}
+};
+var deprecatedJsonVersions = ['v1', 'v2', 'v3'];
+var suffixesOrder = {
+ zero: 0,
+ one: 1,
+ two: 2,
+ few: 3,
+ many: 4,
+ other: 5
+};
- var chromagram = args.chromaFilterBank.map(function (row, i) {
- return args.ampSpectrum.reduce(function (acc, v, j) {
- return acc + v * row[j];
- }, 0);
+function createRules() {
+ var rules = {};
+ sets.forEach(function (set) {
+ set.lngs.forEach(function (l) {
+ rules[l] = {
+ numbers: set.nr,
+ plurals: _rulesPluralsTypes[set.fc]
+ };
+ });
});
- var maxVal = Math.max.apply(Math, _toConsumableArray(chromagram));
- return maxVal ? chromagram.map(function (v) {
- return v / maxVal;
- }) : chromagram;
-});
-
-/***/ }),
-
-/***/ "./src/extractors/energy.js":
-/*!**********************************!*\
- !*** ./src/extractors/energy.js ***!
- \**********************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ return rules;
+}
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var assert__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! assert */ "./node_modules/assert/assert.js");
-/* harmony import */ var assert__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(assert__WEBPACK_IMPORTED_MODULE_0__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+var PluralResolver = function () {
+ function PluralResolver(languageUtils) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ _classCallCheck__default['default'](this, PluralResolver);
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].signal) !== 'object') {
- throw new TypeError();
- }
+ this.languageUtils = languageUtils;
+ this.options = options;
+ this.logger = baseLogger.create('pluralResolver');
- var energy = 0;
+ if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === 'v4') && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
+ this.options.compatibilityJSON = 'v3';
+ this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
+ }
- for (var i = 0; i < arguments[0].signal.length; i++) {
- energy += Math.pow(Math.abs(arguments[0].signal[i]), 2);
+ this.rules = createRules();
}
- return energy;
-});
-
-/***/ }),
-
-/***/ "./src/extractors/extractorUtilities.js":
-/*!**********************************************!*\
- !*** ./src/extractors/extractorUtilities.js ***!
- \**********************************************/
-/*! exports provided: mu */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
-
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mu", function() { return mu; });
-function mu(i, amplitudeSpect) {
- var numerator = 0;
- var denominator = 0;
+ _createClass__default['default'](PluralResolver, [{
+ key: "addRule",
+ value: function addRule(lng, obj) {
+ this.rules[lng] = obj;
+ }
+ }, {
+ key: "getRule",
+ value: function getRule(code) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- for (var k = 0; k < amplitudeSpect.length; k++) {
- numerator += Math.pow(k, i) * Math.abs(amplitudeSpect[k]);
- denominator += amplitudeSpect[k];
- }
+ if (this.shouldUseIntlApi()) {
+ try {
+ return new Intl.PluralRules(code, {
+ type: options.ordinal ? 'ordinal' : 'cardinal'
+ });
+ } catch (_unused) {
+ return;
+ }
+ }
- return numerator / denominator;
-}
+ return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
+ }
+ }, {
+ key: "needsPlural",
+ value: function needsPlural(code) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ var rule = this.getRule(code, options);
-/***/ }),
+ if (this.shouldUseIntlApi()) {
+ return rule && rule.resolvedOptions().pluralCategories.length > 1;
+ }
-/***/ "./src/extractors/loudness.js":
-/*!************************************!*\
- !*** ./src/extractors/loudness.js ***!
- \************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ return rule && rule.numbers.length > 1;
+ }
+ }, {
+ key: "getPluralFormsOfKey",
+ value: function getPluralFormsOfKey(code, key) {
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ return this.getSuffixes(code, options).map(function (suffix) {
+ return "".concat(key).concat(suffix);
+ });
+ }
+ }, {
+ key: "getSuffixes",
+ value: function getSuffixes(code) {
+ var _this = this;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ var rule = this.getRule(code, options);
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.ampSpectrum) !== 'object' || _typeof(args.barkScale) !== 'object') {
- throw new TypeError();
- }
+ if (!rule) {
+ return [];
+ }
- var NUM_BARK_BANDS = 24;
- var specific = new Float32Array(NUM_BARK_BANDS);
- var total = 0;
- var normalisedSpectrum = args.ampSpectrum;
- var bbLimits = new Int32Array(NUM_BARK_BANDS + 1);
- bbLimits[0] = 0;
- var currentBandEnd = args.barkScale[normalisedSpectrum.length - 1] / NUM_BARK_BANDS;
- var currentBand = 1;
+ if (this.shouldUseIntlApi()) {
+ return rule.resolvedOptions().pluralCategories.sort(function (pluralCategory1, pluralCategory2) {
+ return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
+ }).map(function (pluralCategory) {
+ return "".concat(_this.options.prepend).concat(pluralCategory);
+ });
+ }
- for (var i = 0; i < normalisedSpectrum.length; i++) {
- while (args.barkScale[i] > currentBandEnd) {
- bbLimits[currentBand++] = i;
- currentBandEnd = currentBand * args.barkScale[normalisedSpectrum.length - 1] / NUM_BARK_BANDS;
+ return rule.numbers.map(function (number) {
+ return _this.getSuffix(code, number, options);
+ });
}
- }
+ }, {
+ key: "getSuffix",
+ value: function getSuffix(code, count) {
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var rule = this.getRule(code, options);
- bbLimits[NUM_BARK_BANDS] = normalisedSpectrum.length - 1; //process
+ if (rule) {
+ if (this.shouldUseIntlApi()) {
+ return "".concat(this.options.prepend).concat(rule.select(count));
+ }
- for (var _i = 0; _i < NUM_BARK_BANDS; _i++) {
- var sum = 0;
+ return this.getSuffixRetroCompatible(rule, count);
+ }
- for (var j = bbLimits[_i]; j < bbLimits[_i + 1]; j++) {
- sum += normalisedSpectrum[j];
+ this.logger.warn("no plural rule found for: ".concat(code));
+ return '';
}
+ }, {
+ key: "getSuffixRetroCompatible",
+ value: function getSuffixRetroCompatible(rule, count) {
+ var _this2 = this;
- specific[_i] = Math.pow(sum, 0.23);
- } //get total loudness
-
-
- for (var _i2 = 0; _i2 < specific.length; _i2++) {
- total += specific[_i2];
- }
-
- return {
- specific: specific,
- total: total
- };
-});
-
-/***/ }),
+ var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
+ var suffix = rule.numbers[idx];
-/***/ "./src/extractors/mfcc.js":
-/*!********************************!*\
- !*** ./src/extractors/mfcc.js ***!
- \********************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
+ if (suffix === 2) {
+ suffix = 'plural';
+ } else if (suffix === 1) {
+ suffix = '';
+ }
+ }
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _powerSpectrum__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./powerSpectrum */ "./src/extractors/powerSpectrum.js");
-/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./../utilities */ "./src/utilities.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ var returnSuffix = function returnSuffix() {
+ return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
+ };
+ if (this.options.compatibilityJSON === 'v1') {
+ if (suffix === 1) return '';
+ if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
+ return returnSuffix();
+ } else if (this.options.compatibilityJSON === 'v2') {
+ return returnSuffix();
+ } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
+ return returnSuffix();
+ }
+ return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
+ }
+ }, {
+ key: "shouldUseIntlApi",
+ value: function shouldUseIntlApi() {
+ return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
+ }
+ }]);
+ return PluralResolver;
+}();
+function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-var dct = __webpack_require__(/*! dct */ "./node_modules/dct/index.js");
+function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.ampSpectrum) !== 'object') {
- throw new TypeError('Valid ampSpectrum is required to generate MFCC');
- }
+var Interpolator = function () {
+ function Interpolator() {
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- if (_typeof(args.melFilterBank) !== 'object') {
- throw new TypeError('Valid melFilterBank is required to generate MFCC');
- }
+ _classCallCheck__default['default'](this, Interpolator);
- var numberOfMFCCCoefficients = Math.min(40, Math.max(1, args.numberOfMFCCCoefficients || 13)); // Tutorial from:
- // http://practicalcryptography.com/miscellaneous/machine-learning
- // /guide-mel-frequency-cepstral-coefficients-mfccs/
+ this.logger = baseLogger.create('interpolator');
+ this.options = options;
- var powSpec = Object(_powerSpectrum__WEBPACK_IMPORTED_MODULE_0__["default"])(args);
- var numFilters = args.melFilterBank.length;
- var filtered = Array(numFilters);
+ this.format = options.interpolation && options.interpolation.format || function (value) {
+ return value;
+ };
- if (numFilters < numberOfMFCCCoefficients) {
- throw new Error("Insufficient filter bank for requested number of coefficients");
+ this.init(options);
}
- var loggedMelBands = new Float32Array(numFilters);
-
- for (var i = 0; i < loggedMelBands.length; i++) {
- filtered[i] = new Float32Array(args.bufferSize / 2);
- loggedMelBands[i] = 0;
-
- for (var j = 0; j < args.bufferSize / 2; j++) {
- //point-wise multiplication between power spectrum and filterbanks.
- filtered[i][j] = args.melFilterBank[i][j] * powSpec[j]; //summing up all of the coefficients into one array
-
- loggedMelBands[i] += filtered[i][j];
- } //log each coefficient.
-
-
- loggedMelBands[i] = Math.log(loggedMelBands[i] + 1);
- } //dct
-
-
- var loggedMelBandsArray = Array.prototype.slice.call(loggedMelBands);
- var mfccs = dct(loggedMelBandsArray).slice(0, numberOfMFCCCoefficients);
- return mfccs;
-});
-
-/***/ }),
-
-/***/ "./src/extractors/perceptualSharpness.js":
-/*!***********************************************!*\
- !*** ./src/extractors/perceptualSharpness.js ***!
- \***********************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
-
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _loudness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loudness */ "./src/extractors/loudness.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ _createClass__default['default'](Interpolator, [{
+ key: "init",
+ value: function init() {
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ if (!options.interpolation) options.interpolation = {
+ escapeValue: true
+ };
+ var iOpts = options.interpolation;
+ this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
+ this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
+ this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
+ this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
+ this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
+ this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
+ this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
+ this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
+ this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
+ this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
+ this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
+ this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
+ this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
+ this.resetRegExp();
+ }
+ }, {
+ key: "reset",
+ value: function reset() {
+ if (this.options) this.init(this.options);
+ }
+ }, {
+ key: "resetRegExp",
+ value: function resetRegExp() {
+ var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
+ this.regexp = new RegExp(regexpStr, 'g');
+ var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
+ this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
+ var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
+ this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
+ }
+ }, {
+ key: "interpolate",
+ value: function interpolate(str, data, lng, options) {
+ var _this = this;
+ var match;
+ var value;
+ var replaces;
+ var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].signal) !== 'object') {
- throw new TypeError();
- }
+ function regexSafe(val) {
+ return val.replace(/\$/g, '$$$$');
+ }
- var loudnessValue = Object(_loudness__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments[0]);
- var spec = loudnessValue.specific;
- var output = 0;
+ var handleFormat = function handleFormat(key) {
+ if (key.indexOf(_this.formatSeparator) < 0) {
+ var path = getPathWithDefaults(data, defaultData, key);
+ return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
+ interpolationkey: key
+ })) : path;
+ }
- for (var i = 0; i < spec.length; i++) {
- if (i < 15) {
- output += (i + 1) * spec[i + 1];
- } else {
- output += 0.066 * Math.exp(0.171 * (i + 1));
- }
- }
+ var p = key.split(_this.formatSeparator);
+ var k = p.shift().trim();
+ var f = p.join(_this.formatSeparator).trim();
+ return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
+ interpolationkey: k
+ }));
+ };
- output *= 0.11 / loudnessValue.total;
- return output;
-});
+ this.resetRegExp();
+ var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
+ var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables || this.options.interpolation.skipOnVariables;
+ var todos = [{
+ regex: this.regexpUnescape,
+ safeValue: function safeValue(val) {
+ return regexSafe(val);
+ }
+ }, {
+ regex: this.regexp,
+ safeValue: function safeValue(val) {
+ return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
+ }
+ }];
+ todos.forEach(function (todo) {
+ replaces = 0;
-/***/ }),
+ while (match = todo.regex.exec(str)) {
+ value = handleFormat(match[1].trim());
-/***/ "./src/extractors/perceptualSpread.js":
-/*!********************************************!*\
- !*** ./src/extractors/perceptualSpread.js ***!
- \********************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (value === undefined) {
+ if (typeof missingInterpolationHandler === 'function') {
+ var temp = missingInterpolationHandler(str, match, options);
+ value = typeof temp === 'string' ? temp : '';
+ } else if (skipOnVariables) {
+ value = match[0];
+ continue;
+ } else {
+ _this.logger.warn("missed to pass in variable ".concat(match[1], " for interpolating ").concat(str));
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _loudness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loudness */ "./src/extractors/loudness.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ value = '';
+ }
+ } else if (typeof value !== 'string' && !_this.useRawValueToEscape) {
+ value = makeString(value);
+ }
+ var safeValue = todo.safeValue(value);
+ str = str.replace(match[0], safeValue);
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].signal) !== 'object') {
- throw new TypeError();
- }
+ if (skipOnVariables) {
+ todo.regex.lastIndex += safeValue.length;
+ todo.regex.lastIndex -= match[0].length;
+ } else {
+ todo.regex.lastIndex = 0;
+ }
- var loudnessValue = Object(_loudness__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments[0]);
- var max = 0;
+ replaces++;
- for (var i = 0; i < loudnessValue.specific.length; i++) {
- if (loudnessValue.specific[i] > max) {
- max = loudnessValue.specific[i];
+ if (replaces >= _this.maxReplaces) {
+ break;
+ }
+ }
+ });
+ return str;
}
- }
+ }, {
+ key: "nest",
+ value: function nest(str, fc) {
+ var _this2 = this;
- var spread = Math.pow((loudnessValue.total - max) / loudnessValue.total, 2);
- return spread;
-});
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var match;
+ var value;
-/***/ }),
+ var clonedOptions = _objectSpread$3({}, options);
-/***/ "./src/extractors/powerSpectrum.js":
-/*!*****************************************!*\
- !*** ./src/extractors/powerSpectrum.js ***!
- \*****************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ clonedOptions.applyPostProcessor = false;
+ delete clonedOptions.defaultValue;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ function handleHasOptions(key, inheritedOptions) {
+ var sep = this.nestingOptionsSeparator;
+ if (key.indexOf(sep) < 0) return key;
+ var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
+ var optionsString = "{".concat(c[1]);
+ key = c[0];
+ optionsString = this.interpolate(optionsString, clonedOptions);
+ optionsString = optionsString.replace(/'/g, '"');
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].ampSpectrum) !== 'object') {
- throw new TypeError();
- }
+ try {
+ clonedOptions = JSON.parse(optionsString);
+ if (inheritedOptions) clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions);
+ } catch (e) {
+ this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
+ return "".concat(key).concat(sep).concat(optionsString);
+ }
- var powerSpectrum = new Float32Array(arguments[0].ampSpectrum.length);
+ delete clonedOptions.defaultValue;
+ return key;
+ }
- for (var i = 0; i < powerSpectrum.length; i++) {
- powerSpectrum[i] = Math.pow(arguments[0].ampSpectrum[i], 2);
- }
+ while (match = this.nestingRegexp.exec(str)) {
+ var formatters = [];
+ var doReduce = false;
- return powerSpectrum;
-});
+ if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
+ var r = match[1].split(this.formatSeparator).map(function (elem) {
+ return elem.trim();
+ });
+ match[1] = r.shift();
+ formatters = r;
+ doReduce = true;
+ }
-/***/ }),
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
+ if (value && match[0] === str && typeof value !== 'string') return value;
+ if (typeof value !== 'string') value = makeString(value);
-/***/ "./src/extractors/rms.js":
-/*!*******************************!*\
- !*** ./src/extractors/rms.js ***!
- \*******************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (!value) {
+ this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
+ value = '';
+ }
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ if (doReduce) {
+ value = formatters.reduce(function (v, f) {
+ return _this2.format(v, f, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, {
+ interpolationkey: match[1].trim()
+ }));
+ }, value.trim());
+ }
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.signal) !== 'object') {
- throw new TypeError();
- }
+ str = str.replace(match[0], value);
+ this.regexp.lastIndex = 0;
+ }
- var rms = 0;
+ return str;
+ }
+ }]);
- for (var i = 0; i < args.signal.length; i++) {
- rms += Math.pow(args.signal[i], 2);
- }
+ return Interpolator;
+}();
- rms = rms / args.signal.length;
- rms = Math.sqrt(rms);
- return rms;
-});
+function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-/***/ }),
+function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-/***/ "./src/extractors/spectralCentroid.js":
-/*!********************************************!*\
- !*** ./src/extractors/spectralCentroid.js ***!
- \********************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+function parseFormatStr(formatStr) {
+ var formatName = formatStr.toLowerCase().trim();
+ var formatOptions = {};
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ if (formatStr.indexOf('(') > -1) {
+ var p = formatStr.split('(');
+ formatName = p[0].toLowerCase().trim();
+ var optStr = p[1].substring(0, p[1].length - 1);
+ if (formatName === 'currency' && optStr.indexOf(':') < 0) {
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
+ } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
+ } else {
+ var opts = optStr.split(';');
+ opts.forEach(function (opt) {
+ if (!opt) return;
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].ampSpectrum) !== 'object') {
- throw new TypeError();
- }
+ var _opt$split = opt.split(':'),
+ _opt$split2 = _toArray__default['default'](_opt$split),
+ key = _opt$split2[0],
+ rest = _opt$split2.slice(1);
- return Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, arguments[0].ampSpectrum);
-});
+ var val = rest.join(':');
+ if (val.trim() === 'false') formatOptions[key.trim()] = false;
+ if (val.trim() === 'true') formatOptions[key.trim()] = true;
+ if (!isNaN(val.trim())) formatOptions[key.trim()] = parseInt(val.trim(), 10);
+ if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val.trim();
+ });
+ }
+ }
-/***/ }),
+ return {
+ formatName: formatName,
+ formatOptions: formatOptions
+ };
+}
-/***/ "./src/extractors/spectralFlatness.js":
-/*!********************************************!*\
- !*** ./src/extractors/spectralFlatness.js ***!
- \********************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+var Formatter = function () {
+ function Formatter() {
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ _classCallCheck__default['default'](this, Formatter);
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].ampSpectrum) !== 'object') {
- throw new TypeError();
+ this.logger = baseLogger.create('formatter');
+ this.options = options;
+ this.formats = {
+ number: function number(val, lng, options) {
+ return new Intl.NumberFormat(lng, options).format(val);
+ },
+ currency: function currency(val, lng, options) {
+ return new Intl.NumberFormat(lng, _objectSpread$4(_objectSpread$4({}, options), {}, {
+ style: 'currency'
+ })).format(val);
+ },
+ datetime: function datetime(val, lng, options) {
+ return new Intl.DateTimeFormat(lng, _objectSpread$4({}, options)).format(val);
+ },
+ relativetime: function relativetime(val, lng, options) {
+ return new Intl.RelativeTimeFormat(lng, _objectSpread$4({}, options)).format(val, options.range || 'day');
+ },
+ list: function list(val, lng, options) {
+ return new Intl.ListFormat(lng, _objectSpread$4({}, options)).format(val);
+ }
+ };
+ this.init(options);
}
- var numerator = 0;
- var denominator = 0;
-
- for (var i = 0; i < arguments[0].ampSpectrum.length; i++) {
- numerator += Math.log(arguments[0].ampSpectrum[i]);
- denominator += arguments[0].ampSpectrum[i];
- }
+ _createClass__default['default'](Formatter, [{
+ key: "init",
+ value: function init(services) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
+ interpolation: {}
+ };
+ var iOpts = options.interpolation;
+ this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
+ }
+ }, {
+ key: "add",
+ value: function add(name, fc) {
+ this.formats[name] = fc;
+ }
+ }, {
+ key: "format",
+ value: function format(value, _format, lng, options) {
+ var _this = this;
- return Math.exp(numerator / arguments[0].ampSpectrum.length) * arguments[0].ampSpectrum.length / denominator;
-});
+ var formats = _format.split(this.formatSeparator);
-/***/ }),
+ var result = formats.reduce(function (mem, f) {
+ var _parseFormatStr = parseFormatStr(f),
+ formatName = _parseFormatStr.formatName,
+ formatOptions = _parseFormatStr.formatOptions;
-/***/ "./src/extractors/spectralFlux.js":
-/*!****************************************!*\
- !*** ./src/extractors/spectralFlux.js ***!
- \****************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (_this.formats[formatName]) {
+ var formatted = mem;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ try {
+ var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
+ var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
+ formatted = _this.formats[formatName](mem, l, _objectSpread$4(_objectSpread$4(_objectSpread$4({}, formatOptions), options), valOptions));
+ } catch (error) {
+ _this.logger.warn(error);
+ }
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.signal) !== 'object' || _typeof(args.previousSignal) != 'object') {
- throw new TypeError();
- }
+ return formatted;
+ } else {
+ _this.logger.warn("there was no format function for ".concat(formatName));
+ }
- var sf = 0;
+ return mem;
+ }, value);
+ return result;
+ }
+ }]);
- for (var i = -(args.bufferSize / 2); i < signal.length / 2 - 1; i++) {
- x = Math.abs(args.signal[i]) - Math.abs(args.previousSignal[i]);
- sf += (x + Math.abs(x)) / 2;
- }
+ return Formatter;
+}();
- return sf;
-});
+function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-/***/ }),
+function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-/***/ "./src/extractors/spectralKurtosis.js":
-/*!********************************************!*\
- !*** ./src/extractors/spectralKurtosis.js ***!
- \********************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+function remove(arr, what) {
+ var found = arr.indexOf(what);
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].ampSpectrum) !== 'object') {
- throw new TypeError();
+ while (found !== -1) {
+ arr.splice(found, 1);
+ found = arr.indexOf(what);
}
+}
- var ampspec = arguments[0].ampSpectrum;
- var mu1 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, ampspec);
- var mu2 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, ampspec);
- var mu3 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3, ampspec);
- var mu4 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(4, ampspec);
- var numerator = -3 * Math.pow(mu1, 4) + 6 * mu1 * mu2 - 4 * mu1 * mu3 + mu4;
- var denominator = Math.pow(Math.sqrt(mu2 - Math.pow(mu1, 2)), 4);
- return numerator / denominator;
-});
+var Connector = function (_EventEmitter) {
+ _inherits__default['default'](Connector, _EventEmitter);
-/***/ }),
+ var _super = _createSuper$2(Connector);
-/***/ "./src/extractors/spectralRolloff.js":
-/*!*******************************************!*\
- !*** ./src/extractors/spectralRolloff.js ***!
- \*******************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ function Connector(backend, store, services) {
+ var _this;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].ampSpectrum) !== 'object') {
- throw new TypeError();
- }
+ _classCallCheck__default['default'](this, Connector);
- var ampspec = arguments[0].ampSpectrum; //calculate nyquist bin
+ _this = _super.call(this);
- var nyqBin = arguments[0].sampleRate / (2 * (ampspec.length - 1));
- var ec = 0;
+ if (isIE10) {
+ EventEmitter.call(_assertThisInitialized__default['default'](_this));
+ }
- for (var i = 0; i < ampspec.length; i++) {
- ec += ampspec[i];
- }
+ _this.backend = backend;
+ _this.store = store;
+ _this.services = services;
+ _this.languageUtils = services.languageUtils;
+ _this.options = options;
+ _this.logger = baseLogger.create('backendConnector');
+ _this.state = {};
+ _this.queue = [];
- var threshold = 0.99 * ec;
- var n = ampspec.length - 1;
+ if (_this.backend && _this.backend.init) {
+ _this.backend.init(services, options.backend, options);
+ }
- while (ec > threshold && n >= 0) {
- ec -= ampspec[n];
- --n;
+ return _this;
}
- return (n + 1) * nyqBin;
-});
+ _createClass__default['default'](Connector, [{
+ key: "queueLoad",
+ value: function queueLoad(languages, namespaces, options, callback) {
+ var _this2 = this;
-/***/ }),
+ var toLoad = [];
+ var pending = [];
+ var toLoadLanguages = [];
+ var toLoadNamespaces = [];
+ languages.forEach(function (lng) {
+ var hasAllNamespaces = true;
+ namespaces.forEach(function (ns) {
+ var name = "".concat(lng, "|").concat(ns);
-/***/ "./src/extractors/spectralSkewness.js":
-/*!********************************************!*\
- !*** ./src/extractors/spectralSkewness.js ***!
- \********************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
+ _this2.state[name] = 2;
+ } else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
+ if (pending.indexOf(name) < 0) pending.push(name);
+ } else {
+ _this2.state[name] = 1;
+ hasAllNamespaces = false;
+ if (pending.indexOf(name) < 0) pending.push(name);
+ if (toLoad.indexOf(name) < 0) toLoad.push(name);
+ if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns);
+ }
+ });
+ if (!hasAllNamespaces) toLoadLanguages.push(lng);
+ });
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ if (toLoad.length || pending.length) {
+ this.queue.push({
+ pending: pending,
+ loaded: {},
+ errors: [],
+ callback: callback
+ });
+ }
+ return {
+ toLoad: toLoad,
+ pending: pending,
+ toLoadLanguages: toLoadLanguages,
+ toLoadNamespaces: toLoadNamespaces
+ };
+ }
+ }, {
+ key: "loaded",
+ value: function loaded(name, err, data) {
+ var s = name.split('|');
+ var lng = s[0];
+ var ns = s[1];
+ if (err) this.emit('failedLoading', lng, ns, err);
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.ampSpectrum) !== 'object') {
- throw new TypeError();
- }
+ if (data) {
+ this.store.addResourceBundle(lng, ns, data);
+ }
- var mu1 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, args.ampSpectrum);
- var mu2 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, args.ampSpectrum);
- var mu3 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3, args.ampSpectrum);
- var numerator = 2 * Math.pow(mu1, 3) - 3 * mu1 * mu2 + mu3;
- var denominator = Math.pow(Math.sqrt(mu2 - Math.pow(mu1, 2)), 3);
- return numerator / denominator;
-});
+ this.state[name] = err ? -1 : 2;
+ var loaded = {};
+ this.queue.forEach(function (q) {
+ pushPath(q.loaded, [lng], ns);
+ remove(q.pending, name);
+ if (err) q.errors.push(err);
-/***/ }),
+ if (q.pending.length === 0 && !q.done) {
+ Object.keys(q.loaded).forEach(function (l) {
+ if (!loaded[l]) loaded[l] = [];
-/***/ "./src/extractors/spectralSlope.js":
-/*!*****************************************!*\
- !*** ./src/extractors/spectralSlope.js ***!
- \*****************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (q.loaded[l].length) {
+ q.loaded[l].forEach(function (ns) {
+ if (loaded[l].indexOf(ns) < 0) loaded[l].push(ns);
+ });
+ }
+ });
+ q.done = true;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ if (q.errors.length) {
+ q.callback(q.errors);
+ } else {
+ q.callback();
+ }
+ }
+ });
+ this.emit('loaded', loaded);
+ this.queue = this.queue.filter(function (q) {
+ return !q.done;
+ });
+ }
+ }, {
+ key: "read",
+ value: function read(lng, ns, fcName) {
+ var _this3 = this;
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.ampSpectrum) !== 'object') {
- throw new TypeError();
- } //linear regression
+ var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
+ var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 350;
+ var callback = arguments.length > 5 ? arguments[5] : undefined;
+ if (!lng.length) return callback(null, {});
+ return this.backend[fcName](lng, ns, function (err, data) {
+ if (err && data && tried < 5) {
+ setTimeout(function () {
+ _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
+ }, wait);
+ return;
+ }
+ callback(err, data);
+ });
+ }
+ }, {
+ key: "prepareLoading",
+ value: function prepareLoading(languages, namespaces) {
+ var _this4 = this;
- var ampSum = 0;
- var freqSum = 0;
- var freqs = new Float32Array(args.ampSpectrum.length);
- var powFreqSum = 0;
- var ampFreqSum = 0;
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var callback = arguments.length > 3 ? arguments[3] : undefined;
- for (var i = 0; i < args.ampSpectrum.length; i++) {
- ampSum += args.ampSpectrum[i];
- var curFreq = i * args.sampleRate / args.bufferSize;
- freqs[i] = curFreq;
- powFreqSum += curFreq * curFreq;
- freqSum += curFreq;
- ampFreqSum += curFreq * args.ampSpectrum[i];
- }
+ if (!this.backend) {
+ this.logger.warn('No backend was added via i18next.use. Will not load resources.');
+ return callback && callback();
+ }
- return (args.ampSpectrum.length * ampFreqSum - freqSum * ampSum) / (ampSum * (powFreqSum - Math.pow(freqSum, 2)));
-});
+ if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
+ if (typeof namespaces === 'string') namespaces = [namespaces];
+ var toLoad = this.queueLoad(languages, namespaces, options, callback);
-/***/ }),
+ if (!toLoad.toLoad.length) {
+ if (!toLoad.pending.length) callback();
+ return null;
+ }
-/***/ "./src/extractors/spectralSpread.js":
-/*!******************************************!*\
- !*** ./src/extractors/spectralSpread.js ***!
- \******************************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ toLoad.toLoad.forEach(function (name) {
+ _this4.loadOne(name);
+ });
+ }
+ }, {
+ key: "load",
+ value: function load(languages, namespaces, callback) {
+ this.prepareLoading(languages, namespaces, {}, callback);
+ }
+ }, {
+ key: "reload",
+ value: function reload(languages, namespaces, callback) {
+ this.prepareLoading(languages, namespaces, {
+ reload: true
+ }, callback);
+ }
+ }, {
+ key: "loadOne",
+ value: function loadOne(name) {
+ var _this5 = this;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
+ var s = name.split('|');
+ var lng = s[0];
+ var ns = s[1];
+ this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
+ if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
+ if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
+ _this5.loaded(name, err, data);
+ });
+ }
+ }, {
+ key: "saveMissing",
+ value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
+ var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
-/* harmony default export */ __webpack_exports__["default"] = (function (args) {
- if (_typeof(args.ampSpectrum) !== 'object') {
- throw new TypeError();
- }
+ if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
+ this.logger.warn("did not save key \"".concat(key, "\" as the namespace \"").concat(namespace, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
+ return;
+ }
- return Math.sqrt(Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, args.ampSpectrum) - Math.pow(Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, args.ampSpectrum), 2));
-});
+ if (key === undefined || key === null || key === '') return;
-/***/ }),
+ if (this.backend && this.backend.create) {
+ this.backend.create(languages, namespace, key, fallbackValue, null, _objectSpread$5(_objectSpread$5({}, options), {}, {
+ isUpdate: isUpdate
+ }));
+ }
-/***/ "./src/extractors/zcr.js":
-/*!*******************************!*\
- !*** ./src/extractors/zcr.js ***!
- \*******************************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ if (!languages || !languages[0]) return;
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
+ }
+ }]);
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ return Connector;
+}(EventEmitter);
-/* harmony default export */ __webpack_exports__["default"] = (function () {
- if (_typeof(arguments[0].signal) !== 'object') {
- throw new TypeError();
- }
+function get() {
+ return {
+ debug: false,
+ initImmediate: true,
+ ns: ['translation'],
+ defaultNS: ['translation'],
+ fallbackLng: ['dev'],
+ fallbackNS: false,
+ supportedLngs: false,
+ nonExplicitSupportedLngs: false,
+ load: 'all',
+ preload: false,
+ simplifyPluralSuffix: true,
+ keySeparator: '.',
+ nsSeparator: ':',
+ pluralSeparator: '_',
+ contextSeparator: '_',
+ partialBundledLanguages: false,
+ saveMissing: false,
+ updateMissing: false,
+ saveMissingTo: 'fallback',
+ saveMissingPlurals: true,
+ missingKeyHandler: false,
+ missingInterpolationHandler: false,
+ postProcess: false,
+ postProcessPassResolved: false,
+ returnNull: true,
+ returnEmptyString: true,
+ returnObjects: false,
+ joinArrays: false,
+ returnedObjectHandler: false,
+ parseMissingKeyHandler: false,
+ appendNamespaceToMissingKey: false,
+ appendNamespaceToCIMode: false,
+ overloadTranslationOptionHandler: function handle(args) {
+ var ret = {};
+ if (_typeof__default['default'](args[1]) === 'object') ret = args[1];
+ if (typeof args[1] === 'string') ret.defaultValue = args[1];
+ if (typeof args[2] === 'string') ret.tDescription = args[2];
- var zcr = 0;
+ if (_typeof__default['default'](args[2]) === 'object' || _typeof__default['default'](args[3]) === 'object') {
+ var options = args[3] || args[2];
+ Object.keys(options).forEach(function (key) {
+ ret[key] = options[key];
+ });
+ }
- for (var i = 1; i < arguments[0].signal.length; i++) {
- if (arguments[0].signal[i - 1] >= 0 && arguments[0].signal[i] < 0 || arguments[0].signal[i - 1] < 0 && arguments[0].signal[i] >= 0) {
- zcr++;
+ return ret;
+ },
+ interpolation: {
+ escapeValue: true,
+ format: function format(value, _format, lng, options) {
+ return value;
+ },
+ prefix: '{{',
+ suffix: '}}',
+ formatSeparator: ',',
+ unescapePrefix: '-',
+ nestingPrefix: '$t(',
+ nestingSuffix: ')',
+ nestingOptionsSeparator: ',',
+ maxReplaces: 1000,
+ skipOnVariables: true
}
+ };
+}
+function transformOptions(options) {
+ if (typeof options.ns === 'string') options.ns = [options.ns];
+ if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
+ if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
+
+ if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
+ options.supportedLngs = options.supportedLngs.concat(['cimode']);
}
- return zcr;
-});
+ return options;
+}
-/***/ }),
+function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
-/***/ "./src/featureExtractors.js":
-/*!**********************************!*\
- !*** ./src/featureExtractors.js ***!
- \**********************************/
-/*! exports provided: buffer, rms, energy, complexSpectrum, spectralSlope, spectralCentroid, spectralRolloff, spectralFlatness, spectralSpread, spectralSkewness, spectralKurtosis, amplitudeSpectrum, zcr, loudness, perceptualSpread, perceptualSharpness, powerSpectrum, mfcc, chroma, spectralFlux */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return buffer; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "complexSpectrum", function() { return complexSpectrum; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amplitudeSpectrum", function() { return amplitudeSpectrum; });
-/* harmony import */ var _extractors_rms__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractors/rms */ "./src/extractors/rms.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rms", function() { return _extractors_rms__WEBPACK_IMPORTED_MODULE_0__["default"]; });
+function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
-/* harmony import */ var _extractors_energy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./extractors/energy */ "./src/extractors/energy.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "energy", function() { return _extractors_energy__WEBPACK_IMPORTED_MODULE_1__["default"]; });
+function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
-/* harmony import */ var _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./extractors/spectralSlope */ "./src/extractors/spectralSlope.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSlope", function() { return _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__["default"]; });
+function noop() {}
-/* harmony import */ var _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./extractors/spectralCentroid */ "./src/extractors/spectralCentroid.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralCentroid", function() { return _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__["default"]; });
+function bindMemberFunctions(inst) {
+ var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
+ mems.forEach(function (mem) {
+ if (typeof inst[mem] === 'function') {
+ inst[mem] = inst[mem].bind(inst);
+ }
+ });
+}
-/* harmony import */ var _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./extractors/spectralRolloff */ "./src/extractors/spectralRolloff.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralRolloff", function() { return _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__["default"]; });
+var I18n = function (_EventEmitter) {
+ _inherits__default['default'](I18n, _EventEmitter);
-/* harmony import */ var _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./extractors/spectralFlatness */ "./src/extractors/spectralFlatness.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralFlatness", function() { return _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__["default"]; });
+ var _super = _createSuper$3(I18n);
-/* harmony import */ var _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./extractors/spectralSpread */ "./src/extractors/spectralSpread.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSpread", function() { return _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__["default"]; });
+ function I18n() {
+ var _this;
-/* harmony import */ var _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./extractors/spectralSkewness */ "./src/extractors/spectralSkewness.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSkewness", function() { return _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__["default"]; });
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
-/* harmony import */ var _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./extractors/spectralKurtosis */ "./src/extractors/spectralKurtosis.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralKurtosis", function() { return _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__["default"]; });
+ _classCallCheck__default['default'](this, I18n);
-/* harmony import */ var _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./extractors/zcr */ "./src/extractors/zcr.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zcr", function() { return _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__["default"]; });
+ _this = _super.call(this);
-/* harmony import */ var _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./extractors/loudness */ "./src/extractors/loudness.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "loudness", function() { return _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__["default"]; });
+ if (isIE10) {
+ EventEmitter.call(_assertThisInitialized__default['default'](_this));
+ }
-/* harmony import */ var _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./extractors/perceptualSpread */ "./src/extractors/perceptualSpread.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "perceptualSpread", function() { return _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__["default"]; });
+ _this.options = transformOptions(options);
+ _this.services = {};
+ _this.logger = baseLogger;
+ _this.modules = {
+ external: []
+ };
+ bindMemberFunctions(_assertThisInitialized__default['default'](_this));
-/* harmony import */ var _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./extractors/perceptualSharpness */ "./src/extractors/perceptualSharpness.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "perceptualSharpness", function() { return _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__["default"]; });
+ if (callback && !_this.isInitialized && !options.isClone) {
+ if (!_this.options.initImmediate) {
+ _this.init(options, callback);
-/* harmony import */ var _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./extractors/mfcc */ "./src/extractors/mfcc.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mfcc", function() { return _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__["default"]; });
+ return _possibleConstructorReturn__default['default'](_this, _assertThisInitialized__default['default'](_this));
+ }
-/* harmony import */ var _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./extractors/chroma */ "./src/extractors/chroma.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "chroma", function() { return _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__["default"]; });
+ setTimeout(function () {
+ _this.init(options, callback);
+ }, 0);
+ }
-/* harmony import */ var _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./extractors/powerSpectrum */ "./src/extractors/powerSpectrum.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "powerSpectrum", function() { return _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__["default"]; });
+ return _this;
+ }
-/* harmony import */ var _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./extractors/spectralFlux */ "./src/extractors/spectralFlux.js");
-/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralFlux", function() { return _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__["default"]; });
+ _createClass__default['default'](I18n, [{
+ key: "init",
+ value: function init() {
+ var _this2 = this;
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+ if (!options.defaultNS && options.ns) {
+ if (typeof options.ns === 'string') {
+ options.defaultNS = options.ns;
+ } else if (options.ns.indexOf('translation') < 0) {
+ options.defaultNS = options.ns[0];
+ }
+ }
+ var defOpts = get();
+ this.options = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, defOpts), this.options), transformOptions(options));
+ if (this.options.compatibilityAPI !== 'v1') {
+ this.options.interpolation = _objectSpread$6(_objectSpread$6({}, defOpts.interpolation), this.options.interpolation);
+ }
+ if (options.keySeparator !== undefined) {
+ this.options.userDefinedKeySeparator = options.keySeparator;
+ }
+ if (options.nsSeparator !== undefined) {
+ this.options.userDefinedNsSeparator = options.nsSeparator;
+ }
+ function createClassOnDemand(ClassOrObject) {
+ if (!ClassOrObject) return null;
+ if (typeof ClassOrObject === 'function') return new ClassOrObject();
+ return ClassOrObject;
+ }
+ if (!this.options.isClone) {
+ if (this.modules.logger) {
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
+ } else {
+ baseLogger.init(null, this.options);
+ }
+ var formatter;
+ if (this.modules.formatter) {
+ formatter = this.modules.formatter;
+ } else if (typeof Intl !== 'undefined') {
+ formatter = Formatter;
+ }
+ var lu = new LanguageUtil(this.options);
+ this.store = new ResourceStore(this.options.resources, this.options);
+ var s = this.services;
+ s.logger = baseLogger;
+ s.resourceStore = this.store;
+ s.languageUtils = lu;
+ s.pluralResolver = new PluralResolver(lu, {
+ prepend: this.options.pluralSeparator,
+ compatibilityJSON: this.options.compatibilityJSON,
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
+ });
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
+ s.formatter = createClassOnDemand(formatter);
+ s.formatter.init(s, this.options);
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
+ }
+ s.interpolator = new Interpolator(this.options);
+ s.utils = {
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
+ };
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
+ s.backendConnector.on('*', function (event) {
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+ _this2.emit.apply(_this2, [event].concat(args));
+ });
+ if (this.modules.languageDetector) {
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
+ s.languageDetector.init(s, this.options.detection, this.options);
+ }
+ if (this.modules.i18nFormat) {
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
+ }
+ this.translator = new Translator(this.services, this.options);
+ this.translator.on('*', function (event) {
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ args[_key2 - 1] = arguments[_key2];
+ }
-var buffer = function buffer(args) {
- return args.signal;
-};
+ _this2.emit.apply(_this2, [event].concat(args));
+ });
+ this.modules.external.forEach(function (m) {
+ if (m.init) m.init(_this2);
+ });
+ }
-var complexSpectrum = function complexSpectrum(args) {
- return args.complexSpectrum;
-};
+ this.format = this.options.interpolation.format;
+ if (!callback) callback = noop;
-var amplitudeSpectrum = function amplitudeSpectrum(args) {
- return args.ampSpectrum;
-};
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
+ var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
+ if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
+ }
+ if (!this.services.languageDetector && !this.options.lng) {
+ this.logger.warn('init: no languageDetector is used and no lng is defined');
+ }
+ var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
+ storeApi.forEach(function (fcName) {
+ _this2[fcName] = function () {
+ var _this2$store;
-/***/ }),
+ return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
+ };
+ });
+ var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
+ storeApiChained.forEach(function (fcName) {
+ _this2[fcName] = function () {
+ var _this2$store2;
-/***/ "./src/index.js":
-/*!**********************!*\
- !*** ./src/index.js ***!
- \**********************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+ (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
-module.exports = __webpack_require__(/*! ./main */ "./src/main.js")["default"];
+ return _this2;
+ };
+ });
+ var deferred = defer();
-/***/ }),
+ var load = function load() {
+ var finish = function finish(err, t) {
+ if (_this2.isInitialized && !_this2.initializedStoreOnce) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');
+ _this2.isInitialized = true;
+ if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);
-/***/ "./src/main.js":
-/*!*********************!*\
- !*** ./src/main.js ***!
- \*********************/
-/*! exports provided: default */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ _this2.emit('initialized', _this2.options);
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utilities */ "./src/utilities.js");
-/* harmony import */ var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./featureExtractors */ "./src/featureExtractors.js");
-/* harmony import */ var fftjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! fftjs */ "./node_modules/fftjs/dist/fft.js");
-/* harmony import */ var fftjs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fftjs__WEBPACK_IMPORTED_MODULE_2__);
-/* harmony import */ var _meyda_wa__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./meyda-wa */ "./src/meyda-wa.js");
-function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+ deferred.resolve(t);
+ callback(err, t);
+ };
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+ if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));
+
+ _this2.changeLanguage(_this2.options.lng, finish);
+ };
+ if (this.options.resources || !this.options.initImmediate) {
+ load();
+ } else {
+ setTimeout(load, 0);
+ }
+ return deferred;
+ }
+ }, {
+ key: "loadResources",
+ value: function loadResources(language) {
+ var _this3 = this;
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
+ var usedCallback = callback;
+ var usedLng = typeof language === 'string' ? language : this.language;
+ if (typeof language === 'function') usedCallback = language;
+ if (!this.options.resources || this.options.partialBundledLanguages) {
+ if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
+ var toLoad = [];
-/**
- * Meyda Module
- * @module meyda
- */
+ var append = function append(lng) {
+ if (!lng) return;
-/**
- * Options for constructing a MeydaAnalyzer
- * @typedef {Object} MeydaOptions
- * @property {AudioContext} audioContext - The Audio Context for the MeydaAnalyzer to operate in.
- * @property {AudioNode} source - The Audio Node for Meyda to listen to.
- * @property {number} [bufferSize] - The size of the buffer.
- * @property {number} [hopSize] - The hop size between buffers.
- * @property {number} [sampleRate] - The number of samples per second in the audio context.
- * @property {Function} [callback] - A function to receive the frames of audio features
- * @property {string} [windowingFunction] - The Windowing Function to apply to the signal before transformation to the frequency domain
- * @property {string|Array.} [featureExtractors] - Specify the feature extractors you want to run on the audio.
- * @property {boolean} [startImmediately] - Pass `true` to start feature extraction immediately
- * @property {number} [numberOfMFCCCoefficients] - The number of MFCC co-efficients that the MFCC feature extractor should return
- */
+ var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
-/**
- * Web Audio context
- * Either an {@link AudioContext|https://developer.mozilla.org/en-US/docs/Web/API/AudioContext}
- * or an {@link OfflineAudioContext|https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext}
- * @typedef {Object} AudioContext
- */
+ lngs.forEach(function (l) {
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
+ });
+ };
-/**
- * AudioNode
- * A Web AudioNode
- * @typedef {Object} AudioNode
- */
+ if (!usedLng) {
+ var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
+ fallbacks.forEach(function (l) {
+ return append(l);
+ });
+ } else {
+ append(usedLng);
+ }
-/**
- * ScriptProcessorNode
- * A Web Audio ScriptProcessorNode
- * @typedef {Object} ScriptProcessorNode
- */
+ if (this.options.preload) {
+ this.options.preload.forEach(function (l) {
+ return append(l);
+ });
+ }
-/**
- * @class Meyda
- * @hideconstructor
- * @classdesc
- * The schema for the default export of the Meyda library.
- * @example
- * var Meyda = require('meyda');
- */
+ this.services.backendConnector.load(toLoad, this.options.ns, usedCallback);
+ } else {
+ usedCallback(null);
+ }
+ }
+ }, {
+ key: "reloadResources",
+ value: function reloadResources(lngs, ns, callback) {
+ var deferred = defer();
+ if (!lngs) lngs = this.languages;
+ if (!ns) ns = this.options.ns;
+ if (!callback) callback = noop;
+ this.services.backendConnector.reload(lngs, ns, function (err) {
+ deferred.resolve();
+ callback(err);
+ });
+ return deferred;
+ }
+ }, {
+ key: "use",
+ value: function use(module) {
+ if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
+ if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
-var Meyda = {
- /**
- * Meyda stores a reference to the relevant audio context here for use inside
- * the Web Audio API.
- * @instance
- * @member {AudioContext}
- */
- audioContext: null,
+ if (module.type === 'backend') {
+ this.modules.backend = module;
+ }
- /**
- * Meyda keeps an internal ScriptProcessorNode in which it runs audio feature
- * extraction. The ScriptProcessorNode is stored in this member variable.
- * @instance
- * @member {ScriptProcessorNode}
- */
- spn: null,
+ if (module.type === 'logger' || module.log && module.warn && module.error) {
+ this.modules.logger = module;
+ }
- /**
- * The length of each buffer that Meyda will extract audio on. When recieving
- * input via the Web Audio API, the Script Processor Node chunks incoming audio
- * into arrays of this length. Longer buffers allow for more precision in the
- * frequency domain, but increase the amount of time it takes for Meyda to
- * output a set of audio features for the buffer. You can calculate how many
- * sets of audio features Meyda will output per second by dividing the
- * buffer size by the sample rate. If you're using Meyda for visualisation,
- * make sure that you're collecting audio features at a rate that's faster
- * than or equal to the video frame rate you expect.
- * @instance
- * @member {number}
- */
- bufferSize: 512,
+ if (module.type === 'languageDetector') {
+ this.modules.languageDetector = module;
+ }
- /**
- * The number of samples per second of the incoming audio. This affects
- * feature extraction outside of the context of the Web Audio API, and must be
- * set accurately - otherwise calculations will be off.
- * @instance
- * @member {number}
- */
- sampleRate: 44100,
+ if (module.type === 'i18nFormat') {
+ this.modules.i18nFormat = module;
+ }
- /**
- * The number of Mel bands to use in the Mel Frequency Cepstral Co-efficients
- * feature extractor
- * @instance
- * @member {number}
- */
- melBands: 26,
+ if (module.type === 'postProcessor') {
+ postProcessor.addPostProcessor(module);
+ }
- /**
- * The number of bands to divide the spectrum into for the Chroma feature
- * extractor. 12 is the standard number of semitones per octave in the western
- * music tradition, but Meyda can use an arbitrary number of bands, which
- * can be useful for microtonal music.
- * @instance
- * @member {number}
- */
- chromaBands: 12,
+ if (module.type === 'formatter') {
+ this.modules.formatter = module;
+ }
- /**
- * A function you can provide that will be called for each buffer that Meyda
- * receives from its source node
- * @instance
- * @member {Function}
- */
- callback: null,
+ if (module.type === '3rdParty') {
+ this.modules.external.push(module);
+ }
- /**
- * Specify the windowing function to apply to the buffer before the
- * transformation from the time domain to the frequency domain is performed
- *
- * The default windowing function is the hanning window.
- *
- * @instance
- * @member {string}
- */
- windowingFunction: 'hanning',
+ return this;
+ }
+ }, {
+ key: "changeLanguage",
+ value: function changeLanguage(lng, callback) {
+ var _this4 = this;
- /**
- * @member {object}
- */
- featureExtractors: _featureExtractors__WEBPACK_IMPORTED_MODULE_1__,
- EXTRACTION_STARTED: false,
+ this.isLanguageChangingTo = lng;
+ var deferred = defer();
+ this.emit('languageChanging', lng);
- /**
- * The number of MFCC co-efficients that the MFCC feature extractor should return
- * @instance
- * @member {number}
- */
- numberOfMFCCCoefficients: 13,
- _featuresToExtract: [],
- windowing: _utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"],
- _errors: {
- notPow2: new Error('Meyda: Buffer size must be a power of 2, e.g. 64 or 512'),
- featureUndef: new Error('Meyda: No features defined.'),
- invalidFeatureFmt: new Error('Meyda: Invalid feature format'),
- invalidInput: new Error('Meyda: Invalid input.'),
- noAC: new Error('Meyda: No AudioContext specified.'),
- noSource: new Error('Meyda: No source node specified.')
- },
+ var setLngProps = function setLngProps(l) {
+ _this4.language = l;
+ _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
+ _this4.resolvedLanguage = undefined;
+ if (['cimode', 'dev'].indexOf(l) > -1) return;
- /**
- * @summary
- * Create a MeydaAnalyzer
- *
- * A factory function for creating a MeydaAnalyzer, the interface for using
- * Meyda in the context of Web Audio.
- *
- * @method
- * @param {MeydaOptions} options Options - an object containing configuration
- * @returns {MeydaAnalyzer}
- * @example
- * const analyzer = Meyda.createMeydaAnalyzer({
- * "audioContext": audioContext,
- * "source": source,
- * "bufferSize": 512,
- * "featureExtractors": ["rms"],
- * "inputs": 2,
- * "callback": features => {
- * levelRangeElement.value = features.rms;
- * }
- * });
- */
- createMeydaAnalyzer: function createMeydaAnalyzer(options) {
- return new _meyda_wa__WEBPACK_IMPORTED_MODULE_3__["MeydaAnalyzer"](options, Object.assign({}, Meyda));
- },
+ for (var li = 0; li < _this4.languages.length; li++) {
+ var lngInLngs = _this4.languages[li];
+ if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
- /**
- * Extract an audio feature from a buffer
- *
- * Unless `meyda.windowingFunction` is set otherwise, `extract` will
- * internally apply a hanning window to the buffer prior to conversion into
- * the frequency domain.
- *
- * @function
- * @param {(string|Array.)} feature - the feature you want to extract
- * @param {Array.} signal
- * An array of numbers that represents the signal. It should be of length
- * `meyda.bufferSize`
- * @param {Array.} [previousSignal] - the previous buffer
- * @returns {object} Features
- * @example
- * meyda.bufferSize = 2048;
- * const features = meyda.extract(['zcr', 'spectralCentroid'], signal);
- */
- extract: function extract(feature, signal, previousSignal) {
- var _this = this;
+ if (_this4.store.hasLanguageSomeTranslations(lngInLngs)) {
+ _this4.resolvedLanguage = lngInLngs;
+ break;
+ }
+ }
+ };
- if (!signal) throw this._errors.invalidInput;else if (_typeof(signal) != 'object') throw this._errors.invalidInput;else if (!feature) throw this._errors.featureUndef;else if (!_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](signal.length)) throw this._errors.notPow2;
+ var done = function done(err, l) {
+ if (l) {
+ setLngProps(l);
- if (typeof this.barkScale == 'undefined' || this.barkScale.length != this.bufferSize) {
- this.barkScale = _utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this.bufferSize, this.sampleRate, this.bufferSize);
- } // Recalculate mel bank if buffer length changed
+ _this4.translator.changeLanguage(l);
+ _this4.isLanguageChangingTo = undefined;
- if (typeof this.melFilterBank == 'undefined' || this.barkScale.length != this.bufferSize || this.melFilterBank.length != this.melBands) {
- this.melFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this.melBands, this.numberOfMFCCCoefficients), this.sampleRate, this.bufferSize);
- } // Recalculate chroma bank if buffer length changed
+ _this4.emit('languageChanged', l);
+ _this4.logger.log('languageChanged', l);
+ } else {
+ _this4.isLanguageChangingTo = undefined;
+ }
- if (typeof this.chromaFilterBank == 'undefined' || this.chromaFilterBank.length != this.chromaBands) {
- this.chromaFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createChromaFilterBank"](this.chromaBands, this.sampleRate, this.bufferSize);
- }
+ deferred.resolve(function () {
+ return _this4.t.apply(_this4, arguments);
+ });
+ if (callback) callback(err, function () {
+ return _this4.t.apply(_this4, arguments);
+ });
+ };
- if (typeof signal.buffer == 'undefined') {
- //signal is a normal array, convert to F32A
- this.signal = _utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal);
- } else {
- this.signal = signal;
- }
+ var setLng = function setLng(lngs) {
+ if (!lng && !lngs && _this4.services.languageDetector) lngs = [];
+ var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
- var preparedSignal = prepareSignalWithSpectrum(signal, this.windowingFunction, this.bufferSize);
- this.signal = preparedSignal.windowedSignal;
- this.complexSpectrum = preparedSignal.complexSpectrum;
- this.ampSpectrum = preparedSignal.ampSpectrum;
+ if (l) {
+ if (!_this4.language) {
+ setLngProps(l);
+ }
- if (previousSignal) {
- var _preparedSignal = prepareSignalWithSpectrum(previousSignal, this.windowingFunction, this.bufferSize);
+ if (!_this4.translator.language) _this4.translator.changeLanguage(l);
+ if (_this4.services.languageDetector) _this4.services.languageDetector.cacheUserLanguage(l);
+ }
- this.previousSignal = _preparedSignal.windowedSignal;
- this.previousComplexSpectrum = _preparedSignal.complexSpectrum;
- this.previousAmpSpectrum = _preparedSignal.ampSpectrum;
- }
+ _this4.loadResources(l, function (err) {
+ done(err, l);
+ });
+ };
- var extract = function extract(feature) {
- return _this.featureExtractors[feature]({
- ampSpectrum: _this.ampSpectrum,
- chromaFilterBank: _this.chromaFilterBank,
- complexSpectrum: _this.complexSpectrum,
- signal: _this.signal,
- bufferSize: _this.bufferSize,
- sampleRate: _this.sampleRate,
- barkScale: _this.barkScale,
- melFilterBank: _this.melFilterBank,
- previousSignal: _this.previousSignal,
- previousAmpSpectrum: _this.previousAmpSpectrum,
- previousComplexSpectrum: _this.previousComplexSpectrum,
- numberOfMFCCCoefficients: _this.numberOfMFCCCoefficients
- });
- };
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
+ setLng(this.services.languageDetector.detect());
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
+ this.services.languageDetector.detect(setLng);
+ } else {
+ setLng(lng);
+ }
- if (_typeof(feature) === 'object') {
- return feature.reduce(function (acc, el) {
- return Object.assign({}, acc, _defineProperty({}, el, extract(el)));
- }, {});
- } else if (typeof feature === 'string') {
- return extract(feature);
- } else {
- throw this._errors.invalidFeatureFmt;
+ return deferred;
}
- }
-};
+ }, {
+ key: "getFixedT",
+ value: function getFixedT(lng, ns, keyPrefix) {
+ var _this5 = this;
-var prepareSignalWithSpectrum = function prepareSignalWithSpectrum(signal, windowingFunction, bufferSize) {
- var preparedSignal = {};
+ var fixedT = function fixedT(key, opts) {
+ var options;
- if (typeof signal.buffer == 'undefined') {
- //signal is a normal array, convert to F32A
- preparedSignal.signal = _utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal);
- } else {
- preparedSignal.signal = signal;
- }
+ if (_typeof__default['default'](opts) !== 'object') {
+ for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
+ rest[_key3 - 2] = arguments[_key3];
+ }
- preparedSignal.windowedSignal = _utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"](preparedSignal.signal, windowingFunction);
- preparedSignal.complexSpectrum = Object(fftjs__WEBPACK_IMPORTED_MODULE_2__["fft"])(preparedSignal.windowedSignal);
- preparedSignal.ampSpectrum = new Float32Array(bufferSize / 2);
+ options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
+ } else {
+ options = _objectSpread$6({}, opts);
+ }
- for (var i = 0; i < bufferSize / 2; i++) {
- preparedSignal.ampSpectrum[i] = Math.sqrt(Math.pow(preparedSignal.complexSpectrum.real[i], 2) + Math.pow(preparedSignal.complexSpectrum.imag[i], 2));
- }
+ options.lng = options.lng || fixedT.lng;
+ options.lngs = options.lngs || fixedT.lngs;
+ options.ns = options.ns || fixedT.ns;
+ var keySeparator = _this5.options.keySeparator || '.';
+ var resultKey = keyPrefix ? "".concat(keyPrefix).concat(keySeparator).concat(key) : key;
+ return _this5.t(resultKey, options);
+ };
- return preparedSignal;
-};
-/**
- * The Meyda class
- * @type {Meyda}
- */
+ if (typeof lng === 'string') {
+ fixedT.lng = lng;
+ } else {
+ fixedT.lngs = lng;
+ }
+ fixedT.ns = ns;
+ fixedT.keyPrefix = keyPrefix;
+ return fixedT;
+ }
+ }, {
+ key: "t",
+ value: function t() {
+ var _this$translator;
-/* harmony default export */ __webpack_exports__["default"] = (Meyda);
-if (typeof window !== 'undefined') window.Meyda = Meyda;
+ return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
+ }
+ }, {
+ key: "exists",
+ value: function exists() {
+ var _this$translator2;
-/***/ }),
+ return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
+ }
+ }, {
+ key: "setDefaultNamespace",
+ value: function setDefaultNamespace(ns) {
+ this.options.defaultNS = ns;
+ }
+ }, {
+ key: "hasLoadedNamespace",
+ value: function hasLoadedNamespace(ns) {
+ var _this6 = this;
-/***/ "./src/meyda-wa.js":
-/*!*************************!*\
- !*** ./src/meyda-wa.js ***!
- \*************************/
-/*! exports provided: MeydaAnalyzer */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeydaAnalyzer", function() { return MeydaAnalyzer; });
-/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utilities */ "./src/utilities.js");
-/* harmony import */ var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./featureExtractors */ "./src/featureExtractors.js");
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+ if (!this.isInitialized) {
+ this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
+ return false;
+ }
-function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+ if (!this.languages || !this.languages.length) {
+ this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
+ return false;
+ }
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+ var lng = this.resolvedLanguage || this.languages[0];
+ var fallbackLng = this.options ? this.options.fallbackLng : false;
+ var lastLng = this.languages[this.languages.length - 1];
+ if (lng.toLowerCase() === 'cimode') return true;
+ var loadNotPending = function loadNotPending(l, n) {
+ var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
+ return loadState === -1 || loadState === 2;
+ };
-/**
- * MeydaAnalyzer
- * @classdesc
- * Meyda's interface to the Web Audio API. MeydaAnalyzer abstracts an API on
- * top of the Web Audio API's ScriptProcessorNode, running the Meyda audio
- * feature extractors inside that context.
- *
- * MeydaAnalyzer's constructor should not be called directly - MeydaAnalyzer
- * objects should be generated using the {@link Meyda.createMeydaAnalyzer}
- * factory function in the main Meyda class.
- *
- * @example
- * const analyzer = Meyda.createMeydaAnalyzer({
- * "audioContext": audioContext,
- * "source": source,
- * "bufferSize": 512,
- * "featureExtractors": ["rms"],
- * "inputs": 2,
- * "numberOfMFCCCoefficients": 20
- * "callback": features => {
- * levelRangeElement.value = features.rms;
- * }
- * });
- * @hideconstructor
- */
+ if (options.precheck) {
+ var preResult = options.precheck(this, loadNotPending);
+ if (preResult !== undefined) return preResult;
+ }
-var MeydaAnalyzer =
-/*#__PURE__*/
-function () {
- function MeydaAnalyzer(options, _this) {
- var _this2 = this;
+ if (this.hasResourceBundle(lng, ns)) return true;
+ if (!this.services.backendConnector.backend) return true;
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
+ return false;
+ }
+ }, {
+ key: "loadNamespaces",
+ value: function loadNamespaces(ns, callback) {
+ var _this7 = this;
- _classCallCheck(this, MeydaAnalyzer);
+ var deferred = defer();
- this._m = _this;
+ if (!this.options.ns) {
+ callback && callback();
+ return Promise.resolve();
+ }
- if (!options.audioContext) {
- throw this._m.errors.noAC;
- } else if (options.bufferSize && !_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](options.bufferSize)) {
- throw this._m._errors.notPow2;
- } else if (!options.source) {
- throw this._m._errors.noSource;
+ if (typeof ns === 'string') ns = [ns];
+ ns.forEach(function (n) {
+ if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
+ });
+ this.loadResources(function (err) {
+ deferred.resolve();
+ if (callback) callback(err);
+ });
+ return deferred;
}
+ }, {
+ key: "loadLanguages",
+ value: function loadLanguages(lngs, callback) {
+ var deferred = defer();
+ if (typeof lngs === 'string') lngs = [lngs];
+ var preloaded = this.options.preload || [];
+ var newLngs = lngs.filter(function (lng) {
+ return preloaded.indexOf(lng) < 0;
+ });
- this._m.audioContext = options.audioContext; // TODO: validate options
+ if (!newLngs.length) {
+ if (callback) callback();
+ return Promise.resolve();
+ }
+
+ this.options.preload = preloaded.concat(newLngs);
+ this.loadResources(function (err) {
+ deferred.resolve();
+ if (callback) callback(err);
+ });
+ return deferred;
+ }
+ }, {
+ key: "dir",
+ value: function dir(lng) {
+ if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
+ if (!lng) return 'rtl';
+ var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
+ return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
+ }
+ }, {
+ key: "cloneInstance",
+ value: function cloneInstance() {
+ var _this8 = this;
- this._m.bufferSize = options.bufferSize || this._m.bufferSize || 256;
- this._m.hopSize = options.hopSize || this._m.hopSize || this._m.bufferSize;
- this._m.sampleRate = options.sampleRate || this._m.audioContext.sampleRate || 44100;
- this._m.callback = options.callback;
- this._m.windowingFunction = options.windowingFunction || 'hanning';
- this._m.featureExtractors = _featureExtractors__WEBPACK_IMPORTED_MODULE_1__;
- this._m.EXTRACTION_STARTED = options.startImmediately || false;
- this._m.channel = typeof options.channel === 'number' ? options.channel : 0;
- this._m.inputs = options.inputs || 1;
- this._m.outputs = options.outputs || 1;
- this._m.numberOfMFCCCoefficients = options.numberOfMFCCCoefficients || this._m.numberOfMFCCCoefficients || 13; //create nodes
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
- this._m.spn = this._m.audioContext.createScriptProcessor(this._m.bufferSize, this._m.inputs, this._m.outputs);
+ var mergedOptions = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, this.options), options), {
+ isClone: true
+ });
- this._m.spn.connect(this._m.audioContext.destination);
+ var clone = new I18n(mergedOptions);
+ var membersToCopy = ['store', 'services', 'language'];
+ membersToCopy.forEach(function (m) {
+ clone[m] = _this8[m];
+ });
+ clone.services = _objectSpread$6({}, this.services);
+ clone.services.utils = {
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
+ };
+ clone.translator = new Translator(clone.services, clone.options);
+ clone.translator.on('*', function (event) {
+ for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
+ args[_key4 - 1] = arguments[_key4];
+ }
- this._m._featuresToExtract = options.featureExtractors || []; //always recalculate BS and MFB when a new Meyda analyzer is created.
+ clone.emit.apply(clone, [event].concat(args));
+ });
+ clone.init(mergedOptions, callback);
+ clone.translator.options = clone.options;
+ clone.translator.backendConnector.services.utils = {
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
+ };
+ return clone;
+ }
+ }, {
+ key: "toJSON",
+ value: function toJSON() {
+ return {
+ options: this.options,
+ store: this.store,
+ language: this.language,
+ languages: this.languages,
+ resolvedLanguage: this.resolvedLanguage
+ };
+ }
+ }]);
- this._m.barkScale = _utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this._m.bufferSize, this._m.sampleRate, this._m.bufferSize);
- this._m.melFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this._m.melBands, this._m.numberOfMFCCCoefficients), this._m.sampleRate, this._m.bufferSize);
- this._m.inputData = null;
- this._m.previousInputData = null;
- this._m.frame = null;
- this._m.previousFrame = null;
- this.setSource(options.source);
+ return I18n;
+}(EventEmitter);
- this._m.spn.onaudioprocess = function (e) {
- if (_this2._m.inputData !== null) {
- _this2._m.previousInputData = _this2._m.inputData;
- }
+_defineProperty__default['default'](I18n, "createInstance", function () {
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
+ return new I18n(options, callback);
+});
- _this2._m.inputData = e.inputBuffer.getChannelData(_this2._m.channel);
+var instance = I18n.createInstance();
+instance.createInstance = I18n.createInstance;
- if (!_this2._m.previousInputData) {
- var buffer = _this2._m.inputData;
- } else {
- var buffer = new Float32Array(_this2._m.previousInputData.length + _this2._m.inputData.length - _this2._m.hopSize);
- buffer.set(_this2._m.previousInputData.slice(_this2._m.hopSize));
- buffer.set(_this2._m.inputData, _this2._m.previousInputData.length - _this2._m.hopSize);
- }
+module.exports = instance;
- ;
- var frames = _utilities__WEBPACK_IMPORTED_MODULE_0__["frame"](buffer, _this2._m.bufferSize, _this2._m.hopSize);
- frames.forEach(function (f) {
- _this2._m.frame = f;
+},{"@babel/runtime/helpers/assertThisInitialized":10,"@babel/runtime/helpers/classCallCheck":11,"@babel/runtime/helpers/createClass":12,"@babel/runtime/helpers/defineProperty":13,"@babel/runtime/helpers/getPrototypeOf":14,"@babel/runtime/helpers/inherits":15,"@babel/runtime/helpers/possibleConstructorReturn":18,"@babel/runtime/helpers/toArray":20,"@babel/runtime/helpers/typeof":21}],90:[function(require,module,exports){
+/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */
+exports.read = function (buffer, offset, isLE, mLen, nBytes) {
+ var e, m
+ var eLen = (nBytes * 8) - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var nBits = -7
+ var i = isLE ? (nBytes - 1) : 0
+ var d = isLE ? -1 : 1
+ var s = buffer[offset + i]
- var features = _this2._m.extract(_this2._m._featuresToExtract, _this2._m.frame, _this2._m.previousFrame); // call callback if applicable
+ i += d
+ e = s & ((1 << (-nBits)) - 1)
+ s >>= (-nBits)
+ nBits += eLen
+ for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- if (typeof _this2._m.callback === 'function' && _this2._m.EXTRACTION_STARTED) {
- _this2._m.callback(features);
- }
+ m = e & ((1 << (-nBits)) - 1)
+ e >>= (-nBits)
+ nBits += mLen
+ for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- _this2._m.previousFrame = _this2._m.frame;
- });
- };
+ if (e === 0) {
+ e = 1 - eBias
+ } else if (e === eMax) {
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
+ } else {
+ m = m + Math.pow(2, mLen)
+ e = e - eBias
}
- /**
- * Start feature extraction
- * The audio features will be passed to the callback function that was defined
- * in the MeydaOptions that were passed to the factory when constructing the
- * MeydaAnalyzer.
- * @param {(string|Array.)} [features]
- * Change the features that Meyda is extracting. Defaults to the features that
- * were set upon construction in the options parameter.
- * @example
- * analyzer.start('chroma');
- */
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
+}
+
+exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c
+ var eLen = (nBytes * 8) - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
+ var i = isLE ? 0 : (nBytes - 1)
+ var d = isLE ? 1 : -1
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+ value = Math.abs(value)
- _createClass(MeydaAnalyzer, [{
- key: "start",
- value: function start(features) {
- this._m._featuresToExtract = features || this._m._featuresToExtract;
- this._m.EXTRACTION_STARTED = true;
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0
+ e = eMax
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2)
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--
+ c *= 2
+ }
+ if (e + eBias >= 1) {
+ value += rt / c
+ } else {
+ value += rt * Math.pow(2, 1 - eBias)
+ }
+ if (value * c >= 2) {
+ e++
+ c /= 2
}
- /**
- * Stop feature extraction.
- * @example
- * analyzer.stop();
- */
- }, {
- key: "stop",
- value: function stop() {
- this._m.EXTRACTION_STARTED = false;
+ if (e + eBias >= eMax) {
+ m = 0
+ e = eMax
+ } else if (e + eBias >= 1) {
+ m = ((value * c) - 1) * Math.pow(2, mLen)
+ e = e + eBias
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
+ e = 0
}
- /**
- * Set the Audio Node for Meyda to listen to.
- * @param {AudioNode} source - The Audio Node for Meyda to listen to
- * @example
- * analyzer.setSource(audioSourceNode);
- */
+ }
- }, {
- key: "setSource",
- value: function setSource(source) {
- this._m.source && this._m.source.disconnect(this._m.spn);
- this._m.source = source;
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- this._m.source.connect(this._m.spn);
- }
- /**
- * Set the channel of the audio node for Meyda to listen to
- * @param {number} channel - the index of the channel on the input audio node
- * for Meyda to listen to.
- * @example
- * analyzer.setChannel(0);
- */
+ e = (e << mLen) | m
+ eLen += mLen
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- }, {
- key: "setChannel",
- value: function setChannel(channel) {
- if (channel <= this._m.inputs) {
- this._m.channel = channel;
- } else {
- console.error("Channel ".concat(channel, " does not exist. Make sure you've provided a value for 'inputs' that is greater than ").concat(channel, " when instantiating the MeydaAnalyzer"));
- }
- }
- /**
- * Get a set of features from the current frame.
- * @param {(string|Array.)} [features]
- * Change the features that Meyda is extracting
- * @example
- * analyzer.get('spectralFlatness');
- */
+ buffer[offset + i - d] |= s * 128
+}
- }, {
- key: "get",
- value: function get(features) {
- if (this._m.inputData) {
- return this._m.extract(features || this._m._featuresToExtract, this._m.inputData, this._m.previousInputData);
- } else {
- return null;
- }
+},{}],91:[function(require,module,exports){
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ })
}
- }]);
-
- return MeydaAnalyzer;
-}();
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
+ }
+ }
+}
-/***/ }),
+},{}],92:[function(require,module,exports){
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else if(typeof exports === 'object')
+ exports["Meyda"] = factory();
+ else
+ root["Meyda"] = factory();
+})(window, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js");
+/******/ })
+/************************************************************************/
+/******/ ({
-/***/ "./src/utilities.js":
-/*!**************************!*\
- !*** ./src/utilities.js ***!
- \**************************/
-/*! exports provided: isPowerOfTwo, error, pointwiseBufferMult, applyWindow, createBarkScale, typedToArray, arrayToTyped, _normalize, normalize, normalizeToOne, mean, melToFreq, freqToMel, createMelFilterBank, hzToOctaves, normalizeByColumn, createChromaFilterBank, frame */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+/***/ "./node_modules/assert/assert.js":
+/*!***************************************!*\
+ !*** ./node_modules/assert/assert.js ***!
+ \***************************************/
+/*! no static exports found */
+/***/ (function(module, exports, __webpack_require__) {
"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPowerOfTwo", function() { return isPowerOfTwo; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "error", function() { return error; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pointwiseBufferMult", function() { return pointwiseBufferMult; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyWindow", function() { return applyWindow; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBarkScale", function() { return createBarkScale; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "typedToArray", function() { return typedToArray; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayToTyped", function() { return arrayToTyped; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_normalize", function() { return _normalize; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalize", function() { return normalize; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeToOne", function() { return normalizeToOne; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mean", function() { return mean; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "melToFreq", function() { return melToFreq; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "freqToMel", function() { return freqToMel; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createMelFilterBank", function() { return createMelFilterBank; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hzToOctaves", function() { return hzToOctaves; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeByColumn", function() { return normalizeByColumn; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createChromaFilterBank", function() { return createChromaFilterBank; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frame", function() { return frame; });
-/* harmony import */ var _windowing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./windowing */ "./src/windowing.js");
-function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
+/* WEBPACK VAR INJECTION */(function(global) {
-function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
+// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
+// original notice:
-function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+function compare(a, b) {
+ if (a === b) {
+ return 0;
+ }
-function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
+ var x = a.length;
+ var y = b.length;
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i];
+ y = b[i];
+ break;
+ }
+ }
-var windows = {};
-function isPowerOfTwo(num) {
- while (num % 2 === 0 && num > 1) {
- num /= 2;
+ if (x < y) {
+ return -1;
}
+ if (y < x) {
+ return 1;
+ }
+ return 0;
+}
+function isBuffer(b) {
+ if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
+ return global.Buffer.isBuffer(b);
+ }
+ return !!(b != null && b._isBuffer);
+}
- return num === 1;
+// based on node assert, original notice:
+
+// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
+//
+// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
+//
+// Originally from narwhal.js (http://narwhaljs.org)
+// Copyright (c) 2009 Thomas Robinson <280north.com>
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the 'Software'), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var util = __webpack_require__(/*! util/ */ "./node_modules/webpack-stream/node_modules/util/util.js");
+var hasOwn = Object.prototype.hasOwnProperty;
+var pSlice = Array.prototype.slice;
+var functionsHaveNames = (function () {
+ return function foo() {}.name === 'foo';
+}());
+function pToString (obj) {
+ return Object.prototype.toString.call(obj);
}
-function error(message) {
- throw new Error('Meyda: ' + message);
+function isView(arrbuf) {
+ if (isBuffer(arrbuf)) {
+ return false;
+ }
+ if (typeof global.ArrayBuffer !== 'function') {
+ return false;
+ }
+ if (typeof ArrayBuffer.isView === 'function') {
+ return ArrayBuffer.isView(arrbuf);
+ }
+ if (!arrbuf) {
+ return false;
+ }
+ if (arrbuf instanceof DataView) {
+ return true;
+ }
+ if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
+ return true;
+ }
+ return false;
}
-function pointwiseBufferMult(a, b) {
- var c = [];
+// 1. The assert module provides functions that throw
+// AssertionError's when particular conditions are not met. The
+// assert module must conform to the following interface.
+
+var assert = module.exports = ok;
+
+// 2. The AssertionError is defined in assert.
+// new assert.AssertionError({ message: message,
+// actual: actual,
+// expected: expected })
- for (var i = 0; i < Math.min(a.length, b.length); i++) {
- c[i] = a[i] * b[i];
+var regex = /\s*function\s+([^\(\s]*)\s*/;
+// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
+function getName(func) {
+ if (!util.isFunction(func)) {
+ return;
}
-
- return c;
+ if (functionsHaveNames) {
+ return func.name;
+ }
+ var str = func.toString();
+ var match = str.match(regex);
+ return match && match[1];
}
-function applyWindow(signal, windowname) {
- if (windowname !== 'rect') {
- if (windowname === '' || !windowname) windowname = 'hanning';
- if (!windows[windowname]) windows[windowname] = {};
+assert.AssertionError = function AssertionError(options) {
+ this.name = 'AssertionError';
+ this.actual = options.actual;
+ this.expected = options.expected;
+ this.operator = options.operator;
+ if (options.message) {
+ this.message = options.message;
+ this.generatedMessage = false;
+ } else {
+ this.message = getMessage(this);
+ this.generatedMessage = true;
+ }
+ var stackStartFunction = options.stackStartFunction || fail;
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, stackStartFunction);
+ } else {
+ // non v8 browsers so we can have a stacktrace
+ var err = new Error();
+ if (err.stack) {
+ var out = err.stack;
- if (!windows[windowname][signal.length]) {
- try {
- windows[windowname][signal.length] = _windowing__WEBPACK_IMPORTED_MODULE_0__[windowname](signal.length);
- } catch (e) {
- throw new Error('Invalid windowing function');
+ // try to strip useless frames
+ var fn_name = getName(stackStartFunction);
+ var idx = out.indexOf('\n' + fn_name);
+ if (idx >= 0) {
+ // once we have located the function frame
+ // we need to strip out everything before it (and its line)
+ var next_line = out.indexOf('\n', idx + 1);
+ out = out.substring(next_line + 1);
}
- }
- signal = pointwiseBufferMult(signal, windows[windowname][signal.length]);
+ this.stack = out;
+ }
}
+};
- return signal;
-}
-function createBarkScale(length, sampleRate, bufferSize) {
- var barkScale = new Float32Array(length);
+// assert.AssertionError instanceof Error
+util.inherits(assert.AssertionError, Error);
- for (var i = 0; i < barkScale.length; i++) {
- barkScale[i] = i * sampleRate / bufferSize;
- barkScale[i] = 13 * Math.atan(barkScale[i] / 1315.8) + 3.5 * Math.atan(Math.pow(barkScale[i] / 7518, 2));
+function truncate(s, n) {
+ if (typeof s === 'string') {
+ return s.length < n ? s : s.slice(0, n);
+ } else {
+ return s;
}
-
- return barkScale;
-}
-function typedToArray(t) {
- // utility to convert typed arrays to normal arrays
- return Array.prototype.slice.call(t);
-}
-function arrayToTyped(t) {
- // utility to convert arrays to typed F32 arrays
- return Float32Array.from(t);
-}
-function _normalize(num, range) {
- return num / range;
-}
-function normalize(a, range) {
- return a.map(function (n) {
- return _normalize(n, range);
- });
}
-function normalizeToOne(a) {
- var max = Math.max.apply(null, a);
- return a.map(function (n) {
- return n / max;
- });
+function inspect(something) {
+ if (functionsHaveNames || !util.isFunction(something)) {
+ return util.inspect(something);
+ }
+ var rawname = getName(something);
+ var name = rawname ? ': ' + rawname : '';
+ return '[Function' + name + ']';
}
-function mean(a) {
- return a.reduce(function (prev, cur) {
- return prev + cur;
- }) / a.length;
+function getMessage(self) {
+ return truncate(inspect(self.actual), 128) + ' ' +
+ self.operator + ' ' +
+ truncate(inspect(self.expected), 128);
}
-function _melToFreq(melValue) {
- var freqValue = 700 * (Math.exp(melValue / 1125) - 1);
- return freqValue;
-}
+// At present only the three keys mentioned above are used and
+// understood by the spec. Implementations or sub modules can pass
+// other keys to the AssertionError's constructor - they will be
+// ignored.
-function _freqToMel(freqValue) {
- var melValue = 1125 * Math.log(1 + freqValue / 700);
- return melValue;
-}
+// 3. All of the following functions must throw an AssertionError
+// when a corresponding condition is not met, with a message that
+// may be undefined if not provided. All assertion methods provide
+// both the actual and expected values to the assertion error for
+// display purposes.
-function melToFreq(mV) {
- return _melToFreq(mV);
-}
-function freqToMel(fV) {
- return _freqToMel(fV);
+function fail(actual, expected, message, operator, stackStartFunction) {
+ throw new assert.AssertionError({
+ message: message,
+ actual: actual,
+ expected: expected,
+ operator: operator,
+ stackStartFunction: stackStartFunction
+ });
}
-function createMelFilterBank(numFilters, sampleRate, bufferSize) {
- //the +2 is the upper and lower limits
- var melValues = new Float32Array(numFilters + 2);
- var melValuesInFreq = new Float32Array(numFilters + 2); //Generate limits in Hz - from 0 to the nyquist.
-
- var lowerLimitFreq = 0;
- var upperLimitFreq = sampleRate / 2; //Convert the limits to Mel
-
- var lowerLimitMel = _freqToMel(lowerLimitFreq);
-
- var upperLimitMel = _freqToMel(upperLimitFreq); //Find the range
-
-
- var range = upperLimitMel - lowerLimitMel; //Find the range as part of the linear interpolation
-
- var valueToAdd = range / (numFilters + 1);
- var fftBinsOfFreq = Array(numFilters + 2);
- for (var i = 0; i < melValues.length; i++) {
- // Initialising the mel frequencies
- // They're a linear interpolation between the lower and upper limits.
- melValues[i] = i * valueToAdd; // Convert back to Hz
+// EXTENSION! allows for well behaved errors defined elsewhere.
+assert.fail = fail;
- melValuesInFreq[i] = _melToFreq(melValues[i]); // Find the corresponding bins
+// 4. Pure assertion tests whether a value is truthy, as determined
+// by !!guard.
+// assert.ok(guard, message_opt);
+// This statement is equivalent to assert.equal(true, !!guard,
+// message_opt);. To test strictly for the value true, use
+// assert.strictEqual(true, guard, message_opt);.
- fftBinsOfFreq[i] = Math.floor((bufferSize + 1) * melValuesInFreq[i] / sampleRate);
- }
+function ok(value, message) {
+ if (!value) fail(value, true, message, '==', assert.ok);
+}
+assert.ok = ok;
- var filterBank = Array(numFilters);
+// 5. The equality assertion tests shallow, coercive equality with
+// ==.
+// assert.equal(actual, expected, message_opt);
- for (var j = 0; j < filterBank.length; j++) {
- // Create a two dimensional array of size numFilters * (buffersize/2)+1
- // pre-populating the arrays with 0s.
- filterBank[j] = Array.apply(null, new Array(bufferSize / 2 + 1)).map(Number.prototype.valueOf, 0); //creating the lower and upper slopes for each bin
+assert.equal = function equal(actual, expected, message) {
+ if (actual != expected) fail(actual, expected, message, '==', assert.equal);
+};
- for (var _i = fftBinsOfFreq[j]; _i < fftBinsOfFreq[j + 1]; _i++) {
- filterBank[j][_i] = (_i - fftBinsOfFreq[j]) / (fftBinsOfFreq[j + 1] - fftBinsOfFreq[j]);
- }
+// 6. The non-equality assertion tests for whether two objects are not equal
+// with != assert.notEqual(actual, expected, message_opt);
- for (var _i2 = fftBinsOfFreq[j + 1]; _i2 < fftBinsOfFreq[j + 2]; _i2++) {
- filterBank[j][_i2] = (fftBinsOfFreq[j + 2] - _i2) / (fftBinsOfFreq[j + 2] - fftBinsOfFreq[j + 1]);
- }
+assert.notEqual = function notEqual(actual, expected, message) {
+ if (actual == expected) {
+ fail(actual, expected, message, '!=', assert.notEqual);
}
+};
- return filterBank;
-}
-function hzToOctaves(freq, A440) {
- return Math.log2(16 * freq / A440);
-}
-function normalizeByColumn(a) {
- var emptyRow = a[0].map(function () {
- return 0;
- });
- var colDenominators = a.reduce(function (acc, row) {
- row.forEach(function (cell, j) {
- acc[j] += Math.pow(cell, 2);
- });
- return acc;
- }, emptyRow).map(Math.sqrt);
- return a.map(function (row, i) {
- return row.map(function (v, j) {
- return v / (colDenominators[j] || 1);
- });
- });
-}
-;
-function createChromaFilterBank(numFilters, sampleRate, bufferSize) {
- var centerOctave = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5;
- var octaveWidth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 2;
- var baseC = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
- var A440 = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 440;
- var numOutputBins = Math.floor(bufferSize / 2) + 1;
- var frequencyBins = new Array(bufferSize).fill(0).map(function (_, i) {
- return numFilters * hzToOctaves(sampleRate * i / bufferSize, A440);
- }); // Set a value for the 0 Hz bin that is 1.5 octaves below bin 1
- // (so chroma is 50% rotated from bin 1, and bin width is broad)
-
- frequencyBins[0] = frequencyBins[1] - 1.5 * numFilters;
- var binWidthBins = frequencyBins.slice(1).map(function (v, i) {
- return Math.max(v - frequencyBins[i]);
- }, 1).concat([1]);
- var halfNumFilters = Math.round(numFilters / 2);
- var filterPeaks = new Array(numFilters).fill(0).map(function (_, i) {
- return frequencyBins.map(function (frq) {
- return (10 * numFilters + halfNumFilters + frq - i) % numFilters - halfNumFilters;
- });
- });
- var weights = filterPeaks.map(function (row, i) {
- return row.map(function (_, j) {
- return Math.exp(-0.5 * Math.pow(2 * filterPeaks[i][j] / binWidthBins[j], 2));
- });
- });
- weights = normalizeByColumn(weights);
-
- if (octaveWidth) {
- var octaveWeights = frequencyBins.map(function (v) {
- return Math.exp(-0.5 * Math.pow((v / numFilters - centerOctave) / octaveWidth, 2));
- });
- weights = weights.map(function (row) {
- return row.map(function (cell, j) {
- return cell * octaveWeights[j];
- });
- });
- }
+// 7. The equivalence assertion tests a deep equality relation.
+// assert.deepEqual(actual, expected, message_opt);
- if (baseC) {
- weights = [].concat(_toConsumableArray(weights.slice(3)), _toConsumableArray(weights.slice(0, 3)));
+assert.deepEqual = function deepEqual(actual, expected, message) {
+ if (!_deepEqual(actual, expected, false)) {
+ fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
+};
- return weights.map(function (row) {
- return row.slice(0, numOutputBins);
- });
-}
-function frame(buffer, frameLength, hopLength) {
- if (buffer.length < frameLength) {
- throw new Error('Buffer is too short for frame length');
+assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
+ if (!_deepEqual(actual, expected, true)) {
+ fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
+};
- if (hopLength < 1) {
- throw new Error('Hop length cannot be less that 1');
- }
+function _deepEqual(actual, expected, strict, memos) {
+ // 7.1. All identical values are equivalent, as determined by ===.
+ if (actual === expected) {
+ return true;
+ } else if (isBuffer(actual) && isBuffer(expected)) {
+ return compare(actual, expected) === 0;
- if (frameLength < 1) {
- throw new Error('Frame length cannot be less that 1');
- }
+ // 7.2. If the expected value is a Date object, the actual value is
+ // equivalent if it is also a Date object that refers to the same time.
+ } else if (util.isDate(actual) && util.isDate(expected)) {
+ return actual.getTime() === expected.getTime();
- var numFrames = 1 + Math.floor((buffer.length - frameLength) / hopLength);
- return new Array(numFrames).fill(0).map(function (_, i) {
- return buffer.slice(i * hopLength, i * hopLength + frameLength);
- });
-}
+ // 7.3 If the expected value is a RegExp object, the actual value is
+ // equivalent if it is also a RegExp object with the same source and
+ // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
+ } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
+ return actual.source === expected.source &&
+ actual.global === expected.global &&
+ actual.multiline === expected.multiline &&
+ actual.lastIndex === expected.lastIndex &&
+ actual.ignoreCase === expected.ignoreCase;
-/***/ }),
+ // 7.4. Other pairs that do not both pass typeof value == 'object',
+ // equivalence is determined by ==.
+ } else if ((actual === null || typeof actual !== 'object') &&
+ (expected === null || typeof expected !== 'object')) {
+ return strict ? actual === expected : actual == expected;
-/***/ "./src/windowing.js":
-/*!**************************!*\
- !*** ./src/windowing.js ***!
- \**************************/
-/*! exports provided: blackman, sine, hanning, hamming */
-/***/ (function(module, __webpack_exports__, __webpack_require__) {
+ // If both values are instances of typed arrays, wrap their underlying
+ // ArrayBuffers in a Buffer each to increase performance
+ // This optimization requires the arrays to have the same type as checked by
+ // Object.prototype.toString (aka pToString). Never perform binary
+ // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
+ // bit patterns are not identical.
+ } else if (isView(actual) && isView(expected) &&
+ pToString(actual) === pToString(expected) &&
+ !(actual instanceof Float32Array ||
+ actual instanceof Float64Array)) {
+ return compare(new Uint8Array(actual.buffer),
+ new Uint8Array(expected.buffer)) === 0;
-"use strict";
-__webpack_require__.r(__webpack_exports__);
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "blackman", function() { return blackman; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sine", function() { return sine; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hanning", function() { return hanning; });
-/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hamming", function() { return hamming; });
-function blackman(size) {
- var blackmanBuffer = new Float32Array(size);
- var coeff1 = 2 * Math.PI / (size - 1);
- var coeff2 = 2 * coeff1; //According to http://uk.mathworks.com/help/signal/ref/blackman.html
- //first half of the window
+ // 7.5 For all other Object pairs, including Array objects, equivalence is
+ // determined by having the same number of owned properties (as verified
+ // with Object.prototype.hasOwnProperty.call), the same set of keys
+ // (although not necessarily the same order), equivalent values for every
+ // corresponding key, and an identical 'prototype' property. Note: this
+ // accounts for both named and indexed properties on Arrays.
+ } else if (isBuffer(actual) !== isBuffer(expected)) {
+ return false;
+ } else {
+ memos = memos || {actual: [], expected: []};
- for (var i = 0; i < size / 2; i++) {
- blackmanBuffer[i] = 0.42 - 0.5 * Math.cos(i * coeff1) + 0.08 * Math.cos(i * coeff2);
- } //second half of the window
+ var actualIndex = memos.actual.indexOf(actual);
+ if (actualIndex !== -1) {
+ if (actualIndex === memos.expected.indexOf(expected)) {
+ return true;
+ }
+ }
+ memos.actual.push(actual);
+ memos.expected.push(expected);
- for (var _i = size / 2; _i > 0; _i--) {
- blackmanBuffer[size - _i] = blackmanBuffer[_i - 1];
+ return objEquiv(actual, expected, strict, memos);
}
-
- return blackmanBuffer;
}
-function sine(size) {
- var coeff = Math.PI / (size - 1);
- var sineBuffer = new Float32Array(size);
-
- for (var i = 0; i < size; i++) {
- sineBuffer[i] = Math.sin(coeff * i);
- }
- return sineBuffer;
+function isArguments(object) {
+ return Object.prototype.toString.call(object) == '[object Arguments]';
}
-function hanning(size) {
- var hanningBuffer = new Float32Array(size);
- for (var i = 0; i < size; i++) {
- // According to the R documentation
- // http://ugrad.stat.ubc.ca/R/library/e1071/html/hanning.window.html
- hanningBuffer[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (size - 1));
+function objEquiv(a, b, strict, actualVisitedObjects) {
+ if (a === null || a === undefined || b === null || b === undefined)
+ return false;
+ // if one is a primitive, the other must be same
+ if (util.isPrimitive(a) || util.isPrimitive(b))
+ return a === b;
+ if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
+ return false;
+ var aIsArgs = isArguments(a);
+ var bIsArgs = isArguments(b);
+ if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
+ return false;
+ if (aIsArgs) {
+ a = pSlice.call(a);
+ b = pSlice.call(b);
+ return _deepEqual(a, b, strict);
}
-
- return hanningBuffer;
+ var ka = objectKeys(a);
+ var kb = objectKeys(b);
+ var key, i;
+ // having the same number of owned properties (keys incorporates
+ // hasOwnProperty)
+ if (ka.length !== kb.length)
+ return false;
+ //the same set of keys (although not necessarily the same order),
+ ka.sort();
+ kb.sort();
+ //~~~cheap key test
+ for (i = ka.length - 1; i >= 0; i--) {
+ if (ka[i] !== kb[i])
+ return false;
+ }
+ //equivalent values for every corresponding key, and
+ //~~~possibly expensive deep test
+ for (i = ka.length - 1; i >= 0; i--) {
+ key = ka[i];
+ if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
+ return false;
+ }
+ return true;
}
-function hamming(size) {
- var hammingBuffer = new Float32Array(size);
- for (var i = 0; i < size; i++) {
- //According to http://uk.mathworks.com/help/signal/ref/hamming.html
- hammingBuffer[i] = 0.54 - 0.46 * Math.cos(2 * Math.PI * (i / size - 1));
+// 8. The non-equivalence assertion tests for any deep inequality.
+// assert.notDeepEqual(actual, expected, message_opt);
+
+assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
+ if (_deepEqual(actual, expected, false)) {
+ fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
+};
- return hammingBuffer;
+assert.notDeepStrictEqual = notDeepStrictEqual;
+function notDeepStrictEqual(actual, expected, message) {
+ if (_deepEqual(actual, expected, true)) {
+ fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
+ }
}
-/***/ })
-
-/******/ });
-});
-},{}],85:[function(require,module,exports){
-assert.notEqual = notEqual
-assert.notOk = notOk
-assert.equal = equal
-assert.ok = assert
+// 9. The strict equality assertion tests strict equality, as determined by ===.
+// assert.strictEqual(actual, expected, message_opt);
-module.exports = assert
+assert.strictEqual = function strictEqual(actual, expected, message) {
+ if (actual !== expected) {
+ fail(actual, expected, message, '===', assert.strictEqual);
+ }
+};
-function equal (a, b, m) {
- assert(a == b, m) // eslint-disable-line eqeqeq
-}
+// 10. The strict non-equality assertion tests for strict inequality, as
+// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
-function notEqual (a, b, m) {
- assert(a != b, m) // eslint-disable-line eqeqeq
-}
+assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
+ if (actual === expected) {
+ fail(actual, expected, message, '!==', assert.notStrictEqual);
+ }
+};
-function notOk (t, m) {
- assert(!t, m)
-}
+function expectedException(actual, expected) {
+ if (!actual || !expected) {
+ return false;
+ }
-function assert (t, m) {
- if (!t) throw new Error(m || 'AssertionError')
-}
+ if (Object.prototype.toString.call(expected) == '[object RegExp]') {
+ return expected.test(actual);
+ }
-},{}],86:[function(require,module,exports){
-var splice = require('remove-array-items')
-var nanotiming = require('nanotiming')
-var assert = require('assert')
+ try {
+ if (actual instanceof expected) {
+ return true;
+ }
+ } catch (e) {
+ // Ignore. The instanceof check doesn't work for arrow functions.
+ }
-module.exports = Nanobus
+ if (Error.isPrototypeOf(expected)) {
+ return false;
+ }
-function Nanobus (name) {
- if (!(this instanceof Nanobus)) return new Nanobus(name)
+ return expected.call({}, actual) === true;
+}
- this._name = name || 'nanobus'
- this._starListeners = []
- this._listeners = {}
+function _tryBlock(block) {
+ var error;
+ try {
+ block();
+ } catch (e) {
+ error = e;
+ }
+ return error;
}
-Nanobus.prototype.emit = function (eventName) {
- assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.emit: eventName should be type string or symbol')
+function _throws(shouldThrow, block, expected, message) {
+ var actual;
- var data = []
- for (var i = 1, len = arguments.length; i < len; i++) {
- data.push(arguments[i])
+ if (typeof block !== 'function') {
+ throw new TypeError('"block" argument must be a function');
}
- var emitTiming = nanotiming(this._name + "('" + eventName.toString() + "')")
- var listeners = this._listeners[eventName]
- if (listeners && listeners.length > 0) {
- this._emit(this._listeners[eventName], data)
+ if (typeof expected === 'string') {
+ message = expected;
+ expected = null;
}
- if (this._starListeners.length > 0) {
- this._emit(this._starListeners, eventName, data, emitTiming.uuid)
+ actual = _tryBlock(block);
+
+ message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
+ (message ? ' ' + message : '.');
+
+ if (shouldThrow && !actual) {
+ fail(actual, expected, 'Missing expected exception' + message);
}
- emitTiming()
- return this
-}
+ var userProvidedMessage = typeof message === 'string';
+ var isUnwantedException = !shouldThrow && util.isError(actual);
+ var isUnexpectedException = !shouldThrow && actual && !expected;
-Nanobus.prototype.on = Nanobus.prototype.addListener = function (eventName, listener) {
- assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.on: eventName should be type string or symbol')
- assert.equal(typeof listener, 'function', 'nanobus.on: listener should be type function')
+ if ((isUnwantedException &&
+ userProvidedMessage &&
+ expectedException(actual, expected)) ||
+ isUnexpectedException) {
+ fail(actual, expected, 'Got unwanted exception' + message);
+ }
- if (eventName === '*') {
- this._starListeners.push(listener)
- } else {
- if (!this._listeners[eventName]) this._listeners[eventName] = []
- this._listeners[eventName].push(listener)
+ if ((shouldThrow && actual && expected &&
+ !expectedException(actual, expected)) || (!shouldThrow && actual)) {
+ throw actual;
}
- return this
}
-Nanobus.prototype.prependListener = function (eventName, listener) {
- assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.prependListener: eventName should be type string or symbol')
- assert.equal(typeof listener, 'function', 'nanobus.prependListener: listener should be type function')
+// 11. Expected to throw an error:
+// assert.throws(block, Error_opt, message_opt);
- if (eventName === '*') {
- this._starListeners.unshift(listener)
- } else {
- if (!this._listeners[eventName]) this._listeners[eventName] = []
- this._listeners[eventName].unshift(listener)
- }
- return this
-}
+assert.throws = function(block, /*optional*/error, /*optional*/message) {
+ _throws(true, block, error, message);
+};
-Nanobus.prototype.once = function (eventName, listener) {
- assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.once: eventName should be type string or symbol')
- assert.equal(typeof listener, 'function', 'nanobus.once: listener should be type function')
+// EXTENSION! This is annoying to write outside this module.
+assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
+ _throws(false, block, error, message);
+};
- var self = this
- this.on(eventName, once)
- function once () {
- listener.apply(self, arguments)
- self.removeListener(eventName, once)
+assert.ifError = function(err) { if (err) throw err; };
+
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) {
+ if (hasOwn.call(obj, key)) keys.push(key);
}
- return this
-}
+ return keys;
+};
-Nanobus.prototype.prependOnceListener = function (eventName, listener) {
- assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.prependOnceListener: eventName should be type string or symbol')
- assert.equal(typeof listener, 'function', 'nanobus.prependOnceListener: listener should be type function')
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack-stream/node_modules/webpack/buildin/global.js */ "./node_modules/webpack-stream/node_modules/webpack/buildin/global.js")))
- var self = this
- this.prependListener(eventName, once)
- function once () {
- listener.apply(self, arguments)
- self.removeListener(eventName, once)
- }
- return this
-}
+/***/ }),
-Nanobus.prototype.removeListener = function (eventName, listener) {
- assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.removeListener: eventName should be type string or symbol')
- assert.equal(typeof listener, 'function', 'nanobus.removeListener: listener should be type function')
+/***/ "./node_modules/dct/index.js":
+/*!***********************************!*\
+ !*** ./node_modules/dct/index.js ***!
+ \***********************************/
+/*! no static exports found */
+/***/ (function(module, exports, __webpack_require__) {
- if (eventName === '*') {
- this._starListeners = this._starListeners.slice()
- return remove(this._starListeners, listener)
- } else {
- if (typeof this._listeners[eventName] !== 'undefined') {
- this._listeners[eventName] = this._listeners[eventName].slice()
- }
+module.exports = __webpack_require__(/*! ./src/dct.js */ "./node_modules/dct/src/dct.js");
- return remove(this._listeners[eventName], listener)
- }
- function remove (arr, listener) {
- if (!arr) return
- var index = arr.indexOf(listener)
- if (index !== -1) {
- splice(arr, index, 1)
- return true
- }
- }
-}
+/***/ }),
-Nanobus.prototype.removeAllListeners = function (eventName) {
- if (eventName) {
- if (eventName === '*') {
- this._starListeners = []
- } else {
- this._listeners[eventName] = []
- }
- } else {
- this._starListeners = []
- this._listeners = {}
- }
- return this
-}
+/***/ "./node_modules/dct/src/dct.js":
+/*!*************************************!*\
+ !*** ./node_modules/dct/src/dct.js ***!
+ \*************************************/
+/*! no static exports found */
+/***/ (function(module, exports) {
-Nanobus.prototype.listeners = function (eventName) {
- var listeners = eventName !== '*'
- ? this._listeners[eventName]
- : this._starListeners
+/*===========================================================================*\
+ * Discrete Cosine Transform
+ *
+ * (c) Vail Systems. Joshua Jung and Ben Bryan. 2015
+ *
+ * This code is not designed to be highly optimized but as an educational
+ * tool to understand the Mel-scale and its related coefficients used in
+ * human speech analysis.
+\*===========================================================================*/
+var cosMap = null;
- var ret = []
- if (listeners) {
- var ilength = listeners.length
- for (var i = 0; i < ilength; i++) ret.push(listeners[i])
- }
- return ret
-}
+// Builds a cosine map for the given input size. This allows multiple input sizes to be memoized automagically
+// if you want to run the DCT over and over.
+var memoizeCosines = function(N) {
+ cosMap = cosMap || {};
+ cosMap[N] = new Array(N*N);
-Nanobus.prototype._emit = function (arr, eventName, data, uuid) {
- if (typeof arr === 'undefined') return
- if (arr.length === 0) return
- if (data === undefined) {
- data = eventName
- eventName = null
- }
+ var PI_N = Math.PI / N;
- if (eventName) {
- if (uuid !== undefined) {
- data = [eventName].concat(data, uuid)
- } else {
- data = [eventName].concat(data)
+ for (var k = 0; k < N; k++) {
+ for (var n = 0; n < N; n++) {
+ cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k);
}
}
+};
- var length = arr.length
- for (var i = 0; i < length; i++) {
- var listener = arr[i]
- listener.apply(listener, data)
- }
-}
+function dct(signal, scale) {
+ var L = signal.length;
+ scale = scale || 2;
-},{"assert":85,"nanotiming":106,"remove-array-items":116}],87:[function(require,module,exports){
-const document = require('global/document')
-const nanotiming = require('nanotiming')
-const morph = require('nanomorph')
-const onload = require('on-load')
-const assert = require('assert')
+ if (!cosMap || !cosMap[L]) memoizeCosines(L);
-const OL_KEY_ID = onload.KEY_ID
-const OL_ATTR_ID = onload.KEY_ATTR
+ var coefficients = signal.map(function () {return 0;});
-module.exports = Nanocomponent
+ return coefficients.map(function (__, ix) {
+ return scale * signal.reduce(function (prev, cur, ix_, arr) {
+ return prev + (cur * cosMap[L][ix_ + (ix * L)]);
+ }, 0);
+ });
+};
-function makeID () {
- return 'ncid-' + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
-}
+module.exports = dct;
-Nanocomponent.makeID = makeID
-function Nanocomponent (name) {
- this._hasWindow = typeof window !== 'undefined'
- this._id = null // represents the id of the root node
- this._ncID = null // internal nanocomponent id
- this._olID = null
- this._proxy = null
- this._loaded = false // Used to debounce on-load when child-reordering
- this._rootNodeName = null
- this._name = name || 'nanocomponent'
- this._rerender = false
+/***/ }),
- this._handleLoad = this._handleLoad.bind(this)
- this._handleUnload = this._handleUnload.bind(this)
+/***/ "./node_modules/fftjs/dist/fft.js":
+/*!****************************************!*\
+ !*** ./node_modules/fftjs/dist/fft.js ***!
+ \****************************************/
+/*! no static exports found */
+/***/ (function(module, exports, __webpack_require__) {
- this._arguments = []
+"use strict";
- const self = this
- Object.defineProperty(this, 'element', {
- get: function () {
- const el = document.getElementById(self._id)
- if (el) return el.dataset.nanocomponent === self._ncID ? el : undefined
- }
- })
-}
+var utils = __webpack_require__(/*! ./utils */ "./node_modules/fftjs/dist/utils.js");
-Nanocomponent.prototype.render = function () {
- const renderTiming = nanotiming(this._name + '.render')
- const self = this
- const args = new Array(arguments.length)
- let el
+// real to complex fft
+var fft = function fft(signal) {
- for (let i = 0; i < arguments.length; i++) args[i] = arguments[i]
- if (!this._hasWindow) {
- const createTiming = nanotiming(this._name + '.create')
- el = this.createElement.apply(this, args)
- createTiming()
- renderTiming()
- return el
- } else if (this.element) {
- el = this.element // retain reference, as the ID might change on render
- const updateTiming = nanotiming(this._name + '.update')
- const shouldUpdate = this._rerender || this.update.apply(this, args)
- updateTiming()
- if (this._rerender) this._rerender = false
- if (shouldUpdate) {
- const desiredHtml = this._handleRender(args)
- const morphTiming = nanotiming(this._name + '.morph')
- morph(el, desiredHtml)
- morphTiming()
- if (this.afterupdate) this.afterupdate(el)
- }
- if (!this._proxy) { this._proxy = this._createProxy() }
- renderTiming()
- return this._proxy
+ var complexSignal = {};
+
+ if (signal.real === undefined || signal.imag === undefined) {
+ complexSignal = utils.constructComplexArray(signal);
} else {
- this._reset()
- el = this._handleRender(args)
- if (this.beforerender) this.beforerender(el)
- if (this.load || this.unload || this.afterreorder) {
- onload(el, self._handleLoad, self._handleUnload, self._ncID)
- this._olID = el.dataset[OL_KEY_ID]
- }
- renderTiming()
- return el
+ complexSignal.real = signal.real.slice();
+ complexSignal.imag = signal.imag.slice();
}
-}
-Nanocomponent.prototype.rerender = function () {
- assert(this.element, 'nanocomponent: cant rerender on an unmounted dom node')
- this._rerender = true
- this.render.apply(this, this._arguments)
-}
+ var N = complexSignal.real.length;
+ var logN = Math.log2(N);
-Nanocomponent.prototype._handleRender = function (args) {
- const createElementTiming = nanotiming(this._name + '.createElement')
- const el = this.createElement.apply(this, args)
- createElementTiming()
- if (!this._rootNodeName) this._rootNodeName = el.nodeName
- assert(el instanceof window.Element, 'nanocomponent: createElement should return a single DOM node')
- assert(this._rootNodeName === el.nodeName, 'nanocomponent: root node types cannot differ between re-renders')
- this._arguments = args
- return this._brandNode(this._ensureID(el))
-}
+ if (Math.round(logN) != logN) throw new Error('Input size must be a power of 2.');
-Nanocomponent.prototype._createProxy = function () {
- const proxy = document.createElement(this._rootNodeName)
- const self = this
- this._brandNode(proxy)
- proxy.id = this._id
- proxy.setAttribute('data-proxy', '')
- proxy.isSameNode = function (el) {
- return (el && el.dataset.nanocomponent === self._ncID)
+ if (complexSignal.real.length != complexSignal.imag.length) {
+ throw new Error('Real and imaginary components must have the same length.');
}
- return proxy
-}
-Nanocomponent.prototype._reset = function () {
- this._ncID = Nanocomponent.makeID()
- this._olID = null
- this._id = null
- this._proxy = null
- this._rootNodeName = null
-}
+ var bitReversedIndices = utils.bitReverseArray(N);
-Nanocomponent.prototype._brandNode = function (node) {
- node.setAttribute('data-nanocomponent', this._ncID)
- if (this._olID) node.setAttribute(OL_ATTR_ID, this._olID)
- return node
-}
+ // sort array
+ var ordered = {
+ 'real': [],
+ 'imag': []
+ };
-Nanocomponent.prototype._ensureID = function (node) {
- if (node.id) this._id = node.id
- else node.id = this._id = this._ncID
- // Update proxy node ID if it changed
- if (this._proxy && this._proxy.id !== this._id) this._proxy.id = this._id
- return node
-}
+ for (var i = 0; i < N; i++) {
+ ordered.real[bitReversedIndices[i]] = complexSignal.real[i];
+ ordered.imag[bitReversedIndices[i]] = complexSignal.imag[i];
+ }
-Nanocomponent.prototype._handleLoad = function (el) {
- if (this._loaded) {
- if (this.afterreorder) this.afterreorder(el)
- return // Debounce child-reorders
+ for (var _i = 0; _i < N; _i++) {
+ complexSignal.real[_i] = ordered.real[_i];
+ complexSignal.imag[_i] = ordered.imag[_i];
}
- this._loaded = true
- if (this.load) this.load(el)
-}
+ // iterate over the number of stages
+ for (var n = 1; n <= logN; n++) {
+ var currN = Math.pow(2, n);
-Nanocomponent.prototype._handleUnload = function (el) {
- if (this.element) return // Debounce child-reorders
- this._loaded = false
- if (this.unload) this.unload(el)
-}
+ // find twiddle factors
+ for (var k = 0; k < currN / 2; k++) {
+ var twiddle = utils.euler(k, currN);
-Nanocomponent.prototype.createElement = function () {
- throw new Error('nanocomponent: createElement should be implemented!')
-}
+ // on each block of FT, implement the butterfly diagram
+ for (var m = 0; m < N / currN; m++) {
+ var currEvenIndex = currN * m + k;
+ var currOddIndex = currN * m + k + currN / 2;
-Nanocomponent.prototype.update = function () {
- throw new Error('nanocomponent: update should be implemented!')
-}
+ var currEvenIndexSample = {
+ 'real': complexSignal.real[currEvenIndex],
+ 'imag': complexSignal.imag[currEvenIndex]
+ };
+ var currOddIndexSample = {
+ 'real': complexSignal.real[currOddIndex],
+ 'imag': complexSignal.imag[currOddIndex]
+ };
-},{"assert":88,"global/document":77,"nanomorph":99,"nanotiming":106,"on-load":108}],88:[function(require,module,exports){
-module.exports = assert
+ var odd = utils.multiply(twiddle, currOddIndexSample);
-class AssertionError extends Error {}
-AssertionError.prototype.name = 'AssertionError'
+ var subtractionResult = utils.subtract(currEvenIndexSample, odd);
+ complexSignal.real[currOddIndex] = subtractionResult.real;
+ complexSignal.imag[currOddIndex] = subtractionResult.imag;
-/**
- * Minimal assert function
- * @param {any} t Value to check if falsy
- * @param {string=} m Optional assertion error message
- * @throws {AssertionError}
- */
-function assert (t, m) {
- if (!t) {
- var err = new AssertionError(m)
- if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
- throw err
+ var additionResult = utils.add(odd, currEvenIndexSample);
+ complexSignal.real[currEvenIndex] = additionResult.real;
+ complexSignal.imag[currEvenIndex] = additionResult.imag;
+ }
+ }
}
-}
-
-},{}],89:[function(require,module,exports){
-var assert = require('assert')
-
-var safeExternalLink = /(noopener|noreferrer) (noopener|noreferrer)/
-var protocolLink = /^[\w-_]+:/
-module.exports = href
+ return complexSignal;
+};
-function href (cb, root) {
- assert.notEqual(typeof window, 'undefined', 'nanohref: expected window to exist')
+// complex to real ifft
+var ifft = function ifft(signal) {
- root = root || window.document
+ if (signal.real === undefined || signal.imag === undefined) {
+ throw new Error("IFFT only accepts a complex input.");
+ }
- assert.equal(typeof cb, 'function', 'nanohref: cb should be type function')
- assert.equal(typeof root, 'object', 'nanohref: root should be type object')
+ var N = signal.real.length;
- window.addEventListener('click', function (e) {
- if ((e.button && e.button !== 0) ||
- e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ||
- e.defaultPrevented) return
+ var complexSignal = {
+ 'real': [],
+ 'imag': []
+ };
- var anchor = (function traverse (node) {
- if (!node || node === root) return
- if (node.localName !== 'a' || node.href === undefined) {
- return traverse(node.parentNode)
- }
- return node
- })(e.target)
+ //take complex conjugate in order to be able to use the regular FFT for IFFT
+ for (var i = 0; i < N; i++) {
+ var currentSample = {
+ 'real': signal.real[i],
+ 'imag': signal.imag[i]
+ };
- if (!anchor) return
+ var conjugateSample = utils.conj(currentSample);
+ complexSignal.real[i] = conjugateSample.real;
+ complexSignal.imag[i] = conjugateSample.imag;
+ }
- if (window.location.protocol !== anchor.protocol ||
- window.location.hostname !== anchor.hostname ||
- window.location.port !== anchor.port ||
- anchor.hasAttribute('data-nanohref-ignore') ||
- anchor.hasAttribute('download') ||
- (anchor.getAttribute('target') === '_blank' &&
- safeExternalLink.test(anchor.getAttribute('rel'))) ||
- protocolLink.test(anchor.getAttribute('href'))) return
+ //compute
+ var X = fft(complexSignal);
- e.preventDefault()
- cb(anchor)
- })
-}
+ //normalize
+ complexSignal.real = X.real.map(function (val) {
+ return val / N;
+ });
-},{"assert":85}],90:[function(require,module,exports){
-'use strict'
+ complexSignal.imag = X.imag.map(function (val) {
+ return val / N;
+ });
-var trailingNewlineRegex = /\n[\s]+$/
-var leadingNewlineRegex = /^\n[\s]+/
-var trailingSpaceRegex = /[\s]+$/
-var leadingSpaceRegex = /^[\s]+/
-var multiSpaceRegex = /[\n\s]+/g
+ return complexSignal;
+};
-var TEXT_TAGS = [
- 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'data', 'dfn', 'em', 'i',
- 'kbd', 'mark', 'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'amp', 'small', 'span',
- 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr'
-]
+module.exports = {
+ fft: fft,
+ ifft: ifft
+};
-var VERBATIM_TAGS = [
- 'code', 'pre', 'textarea'
-]
+/***/ }),
-module.exports = function appendChild (el, childs) {
- if (!Array.isArray(childs)) return
+/***/ "./node_modules/fftjs/dist/utils.js":
+/*!******************************************!*\
+ !*** ./node_modules/fftjs/dist/utils.js ***!
+ \******************************************/
+/*! no static exports found */
+/***/ (function(module, exports, __webpack_require__) {
- var nodeName = el.nodeName.toLowerCase()
+"use strict";
- var hadText = false
- var value, leader
- for (var i = 0, len = childs.length; i < len; i++) {
- var node = childs[i]
- if (Array.isArray(node)) {
- appendChild(el, node)
- continue
- }
+// memoization of the reversal of different lengths.
- if (typeof node === 'number' ||
- typeof node === 'boolean' ||
- typeof node === 'function' ||
- node instanceof Date ||
- node instanceof RegExp) {
- node = node.toString()
- }
+function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
- var lastChild = el.childNodes[el.childNodes.length - 1]
+var memoizedReversal = {};
+var memoizedZeroBuffers = {};
- // Iterate over text nodes
- if (typeof node === 'string') {
- hadText = true
+var constructComplexArray = function constructComplexArray(signal) {
+ var complexSignal = {};
- // If we already had text, append to the existing text
- if (lastChild && lastChild.nodeName === '#text') {
- lastChild.nodeValue += node
+ complexSignal.real = signal.real === undefined ? signal.slice() : signal.real.slice();
- // We didn't have a text node yet, create one
- } else {
- node = el.ownerDocument.createTextNode(node)
- el.appendChild(node)
- lastChild = node
- }
+ var bufferSize = complexSignal.real.length;
- // If this is the last of the child nodes, make sure we close it out
- // right
- if (i === len - 1) {
- hadText = false
- // Trim the child text nodes if the current node isn't a
- // node where whitespace matters.
- if (TEXT_TAGS.indexOf(nodeName) === -1 &&
- VERBATIM_TAGS.indexOf(nodeName) === -1) {
- value = lastChild.nodeValue
- .replace(leadingNewlineRegex, '')
- .replace(trailingSpaceRegex, '')
- .replace(trailingNewlineRegex, '')
- .replace(multiSpaceRegex, ' ')
- if (value === '') {
- el.removeChild(lastChild)
- } else {
- lastChild.nodeValue = value
- }
- } else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
- // The very first node in the list should not have leading
- // whitespace. Sibling text nodes should have whitespace if there
- // was any.
- leader = i === 0 ? '' : ' '
- value = lastChild.nodeValue
- .replace(leadingNewlineRegex, leader)
- .replace(leadingSpaceRegex, ' ')
- .replace(trailingSpaceRegex, '')
- .replace(trailingNewlineRegex, '')
- .replace(multiSpaceRegex, ' ')
- lastChild.nodeValue = value
- }
- }
+ if (memoizedZeroBuffers[bufferSize] === undefined) {
+ memoizedZeroBuffers[bufferSize] = Array.apply(null, Array(bufferSize)).map(Number.prototype.valueOf, 0);
+ }
- // Iterate over DOM nodes
- } else if (node && node.nodeType) {
- // If the last node was a text node, make sure it is properly closed out
- if (hadText) {
- hadText = false
+ complexSignal.imag = memoizedZeroBuffers[bufferSize].slice();
- // Trim the child text nodes if the current node isn't a
- // text node or a code node
- if (TEXT_TAGS.indexOf(nodeName) === -1 &&
- VERBATIM_TAGS.indexOf(nodeName) === -1) {
- value = lastChild.nodeValue
- .replace(leadingNewlineRegex, '')
- .replace(trailingNewlineRegex, ' ')
- .replace(multiSpaceRegex, ' ')
+ return complexSignal;
+};
- // Remove empty text nodes, append otherwise
- if (value === '') {
- el.removeChild(lastChild)
- } else {
- lastChild.nodeValue = value
- }
- // Trim the child nodes but preserve the appropriate whitespace
- } else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
- value = lastChild.nodeValue
- .replace(leadingSpaceRegex, ' ')
- .replace(leadingNewlineRegex, '')
- .replace(trailingNewlineRegex, ' ')
- .replace(multiSpaceRegex, ' ')
- lastChild.nodeValue = value
- }
- }
+var bitReverseArray = function bitReverseArray(N) {
+ if (memoizedReversal[N] === undefined) {
+ var maxBinaryLength = (N - 1).toString(2).length; //get the binary length of the largest index.
+ var templateBinary = '0'.repeat(maxBinaryLength); //create a template binary of that length.
+ var reversed = {};
+ for (var n = 0; n < N; n++) {
+ var currBinary = n.toString(2); //get binary value of current index.
- // Store the last nodename
- var _nodeName = node.nodeName
- if (_nodeName) nodeName = _nodeName.toLowerCase()
+ //prepend zeros from template to current binary. This makes binary values of all indices have the same length.
+ currBinary = templateBinary.substr(currBinary.length) + currBinary;
- // Append the node to the DOM
- el.appendChild(node)
+ currBinary = [].concat(_toConsumableArray(currBinary)).reverse().join(''); //reverse
+ reversed[n] = parseInt(currBinary, 2); //convert to decimal
}
+ memoizedReversal[N] = reversed; //save
}
-}
+ return memoizedReversal[N];
+};
-},{}],91:[function(require,module,exports){
-'use strict'
+// complex multiplication
+var multiply = function multiply(a, b) {
+ return {
+ 'real': a.real * b.real - a.imag * b.imag,
+ 'imag': a.real * b.imag + a.imag * b.real
+ };
+};
-module.exports = [
- 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default',
- 'defaultchecked', 'defer', 'disabled', 'formnovalidate', 'hidden',
- 'ismap', 'loop', 'multiple', 'muted', 'novalidate', 'open', 'playsinline',
- 'readonly', 'required', 'reversed', 'selected'
-]
+// complex addition
+var add = function add(a, b) {
+ return {
+ 'real': a.real + b.real,
+ 'imag': a.imag + b.imag
+ };
+};
-},{}],92:[function(require,module,exports){
-module.exports = require('./dom')(document)
+// complex subtraction
+var subtract = function subtract(a, b) {
+ return {
+ 'real': a.real - b.real,
+ 'imag': a.imag - b.imag
+ };
+};
-},{"./dom":94}],93:[function(require,module,exports){
-'use strict'
+// euler's identity e^x = cos(x) + sin(x)
+var euler = function euler(kn, N) {
+ var x = -2 * Math.PI * kn / N;
+ return { 'real': Math.cos(x), 'imag': Math.sin(x) };
+};
-module.exports = [
- 'indeterminate'
-]
+// complex conjugate
+var conj = function conj(a) {
+ a.imag *= -1;
+ return a;
+};
-},{}],94:[function(require,module,exports){
-'use strict'
+module.exports = {
+ bitReverseArray: bitReverseArray,
+ multiply: multiply,
+ add: add,
+ subtract: subtract,
+ euler: euler,
+ conj: conj,
+ constructComplexArray: constructComplexArray
+};
-var hyperx = require('hyperx')
-var appendChild = require('./append-child')
-var SVG_TAGS = require('./svg-tags')
-var BOOL_PROPS = require('./bool-props')
-// Props that need to be set directly rather than with el.setAttribute()
-var DIRECT_PROPS = require('./direct-props')
+/***/ }),
-var SVGNS = 'http://www.w3.org/2000/svg'
-var XLINKNS = 'http://www.w3.org/1999/xlink'
+/***/ "./node_modules/inherits/inherits_browser.js":
+/*!***************************************************!*\
+ !*** ./node_modules/inherits/inherits_browser.js ***!
+ \***************************************************/
+/*! no static exports found */
+/***/ (function(module, exports) {
-var COMMENT_TAG = '!--'
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
+ }
+}
-module.exports = function (document) {
- function nanoHtmlCreateElement (tag, props, children) {
- var el
- // If an svg tag, it needs a namespace
- if (SVG_TAGS.indexOf(tag) !== -1) {
- props.namespace = SVGNS
- }
+/***/ }),
- // If we are using a namespace
- var ns = false
- if (props.namespace) {
- ns = props.namespace
- delete props.namespace
- }
+/***/ "./node_modules/process/browser.js":
+/*!*****************************************!*\
+ !*** ./node_modules/process/browser.js ***!
+ \*****************************************/
+/*! no static exports found */
+/***/ (function(module, exports) {
- // If we are extending a builtin element
- var isCustomElement = false
- if (props.is) {
- isCustomElement = props.is
- delete props.is
- }
+// shim for using process in browser
+var process = module.exports = {};
- // Create the element
- if (ns) {
- if (isCustomElement) {
- el = document.createElementNS(ns, tag, { is: isCustomElement })
- } else {
- el = document.createElementNS(ns, tag)
- }
- } else if (tag === COMMENT_TAG) {
- return document.createComment(props.comment)
- } else if (isCustomElement) {
- el = document.createElement(tag, { is: isCustomElement })
- } else {
- el = document.createElement(tag)
- }
+// cached from whatever global is present so that test runners that stub it
+// don't break things. But we need to wrap it in a try catch in case it is
+// wrapped in strict mode code which doesn't define any globals. It's inside a
+// function because try/catches deoptimize in certain engines.
- // Create the properties
- for (var p in props) {
- if (props.hasOwnProperty(p)) {
- var key = p.toLowerCase()
- var val = props[p]
- // Normalize className
- if (key === 'classname') {
- key = 'class'
- p = 'class'
- }
- // The for attribute gets transformed to htmlFor, but we just set as for
- if (p === 'htmlFor') {
- p = 'for'
- }
- // If a property is boolean, set itself to the key
- if (BOOL_PROPS.indexOf(key) !== -1) {
- if (String(val) === 'true') val = key
- else if (String(val) === 'false') continue
+var cachedSetTimeout;
+var cachedClearTimeout;
+
+function defaultSetTimout() {
+ throw new Error('setTimeout has not been defined');
+}
+function defaultClearTimeout () {
+ throw new Error('clearTimeout has not been defined');
+}
+(function () {
+ try {
+ if (typeof setTimeout === 'function') {
+ cachedSetTimeout = setTimeout;
+ } else {
+ cachedSetTimeout = defaultSetTimout;
}
- // If a property prefers being set directly vs setAttribute
- if (key.slice(0, 2) === 'on' || DIRECT_PROPS.indexOf(key) !== -1) {
- el[p] = val
+ } catch (e) {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ try {
+ if (typeof clearTimeout === 'function') {
+ cachedClearTimeout = clearTimeout;
} else {
- if (ns) {
- if (p === 'xlink:href') {
- el.setAttributeNS(XLINKNS, p, val)
- } else if (/^xmlns($|:)/i.test(p)) {
- // skip xmlns definitions
- } else {
- el.setAttributeNS(null, p, val)
- }
- } else {
- el.setAttribute(p, val)
- }
+ cachedClearTimeout = defaultClearTimeout;
+ }
+ } catch (e) {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+} ())
+function runTimeout(fun) {
+ if (cachedSetTimeout === setTimeout) {
+ //normal enviroments in sane situations
+ return setTimeout(fun, 0);
+ }
+ // if setTimeout wasn't available but was latter defined
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
+ cachedSetTimeout = setTimeout;
+ return setTimeout(fun, 0);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedSetTimeout(fun, 0);
+ } catch(e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedSetTimeout.call(null, fun, 0);
+ } catch(e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
+ return cachedSetTimeout.call(this, fun, 0);
}
- }
}
- appendChild(el, children)
- return el
- }
- function createFragment (nodes) {
- var fragment = document.createDocumentFragment()
- for (var i = 0; i < nodes.length; i++) {
- if (nodes[i] == null) continue
- if (Array.isArray(nodes[i])) {
- fragment.appendChild(createFragment(nodes[i]))
- } else {
- if (typeof nodes[i] === 'string') nodes[i] = document.createTextNode(nodes[i])
- fragment.appendChild(nodes[i])
- }
+}
+function runClearTimeout(marker) {
+ if (cachedClearTimeout === clearTimeout) {
+ //normal enviroments in sane situations
+ return clearTimeout(marker);
+ }
+ // if clearTimeout wasn't available but was latter defined
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
+ cachedClearTimeout = clearTimeout;
+ return clearTimeout(marker);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedClearTimeout(marker);
+ } catch (e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedClearTimeout.call(null, marker);
+ } catch (e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
+ return cachedClearTimeout.call(this, marker);
+ }
}
- return fragment
- }
- var exports = hyperx(nanoHtmlCreateElement, {
- comments: true,
- createFragment: createFragment
- })
- exports.default = exports
- exports.createComment = nanoHtmlCreateElement
- return exports
-}
-},{"./append-child":90,"./bool-props":91,"./direct-props":93,"./svg-tags":96,"hyperx":80}],95:[function(require,module,exports){
-'use strict'
-function nanohtmlRawBrowser (tag) {
- var el = document.createElement('div')
- el.innerHTML = tag
- return toArray(el.childNodes)
}
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
-function toArray (arr) {
- return Array.isArray(arr) ? arr : [].slice.call(arr)
+function cleanUpNextTick() {
+ if (!draining || !currentQueue) {
+ return;
+ }
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
+ }
+ if (queue.length) {
+ drainQueue();
+ }
}
-module.exports = nanohtmlRawBrowser
-
-},{}],96:[function(require,module,exports){
-'use strict'
-
-module.exports = [
- 'svg', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor',
- 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile',
- 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix',
- 'feComponentTransfer', 'feComposite', 'feConvolveMatrix',
- 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood',
- 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage',
- 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight',
- 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter',
- 'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src',
- 'font-face-uri', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image',
- 'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph',
- 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect',
- 'set', 'stop', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref',
- 'tspan', 'use', 'view', 'vkern'
-]
-
-},{}],97:[function(require,module,exports){
-var assert = require('assert')
+function drainQueue() {
+ if (draining) {
+ return;
+ }
+ var timeout = runTimeout(cleanUpNextTick);
+ draining = true;
-var emojis = {
- trace: '🔍',
- debug: '🐛',
- info: '✨',
- warn: '⚠️',
- error: '🚨',
- fatal: '💀'
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+ queueIndex = -1;
+ len = queue.length;
+ }
+ currentQueue = null;
+ draining = false;
+ runClearTimeout(timeout);
}
-var levels = {
- trace: 10,
- debug: 20,
- info: 30,
- warn: 40,
- error: 50,
- fatal: 60
-}
+process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ runTimeout(drainQueue);
+ }
+};
-var defaultColors = {
- foreground: '#d3c0c8',
- background: '#2d2d2d',
- black: '#2d2d2d',
- red: '#f2777a',
- green: '#99cc99',
- yellow: '#ffcc66',
- blue: '#6699cc',
- magenta: '#cc99cc',
- cyan: '#66cccc',
- white: '#d3d0c8',
- brightBlack: '#747369'
+// v8 likes predictible objects
+function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
}
+Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
+};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
-module.exports = Nanologger
+function noop() {}
-function Nanologger (name, opts) {
- opts = opts || {}
- if (!(this instanceof Nanologger)) return new Nanologger(name, opts)
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+process.prependListener = noop;
+process.prependOnceListener = noop;
- assert.equal(typeof opts, 'object', 'nanologger: opts should be type object')
+process.listeners = function (name) { return [] }
- this._name = name || ''
- this._colors = Object.assign({}, defaultColors, opts.colors || {})
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+};
- try {
- this.logLevel = window.localStorage.getItem('logLevel') || 'info'
- } catch (e) {
- this.logLevel = 'info'
- }
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
- this._logLevel = levels[this.logLevel]
-}
-Nanologger.prototype.trace = function () {
- var args = [ 'trace' ]
- for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
- this._print.apply(this, args)
-}
+/***/ }),
-Nanologger.prototype.debug = function () {
- var args = [ 'debug' ]
- for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
- this._print.apply(this, args)
-}
+/***/ "./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js":
+/*!**********************************************************************************!*\
+ !*** ./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js ***!
+ \**********************************************************************************/
+/*! no static exports found */
+/***/ (function(module, exports) {
-Nanologger.prototype.info = function () {
- var args = [ 'info' ]
- for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
- this._print.apply(this, args)
+module.exports = function isBuffer(arg) {
+ return arg && typeof arg === 'object'
+ && typeof arg.copy === 'function'
+ && typeof arg.fill === 'function'
+ && typeof arg.readUInt8 === 'function';
}
-Nanologger.prototype.warn = function () {
- var args = [ 'warn' ]
- for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
- this._print.apply(this, args)
-}
+/***/ }),
-Nanologger.prototype.error = function () {
- var args = [ 'error' ]
- for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
- this._print.apply(this, args)
-}
+/***/ "./node_modules/webpack-stream/node_modules/util/util.js":
+/*!***************************************************************!*\
+ !*** ./node_modules/webpack-stream/node_modules/util/util.js ***!
+ \***************************************************************/
+/*! no static exports found */
+/***/ (function(module, exports, __webpack_require__) {
-Nanologger.prototype.fatal = function () {
- var args = [ 'fatal' ]
- for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
- this._print.apply(this, args)
-}
+/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
-Nanologger.prototype._print = function (level) {
- if (levels[level] < this._logLevel) return
+var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
+ function getOwnPropertyDescriptors(obj) {
+ var keys = Object.keys(obj);
+ var descriptors = {};
+ for (var i = 0; i < keys.length; i++) {
+ descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
+ }
+ return descriptors;
+ };
- var time = getTimeStamp()
- var emoji = emojis[level]
- var name = this._name || 'unknown'
+var formatRegExp = /%[sdj%]/g;
+exports.format = function(f) {
+ if (!isString(f)) {
+ var objects = [];
+ for (var i = 0; i < arguments.length; i++) {
+ objects.push(inspect(arguments[i]));
+ }
+ return objects.join(' ');
+ }
- var msgColor = (level === 'error' || level.fatal)
- ? this._colors.red
- : level === 'warn'
- ? this._colors.yellow
- : this._colors.green
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ var str = String(f).replace(formatRegExp, function(x) {
+ if (x === '%%') return '%';
+ if (i >= len) return x;
+ switch (x) {
+ case '%s': return String(args[i++]);
+ case '%d': return Number(args[i++]);
+ case '%j':
+ try {
+ return JSON.stringify(args[i++]);
+ } catch (_) {
+ return '[Circular]';
+ }
+ default:
+ return x;
+ }
+ });
+ for (var x = args[i]; i < len; x = args[++i]) {
+ if (isNull(x) || !isObject(x)) {
+ str += ' ' + x;
+ } else {
+ str += ' ' + inspect(x);
+ }
+ }
+ return str;
+};
- var objs = []
- var args = [ null ]
- var msg = '%c%s ' + emoji + ' %c%s'
- args.push(color(this._colors.brightBlack), time)
- args.push(color(this._colors.magenta), name)
+// Mark that a method should not be used.
+// Returns a modified function which warns once by default.
+// If --no-deprecation is set, then it is a no-op.
+exports.deprecate = function(fn, msg) {
+ if (typeof process !== 'undefined' && process.noDeprecation === true) {
+ return fn;
+ }
- for (var i = 1, len = arguments.length; i < len; i++) {
- var arg = arguments[i]
- if (typeof arg === 'string') {
- if (i === 1) {
- // first string argument is in color
- msg += ' %c%s'
- args.push(color(msgColor))
- args.push(arg)
- } else if (/ms$/.test(arg)) {
- // arguments finishing with 'ms', grey out
- msg += ' %c%s'
- args.push(color(this._colors.brightBlack))
- args.push(arg)
+ // Allow for deprecating things in the process of starting up.
+ if (typeof process === 'undefined') {
+ return function() {
+ return exports.deprecate(fn, msg).apply(this, arguments);
+ };
+ }
+
+ var warned = false;
+ function deprecated() {
+ if (!warned) {
+ if (process.throwDeprecation) {
+ throw new Error(msg);
+ } else if (process.traceDeprecation) {
+ console.trace(msg);
} else {
- // normal colors
- msg += ' %c%s'
- args.push(color(this._colors.white))
- args.push(arg)
+ console.error(msg);
}
- } else if (typeof arg === 'number') {
- msg += ' %c%d'
- args.push(color(this._colors.magenta))
- args.push(arg)
- } else {
- objs.push(arg)
+ warned = true;
}
+ return fn.apply(this, arguments);
}
- args[0] = msg
- objs.forEach(function (obj) {
- args.push(obj)
- })
-
- // In IE/Edge console functions don't inherit from Function.prototype
- // so this is necessary to get all the args applied.
- Function.prototype.apply.apply(console.log, [console, args])
-}
-
-function color (color) {
- return 'color: ' + color + ';'
-}
+ return deprecated;
+};
-function getTimeStamp () {
- var date = new Date()
- var hours = pad(date.getHours().toString())
- var minutes = pad(date.getMinutes().toString())
- var seconds = pad(date.getSeconds().toString())
- return hours + ':' + minutes + ':' + seconds
-}
-function pad (str) {
- return str.length !== 2 ? 0 + str : str
-}
+var debugs = {};
+var debugEnviron;
+exports.debuglog = function(set) {
+ if (isUndefined(debugEnviron))
+ debugEnviron = process.env.NODE_DEBUG || '';
+ set = set.toUpperCase();
+ if (!debugs[set]) {
+ if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
+ var pid = process.pid;
+ debugs[set] = function() {
+ var msg = exports.format.apply(exports, arguments);
+ console.error('%s %d: %s', set, pid, msg);
+ };
+ } else {
+ debugs[set] = function() {};
+ }
+ }
+ return debugs[set];
+};
-},{"assert":125}],98:[function(require,module,exports){
-module.exports = LRU
-function LRU (opts) {
- if (!(this instanceof LRU)) return new LRU(opts)
- if (typeof opts === 'number') opts = {max: opts}
- if (!opts) opts = {}
- this.cache = {}
- this.head = this.tail = null
- this.length = 0
- this.max = opts.max || 1000
- this.maxAge = opts.maxAge || 0
+/**
+ * Echos the value of a value. Trys to print the value out
+ * in the best way possible given the different types.
+ *
+ * @param {Object} obj The object to print out.
+ * @param {Object} opts Optional options object that alters the output.
+ */
+/* legacy: obj, showHidden, depth, colors*/
+function inspect(obj, opts) {
+ // default options
+ var ctx = {
+ seen: [],
+ stylize: stylizeNoColor
+ };
+ // legacy...
+ if (arguments.length >= 3) ctx.depth = arguments[2];
+ if (arguments.length >= 4) ctx.colors = arguments[3];
+ if (isBoolean(opts)) {
+ // legacy...
+ ctx.showHidden = opts;
+ } else if (opts) {
+ // got an "options" object
+ exports._extend(ctx, opts);
+ }
+ // set default options
+ if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
+ if (isUndefined(ctx.depth)) ctx.depth = 2;
+ if (isUndefined(ctx.colors)) ctx.colors = false;
+ if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
+ if (ctx.colors) ctx.stylize = stylizeWithColor;
+ return formatValue(ctx, obj, ctx.depth);
}
+exports.inspect = inspect;
-Object.defineProperty(LRU.prototype, 'keys', {
- get: function () { return Object.keys(this.cache) }
-})
-LRU.prototype.clear = function () {
- this.cache = {}
- this.head = this.tail = null
- this.length = 0
-}
+// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
+inspect.colors = {
+ 'bold' : [1, 22],
+ 'italic' : [3, 23],
+ 'underline' : [4, 24],
+ 'inverse' : [7, 27],
+ 'white' : [37, 39],
+ 'grey' : [90, 39],
+ 'black' : [30, 39],
+ 'blue' : [34, 39],
+ 'cyan' : [36, 39],
+ 'green' : [32, 39],
+ 'magenta' : [35, 39],
+ 'red' : [31, 39],
+ 'yellow' : [33, 39]
+};
-LRU.prototype.remove = function (key) {
- if (typeof key !== 'string') key = '' + key
- if (!this.cache.hasOwnProperty(key)) return
+// Don't use 'blue' not visible on cmd.exe
+inspect.styles = {
+ 'special': 'cyan',
+ 'number': 'yellow',
+ 'boolean': 'yellow',
+ 'undefined': 'grey',
+ 'null': 'bold',
+ 'string': 'green',
+ 'date': 'magenta',
+ // "name": intentionally not styling
+ 'regexp': 'red'
+};
- var element = this.cache[key]
- delete this.cache[key]
- this._unlink(key, element.prev, element.next)
- return element.value
-}
-LRU.prototype._unlink = function (key, prev, next) {
- this.length--
+function stylizeWithColor(str, styleType) {
+ var style = inspect.styles[styleType];
- if (this.length === 0) {
- this.head = this.tail = null
+ if (style) {
+ return '\u001b[' + inspect.colors[style][0] + 'm' + str +
+ '\u001b[' + inspect.colors[style][1] + 'm';
} else {
- if (this.head === key) {
- this.head = prev
- this.cache[this.head].next = null
- } else if (this.tail === key) {
- this.tail = next
- this.cache[this.tail].prev = null
- } else {
- this.cache[prev].next = next
- this.cache[next].prev = prev
- }
+ return str;
}
}
-LRU.prototype.peek = function (key) {
- if (!this.cache.hasOwnProperty(key)) return
-
- var element = this.cache[key]
- if (!this._checkAge(key, element)) return
- return element.value
+function stylizeNoColor(str, styleType) {
+ return str;
}
-LRU.prototype.set = function (key, value) {
- if (typeof key !== 'string') key = '' + key
-
- var element
-
- if (this.cache.hasOwnProperty(key)) {
- element = this.cache[key]
- element.value = value
- if (this.maxAge) element.modified = Date.now()
- // If it's already the head, there's nothing more to do:
- if (key === this.head) return value
- this._unlink(key, element.prev, element.next)
- } else {
- element = {value: value, modified: 0, next: null, prev: null}
- if (this.maxAge) element.modified = Date.now()
- this.cache[key] = element
+function arrayToHash(array) {
+ var hash = {};
- // Eviction is only possible if the key didn't already exist:
- if (this.length === this.max) this.evict()
- }
+ array.forEach(function(val, idx) {
+ hash[val] = true;
+ });
- this.length++
- element.next = null
- element.prev = this.head
+ return hash;
+}
- if (this.head) this.cache[this.head].next = key
- this.head = key
- if (!this.tail) this.tail = key
- return value
-}
+function formatValue(ctx, value, recurseTimes) {
+ // Provide a hook for user-specified inspect functions.
+ // Check that value is an object with an inspect function on it
+ if (ctx.customInspect &&
+ value &&
+ isFunction(value.inspect) &&
+ // Filter out the util module, it's inspect function is special
+ value.inspect !== exports.inspect &&
+ // Also filter out any prototype objects using the circular check.
+ !(value.constructor && value.constructor.prototype === value)) {
+ var ret = value.inspect(recurseTimes, ctx);
+ if (!isString(ret)) {
+ ret = formatValue(ctx, ret, recurseTimes);
+ }
+ return ret;
+ }
-LRU.prototype._checkAge = function (key, element) {
- if (this.maxAge && (Date.now() - element.modified) > this.maxAge) {
- this.remove(key)
- return false
+ // Primitive types cannot have properties
+ var primitive = formatPrimitive(ctx, value);
+ if (primitive) {
+ return primitive;
}
- return true
-}
-LRU.prototype.get = function (key) {
- if (typeof key !== 'string') key = '' + key
- if (!this.cache.hasOwnProperty(key)) return
+ // Look up the keys of the object.
+ var keys = Object.keys(value);
+ var visibleKeys = arrayToHash(keys);
- var element = this.cache[key]
+ if (ctx.showHidden) {
+ keys = Object.getOwnPropertyNames(value);
+ }
- if (!this._checkAge(key, element)) return
+ // IE doesn't make error fields non-enumerable
+ // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
+ if (isError(value)
+ && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
+ return formatError(value);
+ }
- if (this.head !== key) {
- if (key === this.tail) {
- this.tail = element.next
- this.cache[this.tail].prev = null
- } else {
- // Set prev.next -> element.next:
- this.cache[element.prev].next = element.next
+ // Some type of object without properties can be shortcutted.
+ if (keys.length === 0) {
+ if (isFunction(value)) {
+ var name = value.name ? ': ' + value.name : '';
+ return ctx.stylize('[Function' + name + ']', 'special');
+ }
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ }
+ if (isDate(value)) {
+ return ctx.stylize(Date.prototype.toString.call(value), 'date');
+ }
+ if (isError(value)) {
+ return formatError(value);
}
+ }
- // Set element.next.prev -> element.prev:
- this.cache[element.next].prev = element.prev
+ var base = '', array = false, braces = ['{', '}'];
- // Element is the new head
- this.cache[this.head].next = key
- element.prev = this.head
- element.next = null
- this.head = key
+ // Make Array say that they are Array
+ if (isArray(value)) {
+ array = true;
+ braces = ['[', ']'];
}
- return element.value
-}
-
-LRU.prototype.evict = function () {
- if (!this.tail) return
- this.remove(this.tail)
-}
+ // Make functions say that they are functions
+ if (isFunction(value)) {
+ var n = value.name ? ': ' + value.name : '';
+ base = ' [Function' + n + ']';
+ }
-},{}],99:[function(require,module,exports){
-var assert = require('nanoassert')
-var morph = require('./lib/morph')
+ // Make RegExps say that they are RegExps
+ if (isRegExp(value)) {
+ base = ' ' + RegExp.prototype.toString.call(value);
+ }
-var TEXT_NODE = 3
-// var DEBUG = false
+ // Make dates with properties first say the date
+ if (isDate(value)) {
+ base = ' ' + Date.prototype.toUTCString.call(value);
+ }
-module.exports = nanomorph
+ // Make error with message first say the error
+ if (isError(value)) {
+ base = ' ' + formatError(value);
+ }
-// Morph one tree into another tree
-//
-// no parent
-// -> same: diff and walk children
-// -> not same: replace and return
-// old node doesn't exist
-// -> insert new node
-// new node doesn't exist
-// -> delete old node
-// nodes are not the same
-// -> diff nodes and apply patch to old node
-// nodes are the same
-// -> walk all child nodes and append to old node
-function nanomorph (oldTree, newTree, options) {
- // if (DEBUG) {
- // console.log(
- // 'nanomorph\nold\n %s\nnew\n %s',
- // oldTree && oldTree.outerHTML,
- // newTree && newTree.outerHTML
- // )
- // }
- assert.equal(typeof oldTree, 'object', 'nanomorph: oldTree should be an object')
- assert.equal(typeof newTree, 'object', 'nanomorph: newTree should be an object')
+ if (keys.length === 0 && (!array || value.length == 0)) {
+ return braces[0] + base + braces[1];
+ }
- if (options && options.childrenOnly) {
- updateChildren(newTree, oldTree)
- return oldTree
+ if (recurseTimes < 0) {
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ } else {
+ return ctx.stylize('[Object]', 'special');
+ }
}
- assert.notEqual(
- newTree.nodeType,
- 11,
- 'nanomorph: newTree should have one root node (which is not a DocumentFragment)'
- )
-
- return walk(newTree, oldTree)
-}
+ ctx.seen.push(value);
-// Walk and morph a dom tree
-function walk (newNode, oldNode) {
- // if (DEBUG) {
- // console.log(
- // 'walk\nold\n %s\nnew\n %s',
- // oldNode && oldNode.outerHTML,
- // newNode && newNode.outerHTML
- // )
- // }
- if (!oldNode) {
- return newNode
- } else if (!newNode) {
- return null
- } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) {
- return oldNode
- } else if (newNode.tagName !== oldNode.tagName || getComponentId(newNode) !== getComponentId(oldNode)) {
- return newNode
+ var output;
+ if (array) {
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
- morph(newNode, oldNode)
- updateChildren(newNode, oldNode)
- return oldNode
+ output = keys.map(function(key) {
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
+ });
}
-}
-function getComponentId (node) {
- return node.dataset ? node.dataset.nanomorphComponentId : undefined
-}
+ ctx.seen.pop();
-// Update the children of elements
-// (obj, obj) -> null
-function updateChildren (newNode, oldNode) {
- // if (DEBUG) {
- // console.log(
- // 'updateChildren\nold\n %s\nnew\n %s',
- // oldNode && oldNode.outerHTML,
- // newNode && newNode.outerHTML
- // )
- // }
- var oldChild, newChild, morphed, oldMatch
+ return reduceToSingleString(output, base, braces);
+}
- // The offset is only ever increased, and used for [i - offset] in the loop
- var offset = 0
- for (var i = 0; ; i++) {
- oldChild = oldNode.childNodes[i]
- newChild = newNode.childNodes[i - offset]
- // if (DEBUG) {
- // console.log(
- // '===\n- old\n %s\n- new\n %s',
- // oldChild && oldChild.outerHTML,
- // newChild && newChild.outerHTML
- // )
- // }
- // Both nodes are empty, do nothing
- if (!oldChild && !newChild) {
- break
+function formatPrimitive(ctx, value) {
+ if (isUndefined(value))
+ return ctx.stylize('undefined', 'undefined');
+ if (isString(value)) {
+ var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
+ .replace(/'/g, "\\'")
+ .replace(/\\"/g, '"') + '\'';
+ return ctx.stylize(simple, 'string');
+ }
+ if (isNumber(value))
+ return ctx.stylize('' + value, 'number');
+ if (isBoolean(value))
+ return ctx.stylize('' + value, 'boolean');
+ // For some reason typeof null is "object", so special case here.
+ if (isNull(value))
+ return ctx.stylize('null', 'null');
+}
- // There is no new child, remove old
- } else if (!newChild) {
- oldNode.removeChild(oldChild)
- i--
- // There is no old child, add new
- } else if (!oldChild) {
- oldNode.appendChild(newChild)
- offset++
+function formatError(value) {
+ return '[' + Error.prototype.toString.call(value) + ']';
+}
- // Both nodes are the same, morph
- } else if (same(newChild, oldChild)) {
- morphed = walk(newChild, oldChild)
- if (morphed !== oldChild) {
- oldNode.replaceChild(morphed, oldChild)
- offset++
- }
- // Both nodes do not share an ID or a placeholder, try reorder
+function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
+ var output = [];
+ for (var i = 0, l = value.length; i < l; ++i) {
+ if (hasOwnProperty(value, String(i))) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ String(i), true));
} else {
- oldMatch = null
-
- // Try and find a similar node somewhere in the tree
- for (var j = i; j < oldNode.childNodes.length; j++) {
- if (same(oldNode.childNodes[j], newChild)) {
- oldMatch = oldNode.childNodes[j]
- break
- }
- }
-
- // If there was a node with the same ID or placeholder in the old list
- if (oldMatch) {
- morphed = walk(newChild, oldMatch)
- if (morphed !== oldMatch) offset++
- oldNode.insertBefore(morphed, oldChild)
+ output.push('');
+ }
+ }
+ keys.forEach(function(key) {
+ if (!key.match(/^\d+$/)) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ key, true));
+ }
+ });
+ return output;
+}
- // It's safe to morph two nodes in-place if neither has an ID
- } else if (!newChild.id && !oldChild.id) {
- morphed = walk(newChild, oldChild)
- if (morphed !== oldChild) {
- oldNode.replaceChild(morphed, oldChild)
- offset++
- }
- // Insert the node at the index if we couldn't morph or find a matching node
+function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
+ var name, str, desc;
+ desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
+ if (desc.get) {
+ if (desc.set) {
+ str = ctx.stylize('[Getter/Setter]', 'special');
+ } else {
+ str = ctx.stylize('[Getter]', 'special');
+ }
+ } else {
+ if (desc.set) {
+ str = ctx.stylize('[Setter]', 'special');
+ }
+ }
+ if (!hasOwnProperty(visibleKeys, key)) {
+ name = '[' + key + ']';
+ }
+ if (!str) {
+ if (ctx.seen.indexOf(desc.value) < 0) {
+ if (isNull(recurseTimes)) {
+ str = formatValue(ctx, desc.value, null);
} else {
- oldNode.insertBefore(newChild, oldChild)
- offset++
+ str = formatValue(ctx, desc.value, recurseTimes - 1);
+ }
+ if (str.indexOf('\n') > -1) {
+ if (array) {
+ str = str.split('\n').map(function(line) {
+ return ' ' + line;
+ }).join('\n').substr(2);
+ } else {
+ str = '\n' + str.split('\n').map(function(line) {
+ return ' ' + line;
+ }).join('\n');
+ }
}
+ } else {
+ str = ctx.stylize('[Circular]', 'special');
+ }
+ }
+ if (isUndefined(name)) {
+ if (array && key.match(/^\d+$/)) {
+ return str;
+ }
+ name = JSON.stringify('' + key);
+ if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
+ name = name.substr(1, name.length - 2);
+ name = ctx.stylize(name, 'name');
+ } else {
+ name = name.replace(/'/g, "\\'")
+ .replace(/\\"/g, '"')
+ .replace(/(^"|"$)/g, "'");
+ name = ctx.stylize(name, 'string');
}
}
-}
-function same (a, b) {
- if (a.id) return a.id === b.id
- if (a.isSameNode) return a.isSameNode(b)
- if (a.tagName !== b.tagName) return false
- if (a.type === TEXT_NODE) return a.nodeValue === b.nodeValue
- return false
+ return name + ': ' + str;
}
-},{"./lib/morph":101,"nanoassert":85}],100:[function(require,module,exports){
-module.exports = [
- // attribute events (can be set with attributes)
- 'onclick',
- 'ondblclick',
- 'onmousedown',
- 'onmouseup',
- 'onmouseover',
- 'onmousemove',
- 'onmouseout',
- 'onmouseenter',
- 'onmouseleave',
- 'ontouchcancel',
- 'ontouchend',
- 'ontouchmove',
- 'ontouchstart',
- 'ondragstart',
- 'ondrag',
- 'ondragenter',
- 'ondragleave',
- 'ondragover',
- 'ondrop',
- 'ondragend',
- 'onkeydown',
- 'onkeypress',
- 'onkeyup',
- 'onunload',
- 'onabort',
- 'onerror',
- 'onresize',
- 'onscroll',
- 'onselect',
- 'onchange',
- 'onsubmit',
- 'onreset',
- 'onfocus',
- 'onblur',
- 'oninput',
- 'onanimationend',
- 'onanimationiteration',
- 'onanimationstart',
- // other common events
- 'oncontextmenu',
- 'onfocusin',
- 'onfocusout'
-]
-},{}],101:[function(require,module,exports){
-var events = require('./events')
-var eventsLength = events.length
+function reduceToSingleString(output, base, braces) {
+ var numLinesEst = 0;
+ var length = output.reduce(function(prev, cur) {
+ numLinesEst++;
+ if (cur.indexOf('\n') >= 0) numLinesEst++;
+ return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
+ }, 0);
-var ELEMENT_NODE = 1
-var TEXT_NODE = 3
-var COMMENT_NODE = 8
+ if (length > 60) {
+ return braces[0] +
+ (base === '' ? '' : base + '\n ') +
+ ' ' +
+ output.join(',\n ') +
+ ' ' +
+ braces[1];
+ }
-module.exports = morph
+ return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
+}
-// diff elements and apply the resulting patch to the old node
-// (obj, obj) -> null
-function morph (newNode, oldNode) {
- var nodeType = newNode.nodeType
- var nodeName = newNode.nodeName
- if (nodeType === ELEMENT_NODE) {
- copyAttrs(newNode, oldNode)
- }
+// NOTE: These type checking functions intentionally don't use `instanceof`
+// because it is fragile and can be easily faked with `Object.create()`.
+function isArray(ar) {
+ return Array.isArray(ar);
+}
+exports.isArray = isArray;
- if (nodeType === TEXT_NODE || nodeType === COMMENT_NODE) {
- if (oldNode.nodeValue !== newNode.nodeValue) {
- oldNode.nodeValue = newNode.nodeValue
- }
- }
+function isBoolean(arg) {
+ return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
- // Some DOM nodes are weird
- // https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js
- if (nodeName === 'INPUT') updateInput(newNode, oldNode)
- else if (nodeName === 'OPTION') updateOption(newNode, oldNode)
- else if (nodeName === 'TEXTAREA') updateTextarea(newNode, oldNode)
+function isNull(arg) {
+ return arg === null;
+}
+exports.isNull = isNull;
- copyEvents(newNode, oldNode)
+function isNullOrUndefined(arg) {
+ return arg == null;
}
+exports.isNullOrUndefined = isNullOrUndefined;
-function copyAttrs (newNode, oldNode) {
- var oldAttrs = oldNode.attributes
- var newAttrs = newNode.attributes
- var attrNamespaceURI = null
- var attrValue = null
- var fromValue = null
- var attrName = null
- var attr = null
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
+exports.isNumber = isNumber;
- for (var i = newAttrs.length - 1; i >= 0; --i) {
- attr = newAttrs[i]
- attrName = attr.name
- attrNamespaceURI = attr.namespaceURI
- attrValue = attr.value
- if (attrNamespaceURI) {
- attrName = attr.localName || attrName
- fromValue = oldNode.getAttributeNS(attrNamespaceURI, attrName)
- if (fromValue !== attrValue) {
- oldNode.setAttributeNS(attrNamespaceURI, attrName, attrValue)
- }
- } else {
- if (!oldNode.hasAttribute(attrName)) {
- oldNode.setAttribute(attrName, attrValue)
- } else {
- fromValue = oldNode.getAttribute(attrName)
- if (fromValue !== attrValue) {
- // apparently values are always cast to strings, ah well
- if (attrValue === 'null' || attrValue === 'undefined') {
- oldNode.removeAttribute(attrName)
- } else {
- oldNode.setAttribute(attrName, attrValue)
- }
- }
- }
- }
- }
+function isString(arg) {
+ return typeof arg === 'string';
+}
+exports.isString = isString;
- // Remove any extra attributes found on the original DOM element that
- // weren't found on the target element.
- for (var j = oldAttrs.length - 1; j >= 0; --j) {
- attr = oldAttrs[j]
- if (attr.specified !== false) {
- attrName = attr.name
- attrNamespaceURI = attr.namespaceURI
+function isSymbol(arg) {
+ return typeof arg === 'symbol';
+}
+exports.isSymbol = isSymbol;
- if (attrNamespaceURI) {
- attrName = attr.localName || attrName
- if (!newNode.hasAttributeNS(attrNamespaceURI, attrName)) {
- oldNode.removeAttributeNS(attrNamespaceURI, attrName)
- }
- } else {
- if (!newNode.hasAttributeNS(null, attrName)) {
- oldNode.removeAttribute(attrName)
- }
- }
- }
- }
+function isUndefined(arg) {
+ return arg === void 0;
}
+exports.isUndefined = isUndefined;
-function copyEvents (newNode, oldNode) {
- for (var i = 0; i < eventsLength; i++) {
- var ev = events[i]
- if (newNode[ev]) { // if new element has a whitelisted attribute
- oldNode[ev] = newNode[ev] // update existing element
- } else if (oldNode[ev]) { // if existing element has it and new one doesnt
- oldNode[ev] = undefined // remove it from existing element
- }
- }
+function isRegExp(re) {
+ return isObject(re) && objectToString(re) === '[object RegExp]';
}
+exports.isRegExp = isRegExp;
-function updateOption (newNode, oldNode) {
- updateAttribute(newNode, oldNode, 'selected')
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
}
+exports.isObject = isObject;
-// The "value" attribute is special for the element since it sets the
-// initial value. Changing the "value" attribute without changing the "value"
-// property will have no effect since it is only used to the set the initial
-// value. Similar for the "checked" attribute, and "disabled".
-function updateInput (newNode, oldNode) {
- var newValue = newNode.value
- var oldValue = oldNode.value
+function isDate(d) {
+ return isObject(d) && objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
- updateAttribute(newNode, oldNode, 'checked')
- updateAttribute(newNode, oldNode, 'disabled')
+function isError(e) {
+ return isObject(e) &&
+ (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
- // The "indeterminate" property can not be set using an HTML attribute.
- // See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
- if (newNode.indeterminate !== oldNode.indeterminate) {
- oldNode.indeterminate = newNode.indeterminate
- }
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
- // Persist file value since file inputs can't be changed programatically
- if (oldNode.type === 'file') return
+function isPrimitive(arg) {
+ return arg === null ||
+ typeof arg === 'boolean' ||
+ typeof arg === 'number' ||
+ typeof arg === 'string' ||
+ typeof arg === 'symbol' || // ES6 symbol
+ typeof arg === 'undefined';
+}
+exports.isPrimitive = isPrimitive;
- if (newValue !== oldValue) {
- oldNode.setAttribute('value', newValue)
- oldNode.value = newValue
- }
+exports.isBuffer = __webpack_require__(/*! ./support/isBuffer */ "./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js");
- if (newValue === 'null') {
- oldNode.value = ''
- oldNode.removeAttribute('value')
- }
+function objectToString(o) {
+ return Object.prototype.toString.call(o);
+}
- if (!newNode.hasAttributeNS(null, 'value')) {
- oldNode.removeAttribute('value')
- } else if (oldNode.type === 'range') {
- // this is so elements like slider move their UI thingy
- oldNode.value = newValue
- }
+
+function pad(n) {
+ return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
-function updateTextarea (newNode, oldNode) {
- var newValue = newNode.value
- if (newValue !== oldNode.value) {
- oldNode.value = newValue
- }
- if (oldNode.firstChild && oldNode.firstChild.nodeValue !== newValue) {
- // Needed for IE. Apparently IE sets the placeholder as the
- // node value and vise versa. This ignores an empty update.
- if (newValue === '' && oldNode.firstChild.nodeValue === oldNode.placeholder) {
- return
- }
+var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
+ 'Oct', 'Nov', 'Dec'];
- oldNode.firstChild.nodeValue = newValue
- }
+// 26 Feb 16:19:34
+function timestamp() {
+ var d = new Date();
+ var time = [pad(d.getHours()),
+ pad(d.getMinutes()),
+ pad(d.getSeconds())].join(':');
+ return [d.getDate(), months[d.getMonth()], time].join(' ');
}
-function updateAttribute (newNode, oldNode, name) {
- if (newNode[name] !== oldNode[name]) {
- oldNode[name] = newNode[name]
- if (newNode[name]) {
- oldNode.setAttribute(name, '')
- } else {
- oldNode.removeAttribute(name)
- }
+
+// log is just a thin wrapper to console.log that prepends a timestamp
+exports.log = function() {
+ console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
+};
+
+
+/**
+ * Inherit the prototype methods from one constructor into another.
+ *
+ * The Function.prototype.inherits from lang.js rewritten as a standalone
+ * function (not on Function.prototype). NOTE: If this file is to be loaded
+ * during bootstrapping this function needs to be rewritten using some native
+ * functions as prototype setup using normal JavaScript does not work as
+ * expected during bootstrapping (see mirror.js in r114903).
+ *
+ * @param {function} ctor Constructor function which needs to inherit the
+ * prototype.
+ * @param {function} superCtor Constructor function to inherit prototype from.
+ */
+exports.inherits = __webpack_require__(/*! inherits */ "./node_modules/inherits/inherits_browser.js");
+
+exports._extend = function(origin, add) {
+ // Don't do anything if add isn't an object
+ if (!add || !isObject(add)) return origin;
+
+ var keys = Object.keys(add);
+ var i = keys.length;
+ while (i--) {
+ origin[keys[i]] = add[keys[i]];
}
-}
+ return origin;
+};
-},{"./events":100}],102:[function(require,module,exports){
-var reg = /([^?=&]+)(=([^&]*))?/g
-var assert = require('assert')
+function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+}
-module.exports = qs
+var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
-function qs (url) {
- assert.equal(typeof url, 'string', 'nanoquery: url should be type string')
+exports.promisify = function promisify(original) {
+ if (typeof original !== 'function')
+ throw new TypeError('The "original" argument must be of type Function');
- var obj = {}
- url.replace(/^.*\?/, '').replace(reg, function (a0, a1, a2, a3) {
- var value = decodeURIComponent(a3)
- var key = decodeURIComponent(a1)
- if (obj.hasOwnProperty(key)) {
- if (Array.isArray(obj[key])) obj[key].push(value)
- else obj[key] = [obj[key], value]
- } else {
- obj[key] = value
+ if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
+ var fn = original[kCustomPromisifiedSymbol];
+ if (typeof fn !== 'function') {
+ throw new TypeError('The "util.promisify.custom" argument must be of type Function');
}
- })
+ Object.defineProperty(fn, kCustomPromisifiedSymbol, {
+ value: fn, enumerable: false, writable: false, configurable: true
+ });
+ return fn;
+ }
- return obj
-}
+ function fn() {
+ var promiseResolve, promiseReject;
+ var promise = new Promise(function (resolve, reject) {
+ promiseResolve = resolve;
+ promiseReject = reject;
+ });
-},{"assert":85}],103:[function(require,module,exports){
-'use strict'
+ var args = [];
+ for (var i = 0; i < arguments.length; i++) {
+ args.push(arguments[i]);
+ }
+ args.push(function (err, value) {
+ if (err) {
+ promiseReject(err);
+ } else {
+ promiseResolve(value);
+ }
+ });
-var assert = require('assert')
+ try {
+ original.apply(this, args);
+ } catch (err) {
+ promiseReject(err);
+ }
-module.exports = nanoraf
+ return promise;
+ }
-// Only call RAF when needed
-// (fn, fn?) -> fn
-function nanoraf (render, raf) {
- assert.equal(typeof render, 'function', 'nanoraf: render should be a function')
- assert.ok(typeof raf === 'function' || typeof raf === 'undefined', 'nanoraf: raf should be a function or undefined')
+ Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
- if (!raf) raf = window.requestAnimationFrame
- var redrawScheduled = false
- var args = null
+ if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
+ value: fn, enumerable: false, writable: false, configurable: true
+ });
+ return Object.defineProperties(
+ fn,
+ getOwnPropertyDescriptors(original)
+ );
+}
- return function frame () {
- if (args === null && !redrawScheduled) {
- redrawScheduled = true
+exports.promisify.custom = kCustomPromisifiedSymbol
- raf(function redraw () {
- redrawScheduled = false
+function callbackifyOnRejected(reason, cb) {
+ // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
+ // Because `null` is a special error value in callbacks which means "no error
+ // occurred", we error-wrap so the callback consumer can distinguish between
+ // "the promise rejected with null" or "the promise fulfilled with undefined".
+ if (!reason) {
+ var newReason = new Error('Promise was rejected with a falsy value');
+ newReason.reason = reason;
+ reason = newReason;
+ }
+ return cb(reason);
+}
- var length = args.length
- var _args = new Array(length)
- for (var i = 0; i < length; i++) _args[i] = args[i]
+function callbackify(original) {
+ if (typeof original !== 'function') {
+ throw new TypeError('The "original" argument must be of type Function');
+ }
- render.apply(render, _args)
- args = null
- })
+ // We DO NOT return the promise as it gives the user a false sense that
+ // the promise is actually somehow related to the callback's execution
+ // and that the callback throwing will reject the promise.
+ function callbackified() {
+ var args = [];
+ for (var i = 0; i < arguments.length; i++) {
+ args.push(arguments[i]);
}
- args = arguments
+ var maybeCb = args.pop();
+ if (typeof maybeCb !== 'function') {
+ throw new TypeError('The last argument must be of type Function');
+ }
+ var self = this;
+ var cb = function() {
+ return maybeCb.apply(self, arguments);
+ };
+ // In true node style we process the callback on `nextTick` with all the
+ // implications (stack, `uncaughtException`, `async_hooks`)
+ original.apply(this, args)
+ .then(function(ret) { process.nextTick(cb, null, ret) },
+ function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });
}
+
+ Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
+ Object.defineProperties(callbackified,
+ getOwnPropertyDescriptors(original));
+ return callbackified;
}
+exports.callbackify = callbackify;
-},{"assert":85}],104:[function(require,module,exports){
-var assert = require('assert')
-var wayfarer = require('wayfarer')
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "./node_modules/process/browser.js")))
-// electron support
-var isLocalFile = (/file:\/\//.test(
- typeof window === 'object' &&
- window.location &&
- window.location.origin
-))
+/***/ }),
-/* eslint-disable no-useless-escape */
-var electron = '^(file:\/\/|\/)(.*\.html?\/?)?'
-var protocol = '^(http(s)?(:\/\/))?(www\.)?'
-var domain = '[a-zA-Z0-9-_\.]+(:[0-9]{1,5})?(\/{1})?'
-var qs = '[\?].*$'
-/* eslint-enable no-useless-escape */
+/***/ "./node_modules/webpack-stream/node_modules/webpack/buildin/global.js":
+/*!***********************************!*\
+ !*** (webpack)/buildin/global.js ***!
+ \***********************************/
+/*! no static exports found */
+/***/ (function(module, exports) {
-var stripElectron = new RegExp(electron)
-var prefix = new RegExp(protocol + domain)
-var normalize = new RegExp('#')
-var suffix = new RegExp(qs)
+var g;
-module.exports = Nanorouter
+// This works in non-strict mode
+g = (function() {
+ return this;
+})();
-function Nanorouter (opts) {
- if (!(this instanceof Nanorouter)) return new Nanorouter(opts)
- opts = opts || {}
- this.router = wayfarer(opts.default || '/404')
+try {
+ // This works if eval is allowed (see CSP)
+ g = g || new Function("return this")();
+} catch (e) {
+ // This works if the window reference is available
+ if (typeof window === "object") g = window;
}
-Nanorouter.prototype.on = function (routename, listener) {
- assert.equal(typeof routename, 'string')
- routename = routename.replace(/^[#/]/, '')
- this.router.on(routename, listener)
-}
+// g can still be undefined, but nothing to do about it...
+// We return undefined, instead of nothing here, so it's
+// easier to handle this case. if(!global) { ...}
-Nanorouter.prototype.emit = function (routename) {
- assert.equal(typeof routename, 'string')
- routename = pathname(routename, isLocalFile)
- return this.router.emit(routename)
-}
+module.exports = g;
-Nanorouter.prototype.match = function (routename) {
- assert.equal(typeof routename, 'string')
- routename = pathname(routename, isLocalFile)
- return this.router.match(routename)
-}
-// replace everything in a route but the pathname and hash
-function pathname (routename, isElectron) {
- if (isElectron) routename = routename.replace(stripElectron, '')
- else routename = routename.replace(prefix, '')
- return decodeURI(routename.replace(suffix, '').replace(normalize, '/'))
-}
+/***/ }),
-},{"assert":85,"wayfarer":123}],105:[function(require,module,exports){
-var assert = require('assert')
+/***/ "./src/extractors/chroma.js":
+/*!**********************************!*\
+ !*** ./src/extractors/chroma.js ***!
+ \**********************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-var hasWindow = typeof window !== 'undefined'
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
-function createScheduler () {
- var scheduler
- if (hasWindow) {
- if (!window._nanoScheduler) window._nanoScheduler = new NanoScheduler(true)
- scheduler = window._nanoScheduler
- } else {
- scheduler = new NanoScheduler()
- }
- return scheduler
-}
+function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
-function NanoScheduler (hasWindow) {
- this.hasWindow = hasWindow
- this.hasIdle = this.hasWindow && window.requestIdleCallback
- this.method = this.hasIdle ? window.requestIdleCallback.bind(window) : this.setTimeout
- this.scheduled = false
- this.queue = []
-}
+function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
-NanoScheduler.prototype.push = function (cb) {
- assert.equal(typeof cb, 'function', 'nanoscheduler.push: cb should be type function')
+function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
- this.queue.push(cb)
- this.schedule()
-}
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-NanoScheduler.prototype.schedule = function () {
- if (this.scheduled) return
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.ampSpectrum) !== 'object') {
+ throw new TypeError('Valid ampSpectrum is required to generate chroma');
+ }
- this.scheduled = true
- var self = this
- this.method(function (idleDeadline) {
- var cb
- while (self.queue.length && idleDeadline.timeRemaining() > 0) {
- cb = self.queue.shift()
- cb(idleDeadline)
- }
- self.scheduled = false
- if (self.queue.length) self.schedule()
- })
-}
+ if (_typeof(args.chromaFilterBank) !== 'object') {
+ throw new TypeError('Valid chromaFilterBank is required to generate chroma');
+ }
-NanoScheduler.prototype.setTimeout = function (cb) {
- setTimeout(cb, 0, {
- timeRemaining: function () {
- return 1
- }
- })
-}
+ var chromagram = args.chromaFilterBank.map(function (row, i) {
+ return args.ampSpectrum.reduce(function (acc, v, j) {
+ return acc + v * row[j];
+ }, 0);
+ });
+ var maxVal = Math.max.apply(Math, _toConsumableArray(chromagram));
+ return maxVal ? chromagram.map(function (v) {
+ return v / maxVal;
+ }) : chromagram;
+});
-module.exports = createScheduler
+/***/ }),
-},{"assert":85}],106:[function(require,module,exports){
-var scheduler = require('nanoscheduler')()
-var assert = require('assert')
+/***/ "./src/extractors/energy.js":
+/*!**********************************!*\
+ !*** ./src/extractors/energy.js ***!
+ \**********************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-var perf
-nanotiming.disabled = true
-try {
- perf = window.performance
- nanotiming.disabled = window.localStorage.DISABLE_NANOTIMING === 'true' || !perf.mark
-} catch (e) { }
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var assert__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! assert */ "./node_modules/assert/assert.js");
+/* harmony import */ var assert__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(assert__WEBPACK_IMPORTED_MODULE_0__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-module.exports = nanotiming
-function nanotiming (name) {
- assert.equal(typeof name, 'string', 'nanotiming: name should be type string')
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].signal) !== 'object') {
+ throw new TypeError();
+ }
- if (nanotiming.disabled) return noop
+ var energy = 0;
- var uuid = (perf.now() * 10000).toFixed() % Number.MAX_SAFE_INTEGER
- var startName = 'start-' + uuid + '-' + name
- perf.mark(startName)
+ for (var i = 0; i < arguments[0].signal.length; i++) {
+ energy += Math.pow(Math.abs(arguments[0].signal[i]), 2);
+ }
- function end (cb) {
- var endName = 'end-' + uuid + '-' + name
- perf.mark(endName)
+ return energy;
+});
- scheduler.push(function () {
- var err = null
- try {
- var measureName = name + ' [' + uuid + ']'
- perf.measure(measureName, startName, endName)
- perf.clearMarks(startName)
- perf.clearMarks(endName)
- } catch (e) { err = e }
- if (cb) cb(err, name)
- })
- }
+/***/ }),
- end.uuid = uuid
- return end
-}
+/***/ "./src/extractors/extractorUtilities.js":
+/*!**********************************************!*\
+ !*** ./src/extractors/extractorUtilities.js ***!
+ \**********************************************/
+/*! exports provided: mu */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-function noop (cb) {
- if (cb) {
- scheduler.push(function () {
- cb(new Error('nanotiming: performance API unavailable'))
- })
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mu", function() { return mu; });
+function mu(i, amplitudeSpect) {
+ var numerator = 0;
+ var denominator = 0;
+
+ for (var k = 0; k < amplitudeSpect.length; k++) {
+ numerator += Math.pow(k, i) * Math.abs(amplitudeSpect[k]);
+ denominator += amplitudeSpect[k];
}
-}
-},{"assert":85,"nanoscheduler":105}],107:[function(require,module,exports){
-var assert = require('assert')
+ return numerator / denominator;
+}
-module.exports = objectChangeCallsite
+/***/ }),
-function objectChangeCallsite (target, callback) {
- assert.equal(typeof target, 'object', 'object-change-callsite: target should be type object')
- assert.equal(typeof callback, 'function', 'object-change-callsite: callback should be type function')
+/***/ "./src/extractors/loudness.js":
+/*!************************************!*\
+ !*** ./src/extractors/loudness.js ***!
+ \************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
- return new Proxy(target, {
- set: function (obj, prop, value) {
- var err = new Error()
- var trace = strip(err.stack)
- callback(prop, value, trace)
- obj[prop] = value
- return true
- },
- deleteProperty: function (target, prop) {
- var err = new Error()
- var trace = strip(err.stack)
- callback(prop, undefined, trace)
- if (prop in target) {
- delete target[prop]
- return true
- }
- return false
- }
- })
-}
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-function strip (str) {
- var arr = str.split('\n')
- arr = arr.length > 2 ? arr.slice(2) : arr
- arr[0] = arr[0].replace(/^ {4}at /, '')
- return '\n' + arr.join('\n')
-}
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.ampSpectrum) !== 'object' || _typeof(args.barkScale) !== 'object') {
+ throw new TypeError();
+ }
-},{"assert":125}],108:[function(require,module,exports){
-/* global MutationObserver */
-var document = require('global/document')
-var window = require('global/window')
-var watch = Object.create(null)
-var KEY_ID = 'onloadid' + Math.random().toString(36).slice(2)
-var KEY_ATTR = 'data-' + KEY_ID
-var INDEX = 0
+ var NUM_BARK_BANDS = 24;
+ var specific = new Float32Array(NUM_BARK_BANDS);
+ var total = 0;
+ var normalisedSpectrum = args.ampSpectrum;
+ var bbLimits = new Int32Array(NUM_BARK_BANDS + 1);
+ bbLimits[0] = 0;
+ var currentBandEnd = args.barkScale[normalisedSpectrum.length - 1] / NUM_BARK_BANDS;
+ var currentBand = 1;
-if (window && window.MutationObserver) {
- var observer = new MutationObserver(function (mutations) {
- if (Object.keys(watch).length < 1) return
- for (var i = 0; i < mutations.length; i++) {
- if (mutations[i].attributeName === KEY_ATTR) {
- eachAttr(mutations[i], turnon, turnoff)
- continue
- }
- eachMutation(mutations[i].removedNodes, function (index, el) {
- if (!document.documentElement.contains(el)) turnoff(index, el)
- })
- eachMutation(mutations[i].addedNodes, function (index, el) {
- if (document.documentElement.contains(el)) turnon(index, el)
- })
+ for (var i = 0; i < normalisedSpectrum.length; i++) {
+ while (args.barkScale[i] > currentBandEnd) {
+ bbLimits[currentBand++] = i;
+ currentBandEnd = currentBand * args.barkScale[normalisedSpectrum.length - 1] / NUM_BARK_BANDS;
}
- })
+ }
- observer.observe(document.documentElement, {
- childList: true,
- subtree: true,
- attributes: true,
- attributeOldValue: true,
- attributeFilter: [KEY_ATTR]
- })
-}
+ bbLimits[NUM_BARK_BANDS] = normalisedSpectrum.length - 1; //process
-module.exports = function onload (el, on, off, caller) {
- on = on || function () {}
- off = off || function () {}
- el.setAttribute(KEY_ATTR, 'o' + INDEX)
- watch['o' + INDEX] = [on, off, 0, caller || onload.caller]
- INDEX += 1
- return el
-}
+ for (var _i = 0; _i < NUM_BARK_BANDS; _i++) {
+ var sum = 0;
-module.exports.KEY_ATTR = KEY_ATTR
-module.exports.KEY_ID = KEY_ID
+ for (var j = bbLimits[_i]; j < bbLimits[_i + 1]; j++) {
+ sum += normalisedSpectrum[j];
+ }
-function turnon (index, el) {
- if (watch[index][0] && watch[index][2] === 0) {
- watch[index][0](el)
- watch[index][2] = 1
- }
-}
+ specific[_i] = Math.pow(sum, 0.23);
+ } //get total loudness
-function turnoff (index, el) {
- if (watch[index][1] && watch[index][2] === 1) {
- watch[index][1](el)
- watch[index][2] = 0
- }
-}
-function eachAttr (mutation, on, off) {
- var newValue = mutation.target.getAttribute(KEY_ATTR)
- if (sameOrigin(mutation.oldValue, newValue)) {
- watch[newValue] = watch[mutation.oldValue]
- return
- }
- if (watch[mutation.oldValue]) {
- off(mutation.oldValue, mutation.target)
- }
- if (watch[newValue]) {
- on(newValue, mutation.target)
+ for (var _i2 = 0; _i2 < specific.length; _i2++) {
+ total += specific[_i2];
}
-}
-
-function sameOrigin (oldValue, newValue) {
- if (!oldValue || !newValue) return false
- return watch[oldValue][3] === watch[newValue][3]
-}
-function eachMutation (nodes, fn) {
- var keys = Object.keys(watch)
- for (var i = 0; i < nodes.length; i++) {
- if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute(KEY_ATTR)) {
- var onloadid = nodes[i].getAttribute(KEY_ATTR)
- keys.forEach(function (k) {
- if (onloadid === k) {
- fn(k, nodes[i])
- }
- })
- }
- if (nodes[i] && nodes[i].childNodes.length > 0) {
- eachMutation(nodes[i].childNodes, fn)
- }
- }
-}
+ return {
+ specific: specific,
+ total: total
+ };
+});
-},{"global/document":77,"global/window":78}],109:[function(require,module,exports){
-var scheduler = require('nanoscheduler')()
-var assert = require('assert')
+/***/ }),
-var entryTypes = [
- 'frame',
- 'measure',
- 'navigation',
- 'resource',
- 'longtask'
-]
+/***/ "./src/extractors/mfcc.js":
+/*!********************************!*\
+ !*** ./src/extractors/mfcc.js ***!
+ \********************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-module.exports = onPerformance
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _powerSpectrum__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./powerSpectrum */ "./src/extractors/powerSpectrum.js");
+/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./../utilities */ "./src/utilities.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-function onPerformance (cb) {
- assert.equal(typeof cb, 'function', 'on-performance: cb should be type function')
- var PerformanceObserver = typeof window !== 'undefined' && window.PerformanceObserver
- if (!PerformanceObserver) return
- // Enable singleton.
- if (window._onperformance) {
- window._onperformance.push(cb)
- return stop
- }
- window._onperformance = [cb]
- var observer = new PerformanceObserver(parseEntries)
- setTimeout(function () {
- parseEntries(window.performance)
- observer.observe({ entryTypes: entryTypes })
- }, 0)
- return stop
+var dct = __webpack_require__(/*! dct */ "./node_modules/dct/index.js");
- function stop () {
- window._onperformance.splice(window._onperformance.indexOf(cb), 1)
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.ampSpectrum) !== 'object') {
+ throw new TypeError('Valid ampSpectrum is required to generate MFCC');
}
- function parseEntries (list) {
- list.getEntries().forEach(function (entry) {
- scheduler.push(function () {
- clear(entry)
- window._onperformance.forEach(function (cb) {
- cb(entry)
- })
- })
- })
+ if (_typeof(args.melFilterBank) !== 'object') {
+ throw new TypeError('Valid melFilterBank is required to generate MFCC');
}
- // Navigation, longtask and frame don't have a clear method (yet)
- // Resource timings can only be cleared in bulk
- // see: https://developer.mozilla.org/en-US/docs/Web/API/Performance/clearMeasures
- function clear (entry) {
- var type = entry.entryType
- if (type === 'measure') window.performance.clearMeasures(entry.name)
- else if (type === 'resource') window.performance.clearResourceTimings()
- }
-}
+ var numberOfMFCCCoefficients = Math.min(40, Math.max(1, args.numberOfMFCCCoefficients || 13)); // Tutorial from:
+ // http://practicalcryptography.com/miscellaneous/machine-learning
+ // /guide-mel-frequency-cepstral-coefficients-mfccs/
-},{"assert":85,"nanoscheduler":105}],110:[function(require,module,exports){
-(function (process){
-// Generated by CoffeeScript 1.12.2
-(function() {
- var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
+ var powSpec = Object(_powerSpectrum__WEBPACK_IMPORTED_MODULE_0__["default"])(args);
+ var numFilters = args.melFilterBank.length;
+ var filtered = Array(numFilters);
- if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
- module.exports = function() {
- return performance.now();
- };
- } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
- module.exports = function() {
- return (getNanoSeconds() - nodeLoadTime) / 1e6;
- };
- hrtime = process.hrtime;
- getNanoSeconds = function() {
- var hr;
- hr = hrtime();
- return hr[0] * 1e9 + hr[1];
- };
- moduleLoadTime = getNanoSeconds();
- upTime = process.uptime() * 1e9;
- nodeLoadTime = moduleLoadTime - upTime;
- } else if (Date.now) {
- module.exports = function() {
- return Date.now() - loadTime;
- };
- loadTime = Date.now();
- } else {
- module.exports = function() {
- return new Date().getTime() - loadTime;
- };
- loadTime = new Date().getTime();
+ if (numFilters < numberOfMFCCCoefficients) {
+ throw new Error("Insufficient filter bank for requested number of coefficients");
}
-}).call(this);
+ var loggedMelBands = new Float32Array(numFilters);
+ for (var i = 0; i < loggedMelBands.length; i++) {
+ filtered[i] = new Float32Array(args.bufferSize / 2);
+ loggedMelBands[i] = 0;
+ for (var j = 0; j < args.bufferSize / 2; j++) {
+ //point-wise multiplication between power spectrum and filterbanks.
+ filtered[i][j] = args.melFilterBank[i][j] * powSpec[j]; //summing up all of the coefficients into one array
-}).call(this,require('_process'))
-},{"_process":135}],111:[function(require,module,exports){
-module.exports = plucker
+ loggedMelBands[i] += filtered[i][j];
+ } //log each coefficient.
-function plucker(path, object) {
- return arguments.length >= 2
- ? pluck(path)(object)
- : pluck(path)
-}
-function pluck(path) {
- path = typeof path === 'string'
- ? String(path).trim().split('.')
- : path
+ loggedMelBands[i] = Math.log(loggedMelBands[i] + 1);
+ } //dct
- if (path.length < 2) {
- path = path[0]
- return pluckSingle
- } else {
- var l = path.length
- return pluckPath
- }
- function pluckSingle(object) {
- return object[path]
- }
+ var loggedMelBandsArray = Array.prototype.slice.call(loggedMelBands);
+ var mfccs = dct(loggedMelBandsArray).slice(0, numberOfMFCCCoefficients);
+ return mfccs;
+});
- function pluckPath(object) {
- for (var i = 0; i < l; i++) {
- if (typeof object === 'undefined') break
+/***/ }),
- object = object[path[i]]
- }
+/***/ "./src/extractors/perceptualSharpness.js":
+/*!***********************************************!*\
+ !*** ./src/extractors/perceptualSharpness.js ***!
+ \***********************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
- return object
- }
-}
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _loudness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loudness */ "./src/extractors/loudness.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-},{}],112:[function(require,module,exports){
-module.exports = prettierBytes
-function prettierBytes (num) {
- if (typeof num !== 'number' || isNaN(num)) {
- throw new TypeError('Expected a number, got ' + typeof num)
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].signal) !== 'object') {
+ throw new TypeError();
}
- var neg = num < 0
- var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+ var loudnessValue = Object(_loudness__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments[0]);
+ var spec = loudnessValue.specific;
+ var output = 0;
- if (neg) {
- num = -num
+ for (var i = 0; i < spec.length; i++) {
+ if (i < 15) {
+ output += (i + 1) * spec[i + 1];
+ } else {
+ output += 0.066 * Math.exp(0.171 * (i + 1));
+ }
}
- if (num < 1) {
- return (neg ? '-' : '') + num + ' B'
- }
+ output *= 0.11 / loudnessValue.total;
+ return output;
+});
- var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
- num = Number(num / Math.pow(1000, exponent))
- var unit = units[exponent]
+/***/ }),
- if (num >= 10 || num % 1 === 0) {
- // Do not show decimals when the number is two-digit, or if the number has no
- // decimal component.
- return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit
- } else {
- return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit
- }
-}
+/***/ "./src/extractors/perceptualSpread.js":
+/*!********************************************!*\
+ !*** ./src/extractors/perceptualSpread.js ***!
+ \********************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-},{}],113:[function(require,module,exports){
-var inherits = require('inherits')
-var EventEmitter = require('events').EventEmitter
-var now = require('right-now')
-var raf = require('raf')
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _loudness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loudness */ "./src/extractors/loudness.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-module.exports = Engine
-function Engine(fn) {
- if (!(this instanceof Engine))
- return new Engine(fn)
- this.running = false
- this.last = now()
- this._frame = 0
- this._tick = this.tick.bind(this)
- if (fn)
- this.on('tick', fn)
-}
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].signal) !== 'object') {
+ throw new TypeError();
+ }
-inherits(Engine, EventEmitter)
+ var loudnessValue = Object(_loudness__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments[0]);
+ var max = 0;
-Engine.prototype.start = function() {
- if (this.running)
- return
- this.running = true
- this.last = now()
- this._frame = raf(this._tick)
- return this
-}
+ for (var i = 0; i < loudnessValue.specific.length; i++) {
+ if (loudnessValue.specific[i] > max) {
+ max = loudnessValue.specific[i];
+ }
+ }
-Engine.prototype.stop = function() {
- this.running = false
- if (this._frame !== 0)
- raf.cancel(this._frame)
- this._frame = 0
- return this
-}
+ var spread = Math.pow((loudnessValue.total - max) / loudnessValue.total, 2);
+ return spread;
+});
-Engine.prototype.tick = function() {
- this._frame = raf(this._tick)
- var time = now()
- var dt = time - this.last
- this.emit('tick', dt)
- this.last = time
-}
-},{"events":132,"inherits":83,"raf":114,"right-now":117}],114:[function(require,module,exports){
-(function (global){
-var now = require('performance-now')
- , root = typeof window === 'undefined' ? global : window
- , vendors = ['moz', 'webkit']
- , suffix = 'AnimationFrame'
- , raf = root['request' + suffix]
- , caf = root['cancel' + suffix] || root['cancelRequest' + suffix]
+/***/ }),
-for(var i = 0; !raf && i < vendors.length; i++) {
- raf = root[vendors[i] + 'Request' + suffix]
- caf = root[vendors[i] + 'Cancel' + suffix]
- || root[vendors[i] + 'CancelRequest' + suffix]
-}
+/***/ "./src/extractors/powerSpectrum.js":
+/*!*****************************************!*\
+ !*** ./src/extractors/powerSpectrum.js ***!
+ \*****************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-// Some versions of FF have rAF but not cAF
-if(!raf || !caf) {
- var last = 0
- , id = 0
- , queue = []
- , frameDuration = 1000 / 60
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- raf = function(callback) {
- if(queue.length === 0) {
- var _now = now()
- , next = Math.max(0, frameDuration - (_now - last))
- last = next + _now
- setTimeout(function() {
- var cp = queue.slice(0)
- // Clear queue here to prevent
- // callbacks from appending listeners
- // to the current frame's queue
- queue.length = 0
- for(var i = 0; i < cp.length; i++) {
- if(!cp[i].cancelled) {
- try{
- cp[i].callback(last)
- } catch(e) {
- setTimeout(function() { throw e }, 0)
- }
- }
- }
- }, Math.round(next))
- }
- queue.push({
- handle: ++id,
- callback: callback,
- cancelled: false
- })
- return id
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].ampSpectrum) !== 'object') {
+ throw new TypeError();
}
- caf = function(handle) {
- for(var i = 0; i < queue.length; i++) {
- if(queue[i].handle === handle) {
- queue[i].cancelled = true
- }
- }
- }
-}
+ var powerSpectrum = new Float32Array(arguments[0].ampSpectrum.length);
-module.exports = function(fn) {
- // Wrap in a new function to prevent
- // `cancel` potentially being assigned
- // to the native rAF function
- return raf.call(root, fn)
-}
-module.exports.cancel = function() {
- caf.apply(root, arguments)
-}
-module.exports.polyfill = function(object) {
- if (!object) {
- object = root;
+ for (var i = 0; i < powerSpectrum.length; i++) {
+ powerSpectrum[i] = Math.pow(arguments[0].ampSpectrum[i], 2);
}
- object.requestAnimationFrame = raf
- object.cancelAnimationFrame = caf
-}
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"performance-now":110}],115:[function(require,module,exports){
-(function(U,X){"object"===typeof exports&&"undefined"!==typeof module?module.exports=X():"function"===typeof define&&define.amd?define(X):U.createREGL=X()})(this,function(){function U(a,b){this.id=Eb++;this.type=a;this.data=b}function X(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1>>=b;c=(255>>=c;b|=c;c=(15>>=c;b|=c;c=(3>>c>>1}function hb(){function a(a){a:{for(var b=16;268435456>=b;b*=16)if(a<=b){a=b;break a}a=0}b=c[gb(a)>>2];return 0>2].push(a)}var c=J(8,function(){return[]});return{alloc:a,free:b,allocType:function(b,c){var d=null;switch(b){case 5120:d=new Int8Array(a(c),0,c);break;case 5121:d=new Uint8Array(a(c),0,c);break;case 5122:d=new Int16Array(a(2*c),0,c);break;case 5123:d=new Uint16Array(a(2*c),0,c);break;case 5124:d=new Int32Array(a(4*c),0,c);break;case 5125:d=new Uint32Array(a(4*c),0,c);break;case 5126:d=new Float32Array(a(4*c),0,c);break;default:return null}return d.length!==
-c?d.subarray(0,c):d},freeType:function(a){b(a.buffer)}}}function da(a){return!!a&&"object"===typeof a&&Array.isArray(a.shape)&&Array.isArray(a.stride)&&"number"===typeof a.offset&&a.shape.length===a.stride.length&&(Array.isArray(a.data)||M(a.data))}function ib(a,b,c,e,f,d){for(var p=0;pd&&(d=e.buffer.byteLength,5123===m?d>>=1:5125===m&&(d>>=2));e.vertCount=d;d=h;0>h&&(d=4,h=e.buffer.dimension,1===h&&(d=0),2===h&&(d=1),3===h&&(d=4));e.primType=d}function p(a){e.elementsCount--;delete n[a.id];a.buffer.destroy();a.buffer=null}var n={},u=0,t={uint8:5121,uint16:5123};b.oes_element_index_uint&&(t.uint32=5125);f.prototype.bind=function(){this.buffer.bind()};var w=[];return{create:function(a,
-b){function l(a){if(a)if("number"===typeof a)h(a),g.primType=4,g.vertCount=a|0,g.type=5121;else{var b=null,c=35044,e=-1,f=-1,k=0,n=0;if(Array.isArray(a)||M(a)||da(a))b=a;else if("data"in a&&(b=a.data),"usage"in a&&(c=ob[a.usage]),"primitive"in a&&(e=Ta[a.primitive]),"count"in a&&(f=a.count|0),"type"in a&&(n=t[a.type]),"length"in a)k=a.length|0;else if(k=f,5123===n||5122===n)k*=2;else if(5125===n||5124===n)k*=4;d(g,b,c,e,f,k,n)}else h(),g.primType=4,g.vertCount=0,g.type=5121;return l}var h=c.create(null,
-34963,!0),g=new f(h._buffer);e.elementsCount++;l(a);l._reglType="elements";l._elements=g;l.subdata=function(a,b){h.subdata(a,b);return l};l.destroy=function(){p(g)};return l},createStream:function(a){var b=w.pop();b||(b=new f(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){w.push(a)},getElements:function(a){return"function"===typeof a&&a._elements instanceof f?a._elements:null},clear:function(){S(n).forEach(p)}}}function pb(a){for(var b=E.allocType(5123,
-a.length),c=0;c>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?f:-14>d?f+(e+1024>>-14-d):15>=e,c.height>>=e,B(c,g[e]),a.mipmask|=1<b;++b)a.images[b]=null;return a}function nb(a){for(var b=a.images,c=0;cb){for(var c=0;c=--this.refCount&&D(this)}});p.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(ia).forEach(function(b){a+=ia[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;Z.call(c);var g=Ha();"number"===typeof a?"number"===typeof b?r(g,a|0,b|0):r(g,a|0,a|0):a?(G(c,a),m(g,a)):r(g,1,1);c.genMipmaps&&(g.mipmask=(g.width<<1)-1);f.mipmask=g.mipmask;u(f,
-g);f.internalformat=g.internalformat;e.width=g.width;e.height=g.height;xa(f);z(g,3553);H(c,3553);ya();nb(g);p.profile&&(f.stats.size=Ja(f.internalformat,f.type,g.width,g.height,c.genMipmaps,!1));e.format=aa[f.internalformat];e.type=K[f.type];e.mag=fa[c.magFilter];e.min=Da[c.minFilter];e.wrapS=ua[c.wrapS];e.wrapT=ua[c.wrapT];return e}var f=new O(3553);ia[f.id]=f;d.textureCount++;e(b,c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var m=h();u(m,f);m.width=0;m.height=0;B(m,a);m.width=m.width||(f.width>>
-d)-b;m.height=m.height||(f.height>>d)-c;xa(f);l(m,3553,b,c,d);ya();g(m);return e};e.resize=function(b,c){var g=b|0,d=c|0||g;if(g===f.width&&d===f.height)return e;e.width=f.width=g;e.height=f.height=d;xa(f);for(var h=0;f.mipmask>>h;++h){var m=g>>h,x=d>>h;if(!m||!x)break;a.texImage2D(3553,h,f.format,m,x,0,f.format,f.type,null)}ya();p.profile&&(f.stats.size=Ja(f.internalformat,f.type,g,d,!1,!1));return e};e._reglType="texture2d";e._texture=f;p.profile&&(e.stats=f.stats);e.destroy=function(){f.decRef()};
-return e},createCube:function(b,c,e,f,q,n){function k(a,b,c,g,e,d){var f,ca=y.texInfo;Z.call(ca);for(f=0;6>f;++f)D[f]=Ha();if("number"===typeof a||!a)for(a=a|0||1,f=0;6>f;++f)r(D[f],a,a);else if("object"===typeof a)if(b)m(D[0],a),m(D[1],b),m(D[2],c),m(D[3],g),m(D[4],e),m(D[5],d);else if(G(ca,a),t(y,a),"faces"in a)for(a=a.faces,f=0;6>f;++f)u(D[f],y),m(D[f],a[f]);else for(f=0;6>f;++f)m(D[f],a);u(y,D[0]);y.mipmask=ca.genMipmaps?(D[0].width<<1)-1:D[0].mipmask;y.internalformat=D[0].internalformat;k.width=
-D[0].width;k.height=D[0].height;xa(y);for(f=0;6>f;++f)z(D[f],34069+f);H(ca,34067);ya();p.profile&&(y.stats.size=Ja(y.internalformat,y.type,k.width,k.height,ca.genMipmaps,!0));k.format=aa[y.internalformat];k.type=K[y.type];k.mag=fa[ca.magFilter];k.min=Da[ca.minFilter];k.wrapS=ua[ca.wrapS];k.wrapT=ua[ca.wrapT];for(f=0;6>f;++f)nb(D[f]);return k}var y=new O(34067);ia[y.id]=y;d.cubeCount++;var D=Array(6);k(b,c,e,f,q,n);k.subimage=function(a,b,c,e,f){c|=0;e|=0;f|=0;var d=h();u(d,y);d.width=0;d.height=0;
-B(d,b);d.width=d.width||(y.width>>f)-c;d.height=d.height||(y.height>>f)-e;xa(y);l(d,34069+a,c,e,f);ya();g(d);return k};k.resize=function(b){b|=0;if(b!==y.width){k.width=y.width=b;k.height=y.height=b;xa(y);for(var c=0;6>c;++c)for(var g=0;y.mipmask>>g;++g)a.texImage2D(34069+c,g,y.format,b>>g,b>>g,0,y.format,y.type,null);ya();p.profile&&(y.stats.size=Ja(y.internalformat,y.type,k.width,k.height,!1,!0));return k}};k._reglType="textureCube";k._texture=y;p.profile&&(k.stats=y.stats);k.destroy=function(){y.decRef()};
-return k},clear:function(){for(var b=0;bc;++c)if(0!==(b.mipmask&1<>c,b.height>>c,0,b.internalformat,
-b.type,null);else for(var g=0;6>g;++g)a.texImage2D(34069+g,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);H(b.texInfo,b.target)})},refresh:function(){for(var b=0;bg;++g){for(r=
-0;ra;++a)c[a].resize(g);b.width=b.height=g;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})},clear:function(){S(H).forEach(q)},
-restore:function(){z.cur=null;z.next=null;z.dirty=!0;S(H).forEach(function(b){b.framebuffer=a.createFramebuffer();r(b)})}})}function Za(){this.w=this.z=this.y=this.x=this.state=0;this.buffer=null;this.size=0;this.normalized=!1;this.type=5126;this.divisor=this.stride=this.offset=0}function Sb(a,b,c,e,f){function d(a){if(a!==h.currentVAO){var c=b.oes_vertex_array_object;a?c.bindVertexArrayOES(a.vao):c.bindVertexArrayOES(null);h.currentVAO=a}}function p(c){if(c!==h.currentVAO){if(c)c.bindAttrs();else for(var e=
-b.angle_instanced_arrays,f=0;f=
-l.byteLength?n.subdata(l):(n.destroy(),c.buffers[d]=null));c.buffers[d]||(n=c.buffers[d]=f.create(h,34962,!1,!0));k.buffer=f.getBuffer(n);k.size=k.buffer.dimension|0;k.normalized=!1;k.type=k.buffer.dtype;k.offset=0;k.stride=0;k.divisor=0;k.state=1;g[d]=1}else f.getBuffer(h)?(k.buffer=f.getBuffer(h),k.size=k.buffer.dimension|0,k.normalized=!1,k.type=k.buffer.dtype,k.offset=0,k.stride=0,k.divisor=0,k.state=1):f.getBuffer(h.buffer)?(k.buffer=f.getBuffer(h.buffer),k.size=(+h.size||k.buffer.dimension)|
-0,k.normalized=!!h.normalized||!1,k.type="type"in h?Ia[h.type]:k.buffer.dtype,k.offset=(h.offset||0)|0,k.stride=(h.stride||0)|0,k.divisor=(h.divisor||0)|0,k.state=1):"x"in h&&(k.x=+h.x||0,k.y=+h.y||0,k.z=+h.z||0,k.w=+h.w||0,k.state=2)}for(a=0;aa&&(a=b.stats.uniformsCount)});
-return a},c.getMaxAttributesCount=function(){var a=0;B.forEach(function(b){b.stats.attributesCount>a&&(a=b.stats.attributesCount)});return a});return{clear:function(){var b=a.deleteShader.bind(a);S(t).forEach(b);t={};S(w).forEach(b);w={};B.forEach(function(b){a.deleteProgram(b.program)});B.length=0;k={};c.shaderCount=0},program:function(b,e,d,f){var l=k[e];l||(l=k[e]={});var p=l[b];if(p&&(p.refCount++,!f))return p;var v=new n(e,b);c.shaderCount++;u(v,d,f);p||(l[b]=v);B.push(v);return A(v,{destroy:function(){v.refCount--;
-if(0>=v.refCount){a.deleteProgram(v.program);var b=B.indexOf(v);B.splice(b,1);c.shaderCount--}0>=l[v.vertId].refCount&&(a.deleteShader(w[v.vertId]),delete w[v.vertId],delete k[v.fragId][v.vertId]);Object.keys(k[v.fragId]).length||(a.deleteShader(t[v.fragId]),delete t[v.fragId],delete k[v.fragId])}})},restore:function(){t={};w={};for(var a=0;a"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{",
-"if(",x,"(",e,".buffer)){",k,"=",f,".createStream(",34962,",",e,".buffer);","}else{",k,"=",f,".getBuffer(",e,".buffer);","}",l,'="type" in ',e,"?",g.glTypes,"[",e,".type]:",k,".dtype;",h.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",h.isStream,"){",f,".destroyStream(",k,");","}");return h})});return g}function D(a,b){var c=a["static"],d=a.dynamic;if("vao"in c){var e=c.vao;null!==e&&null===t.getVAO(e)&&(e=t.createVAO(e));return v(function(a){return a.link(t.getVAO(e))})}if("vao"in
-d){var f=d.vao;return L(f,function(a,b){var c=a.invoke(b,f);return b.def(a.shared.vao+".getVAO("+c+")")})}return null}function y(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=v(function(a,b){return"number"===typeof c||"boolean"===typeof c?""+c:a.link(c)})});Object.keys(c).forEach(function(a){var b=c[a];d[a]=L(b,function(a,c){return a.invoke(c,b)})});return d}function la(a,b,d,e,f){function h(a){var b=m[a];b&&($a[a]=b)}var k=Z(a,b),l=E(a,f),m=F(a,l,f),n=H(a,
-f),$a=O(a,f),p=G(a,f,k);h("viewport");h(g("scissor.box"));var q=0>1)",t],");")}function b(){c(w,".drawArraysInstancedANGLE(",
-[p,r,q,t],");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(k+".drawElements("+[p,q,u,r+"<<(("+u+"-5121)>>1)"]+");")}function b(){c(k+".drawArrays("+[p,r,q]+");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}var h=a.shared,k=h.gl,l=h.draw,m=d.draw,n=function(){var e=m.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(l,".","elements");e&&f("if("+e+")"+k+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),
-p=e("primitive"),r=e("offset"),q=function(){var e=m.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(l,".","count");return e}();if("number"===typeof q){if(0===q)return}else c("if(",q,"){"),c.exit("}");var t,w;oa&&(t=e("instances"),w=a.instancing);var u=n+".type",B=m.elements&&sa(m.elements);oa&&("number"!==typeof t||0<=t)?"string"===typeof t?(c("if(",t,">0){"),f(),c("}else if(",t,"<0){"),g(),c("}")):f():g()}function X(a,b,c,d,e){b=m();e=b.proc("body",e);
-oa&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function fa(a,b,c,d){C(a,b);c.useVAO?c.drawVAO?b(a.shared.vao,".setVAO(",c.drawVAO.append(a,b),");"):b(a.shared.vao,".setVAO(",a.shared.vao,".targetVAO);"):(b(a.shared.vao,".setVAO(null);"),U(a,b,c,d.attributes,function(){return!0}));ta(a,b,c,d.uniforms,function(){return!0});aa(a,b,b,c)}function Da(a,b){var c=a.proc("draw",1);C(a,c);V(a,c,b.context);R(a,c,b.framebuffer);T(a,c,b);N(a,c,b.state);
-Q(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(",d,".program);");if(b.shader.program)fa(a,c,b,b.shader.program);else{c(a.shared.vao,".setVAO(null);");var e=a.global.def("{}"),f=c.def(d,".id"),g=c.def(e,"[",f,"]");c(a.cond(g).then(g,".call(this,a0);")["else"](g,"=",e,"[",f,"]=",a.link(function(c){return X(fa,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0=--this.refCount&&p(this)};f.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(w).forEach(function(b){a+=w[b].stats.size});return a});return{create:function(b,c){function l(b,c){var d=0,e=0,k=32854;
-"object"===typeof b&&b?("shape"in b?(e=b.shape,d=e[0]|0,e=e[1]|0):("radius"in b&&(d=e=b.radius|0),"width"in b&&(d=b.width|0),"height"in b&&(e=b.height|0)),"format"in b&&(k=n[b.format])):"number"===typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==h.width||e!==h.height||k!==h.format)return l.width=h.width=d,l.height=h.height=e,h.format=k,a.bindRenderbuffer(36161,h.renderbuffer),a.renderbufferStorage(36161,k,d,e),f.profile&&(h.stats.size=T[h.format]*h.width*h.height),l.format=u[h.format],
-l}var h=new d(a.createRenderbuffer());w[h.id]=h;e.renderbufferCount++;l(b,c);l.resize=function(b,c){var d=b|0,e=c|0||d;if(d===h.width&&e===h.height)return l;l.width=h.width=d;l.height=h.height=e;a.bindRenderbuffer(36161,h.renderbuffer);a.renderbufferStorage(36161,h.format,d,e);f.profile&&(h.stats.size=T[h.format]*h.width*h.height);return l};l._reglType="renderbuffer";l._renderbuffer=h;f.profile&&(l.stats=h.stats);l.destroy=function(){h.decRef()};return l},clear:function(){S(w).forEach(p)},restore:function(){S(w).forEach(function(b){b.renderbuffer=
-a.createRenderbuffer();a.bindRenderbuffer(36161,b.renderbuffer);a.renderbufferStorage(36161,b.format,b.width,b.height)});a.bindRenderbuffer(36161,null)}}},Ya=[];Ya[6408]=4;Ya[6407]=3;var Pa=[];Pa[5121]=1;Pa[5126]=4;Pa[36193]=2;var Ba=["x","y","z","w"],Xb="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),Ea={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,
-"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},ab={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Ra={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,
-invert:5386},Ab={cw:2304,ccw:2305},Bb=new K(!1,!1,!1,function(){}),$b=function(a,b){function c(){this.endQueryIndex=this.startQueryIndex=-1;this.sum=0;this.stats=null}function e(a,b,d){var e=p.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;n.push(e)}if(!b.ext_disjoint_timer_query)return null;var f=[],d=[],p=[],n=[],u=[],t=[];return{beginQuery:function(a){var c=f.pop()||b.ext_disjoint_timer_query.createQueryEXT();b.ext_disjoint_timer_query.beginQueryEXT(35007,c);d.push(c);e(d.length-
-1,d.length,a)},endQuery:function(){b.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,c;a=d.length;if(0!==a){t.length=Math.max(t.length,a+1);u.length=Math.max(u.length,a+1);u[0]=0;var e=t[0]=0;for(c=a=0;c=C.length&&e()}var c=Cb(C,a);C[c]=b}}}function t(){var a=Q.viewport,b=Q.scissor_box;a[0]=a[1]=b[0]=b[1]=0;G.viewportWidth=G.framebufferWidth=G.drawingBufferWidth=a[2]=b[2]=l.drawingBufferWidth;G.viewportHeight=G.framebufferHeight=G.drawingBufferHeight=a[3]=b[3]=l.drawingBufferHeight}function w(){G.tick+=1;G.time=v();t();R.procs.poll()}function k(){y.refresh();t();R.procs.refresh();z&&z.update()}function v(){return(Db()-
-E)/1E3}a=Ib(a);if(!a)return null;var l=a.gl,h=l.getContextAttributes();l.isContextLost();var g=Jb(l,a);if(!g)return null;var q=Fb(),r={vaoCount:0,bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},m=g.extensions,z=$b(l,m),E=Db(),F=l.drawingBufferWidth,K=l.drawingBufferHeight,G={tick:0,time:0,viewportWidth:F,viewportHeight:K,framebufferWidth:F,framebufferHeight:K,drawingBufferWidth:F,drawingBufferHeight:K,pixelRatio:a.pixelRatio},
-H=Yb(l,m),O=Kb(l,r,a,function(a){return J.destroyBuffer(a)}),J=Sb(l,m,H,r,O),M=Lb(l,m,O,r),D=Tb(l,q,r,a),y=Ob(l,m,H,function(){R.procs.poll()},G,r,a),L=Zb(l,m,H,r,a),V=Rb(l,m,H,y,L,r),R=Wb(l,q,m,H,O,M,y,V,{},J,D,{elements:null,primitive:4,count:-1,offset:0,instances:-1},G,z,a),q=Ub(l,V,R.procs.poll,G,h,m,H),Q=R.next,N=l.canvas,C=[],S=[],T=[],U=[a.onDestroy],aa=null;N&&(N.addEventListener("webglcontextlost",f,!1),N.addEventListener("webglcontextrestored",d,!1));var X=V.setFBO=p({framebuffer:Y.define.call(null,
-1,"framebuffer")});k();h=A(p,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)X(A({framebuffer:a.framebuffer.faces[b]},a),n);else X(a,n);else n(null,a)},prop:Y.define.bind(null,1),context:Y.define.bind(null,2),"this":Y.define.bind(null,3),draw:p({}),buffer:function(a){return O.create(a,34962,!1,!1)},elements:function(a){return M.create(a,!1)},texture:y.create2D,cube:y.createCube,renderbuffer:L.create,framebuffer:V.create,framebufferCube:V.createCube,
-vao:J.createVAO,attributes:h,frame:u,on:function(a,b){var c;switch(a){case "frame":return u(b);case "lost":c=S;break;case "restore":c=T;break;case "destroy":c=U}c.push(b);return{cancel:function(){for(var a=0;a} arr The target array
- * @param {number} startIdx The index to begin removing from (inclusive)
- * @param {number} removeCount How many items to remove
- */
-module.exports = function removeItems (arr, startIdx, removeCount) {
- var i, length = arr.length
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.signal) !== 'object') {
+ throw new TypeError();
+ }
- if (startIdx >= length || removeCount === 0) {
- return
+ var rms = 0;
+
+ for (var i = 0; i < args.signal.length; i++) {
+ rms += Math.pow(args.signal[i], 2);
}
- removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount)
+ rms = rms / args.signal.length;
+ rms = Math.sqrt(rms);
+ return rms;
+});
- var len = length - removeCount
+/***/ }),
- for (i = startIdx; i < len; ++i) {
- arr[i] = arr[i + removeCount]
+/***/ "./src/extractors/spectralCentroid.js":
+/*!********************************************!*\
+ !*** ./src/extractors/spectralCentroid.js ***!
+ \********************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].ampSpectrum) !== 'object') {
+ throw new TypeError();
}
- arr.length = len
-}
+ return Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, arguments[0].ampSpectrum);
+});
-},{}],117:[function(require,module,exports){
-(function (global){
-module.exports =
- global.performance &&
- global.performance.now ? function now() {
- return performance.now()
- } : Date.now || function now() {
- return +new Date
+/***/ }),
+
+/***/ "./src/extractors/spectralFlatness.js":
+/*!********************************************!*\
+ !*** ./src/extractors/spectralFlatness.js ***!
+ \********************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].ampSpectrum) !== 'object') {
+ throw new TypeError();
}
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],118:[function(require,module,exports){
-module.exports = scrollToAnchor
+ var numerator = 0;
+ var denominator = 0;
-function scrollToAnchor (anchor, options) {
- if (anchor) {
- try {
- var el = document.querySelector(anchor)
- if (el) el.scrollIntoView(options)
- } catch (e) {}
+ for (var i = 0; i < arguments[0].ampSpectrum.length; i++) {
+ numerator += Math.log(arguments[0].ampSpectrum[i]);
+ denominator += arguments[0].ampSpectrum[i];
}
-}
-},{}],119:[function(require,module,exports){
-var fastSafeStringify = require('fast-safe-stringify')
-var copy = require('clipboard-copy')
+ return Math.exp(numerator / arguments[0].ampSpectrum.length) * arguments[0].ampSpectrum.length / denominator;
+});
-function tryStringify (obj) {
- try {
- return JSON.stringify(obj)
- } catch (e) {}
-}
+/***/ }),
-function stateCopy (obj) {
- var str = tryStringify(obj) || fastSafeStringify(obj)
- copy(str)
-}
+/***/ "./src/extractors/spectralFlux.js":
+/*!****************************************!*\
+ !*** ./src/extractors/spectralFlux.js ***!
+ \****************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-module.exports = stateCopy
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-},{"clipboard-copy":73,"fast-safe-stringify":76}],120:[function(require,module,exports){
-var C = "\u037c"
-var COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C)
-var SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet")
-var top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.signal) !== 'object' || _typeof(args.previousSignal) != 'object') {
+ throw new TypeError();
+ }
-// :: - Style modules encapsulate a set of CSS rules defined from
-// JavaScript. Their definitions are only available in a given DOM
-// root after it has been _mounted_ there with `StyleModule.mount`.
-//
-// Style modules should be created once and stored somewhere, as
-// opposed to re-creating them every time you need them. The amount of
-// CSS rules generated for a given DOM root is bounded by the amount
-// of style modules that were used. So to avoid leaking rules, don't
-// create these dynamically, but treat them as one-time allocations.
-var StyleModule = exports.StyleModule = function StyleModule(spec, options) {
- this.rules = []
- var ref = options || {};
- var finish = ref.finish;
+ var sf = 0;
- function splitSelector(selector) {
- return /^@/.test(selector) ? [selector] : selector.split(/,\s*/)
+ for (var i = -(args.bufferSize / 2); i < signal.length / 2 - 1; i++) {
+ x = Math.abs(args.signal[i]) - Math.abs(args.previousSignal[i]);
+ sf += (x + Math.abs(x)) / 2;
}
- function render(selectors, spec, target, isKeyframes) {
- var local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"
- if (isAt && spec == null) { return target.push(selectors[0] + ";") }
- for (var prop in spec) {
- var value = spec[prop]
- if (/&/.test(prop)) {
- render(prop.split(/,\s*/).map(function (part) { return selectors.map(function (sel) { return part.replace(/&/, sel); }); }).reduce(function (a, b) { return a.concat(b); }),
- value, target)
- } else if (value && typeof value == "object") {
- if (!isAt) { throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") }
- render(splitSelector(prop), value, local, keyframes)
- } else if (value != null) {
- local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, function (l) { return "-" + l.toLowerCase(); }) + ": " + value + ";")
- }
- }
- if (local.length || keyframes) {
- target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") +
- " {" + local.join(" ") + "}")
- }
+ return sf;
+});
+
+/***/ }),
+
+/***/ "./src/extractors/spectralKurtosis.js":
+/*!********************************************!*\
+ !*** ./src/extractors/spectralKurtosis.js ***!
+ \********************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].ampSpectrum) !== 'object') {
+ throw new TypeError();
}
- for (var prop in spec) { render(splitSelector(prop), spec[prop], this.rules) }
-};
+ var ampspec = arguments[0].ampSpectrum;
+ var mu1 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, ampspec);
+ var mu2 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, ampspec);
+ var mu3 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3, ampspec);
+ var mu4 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(4, ampspec);
+ var numerator = -3 * Math.pow(mu1, 4) + 6 * mu1 * mu2 - 4 * mu1 * mu3 + mu4;
+ var denominator = Math.pow(Math.sqrt(mu2 - Math.pow(mu1, 2)), 4);
+ return numerator / denominator;
+});
-// :: () → string
-// Returns a string containing the module's CSS rules.
-StyleModule.prototype.getRules = function getRules () { return this.rules.join("\n") };
+/***/ }),
-// :: () → string
-// Generate a new unique CSS class name.
-StyleModule.newName = function newName () {
- var id = top[COUNT] || 1
- top[COUNT] = id + 1
- return C + id.toString(36)
-};
+/***/ "./src/extractors/spectralRolloff.js":
+/*!*******************************************!*\
+ !*** ./src/extractors/spectralRolloff.js ***!
+ \*******************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-// :: (union, union<[StyleModule], StyleModule>)
-//
-// Mount the given set of modules in the given DOM root, which ensures
-// that the CSS rules defined by the module are available in that
-// context.
-//
-// Rules are only added to the document once per root.
-//
-// Rule order will follow the order of the modules, so that rules from
-// modules later in the array take precedence of those from earlier
-// modules. If you call this function multiple times for the same root
-// in a way that changes the order of already mounted modules, the old
-// order will be changed.
-StyleModule.mount = function mount (root, modules) {
- (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules])
-};
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-var adoptedSet = null
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].ampSpectrum) !== 'object') {
+ throw new TypeError();
+ }
-var StyleSet = function StyleSet(root) {
- if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") {
- if (adoptedSet) {
- root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets)
- return root[SET] = adoptedSet
- }
- this.sheet = new CSSStyleSheet
- root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets)
- adoptedSet = this
- } else {
- this.styleTag = (root.ownerDocument || root).createElement("style")
- var target = root.head || root
- target.insertBefore(this.styleTag, target.firstChild)
+ var ampspec = arguments[0].ampSpectrum; //calculate nyquist bin
+
+ var nyqBin = arguments[0].sampleRate / (2 * (ampspec.length - 1));
+ var ec = 0;
+
+ for (var i = 0; i < ampspec.length; i++) {
+ ec += ampspec[i];
}
- this.modules = []
- root[SET] = this
-};
-StyleSet.prototype.mount = function mount (modules) {
- var sheet = this.sheet
- var pos = 0 /* Current rule offset */, j = 0 /* Index into this.modules */
- for (var i = 0; i < modules.length; i++) {
- var mod = modules[i], index = this.modules.indexOf(mod)
- if (index < j && index > -1) { // Ordering conflict
- this.modules.splice(index, 1)
- j--
- index = -1
- }
- if (index == -1) {
- this.modules.splice(j++, 0, mod)
- if (sheet) { for (var k = 0; k < mod.rules.length; k++)
- { sheet.insertRule(mod.rules[k], pos++) } }
- } else {
- while (j < index) { pos += this.modules[j++].rules.length }
- pos += mod.rules.length
- j++
- }
+ var threshold = 0.99 * ec;
+ var n = ampspec.length - 1;
+
+ while (ec > threshold && n >= 0) {
+ ec -= ampspec[n];
+ --n;
}
- if (!sheet) {
- var text = ""
- for (var i$1 = 0; i$1 < this.modules.length; i$1++)
- { text += this.modules[i$1].getRules() + "\n" }
- this.styleTag.textContent = text
+ return (n + 1) * nyqBin;
+});
+
+/***/ }),
+
+/***/ "./src/extractors/spectralSkewness.js":
+/*!********************************************!*\
+ !*** ./src/extractors/spectralSkewness.js ***!
+ \********************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.ampSpectrum) !== 'object') {
+ throw new TypeError();
}
-};
-// Style::Object>
-//
-// A style is an object that, in the simple case, maps CSS property
-// names to strings holding their values, as in `{color: "red",
-// fontWeight: "bold"}`. The property names can be given in
-// camel-case—the library will insert a dash before capital letters
-// when converting them to CSS.
-//
-// If you include an underscore in a property name, it and everything
-// after it will be removed from the output, which can be useful when
-// providing a property multiple times, for browser compatibility
-// reasons.
-//
-// A property in a style object can also be a sub-selector, which
-// extends the current context to add a pseudo-selector or a child
-// selector. Such a property should contain a `&` character, which
-// will be replaced by the current selector. For example `{"&:before":
-// {content: '"hi"'}}`. Sub-selectors and regular properties can
-// freely be mixed in a given object. Any property containing a `&` is
-// assumed to be a sub-selector.
-//
-// Finally, a property can specify an @-block to be wrapped around the
-// styles defined inside the object that's the property's value. For
-// example to create a media query you can do `{"@media screen and
-// (min-width: 400px)": {...}}`.
+ var mu1 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, args.ampSpectrum);
+ var mu2 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, args.ampSpectrum);
+ var mu3 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3, args.ampSpectrum);
+ var numerator = 2 * Math.pow(mu1, 3) - 3 * mu1 * mu2 + mu3;
+ var denominator = Math.pow(Math.sqrt(mu2 - Math.pow(mu1, 2)), 3);
+ return numerator / denominator;
+});
+/***/ }),
-},{}],121:[function(require,module,exports){
-'use strict';
+/***/ "./src/extractors/spectralSlope.js":
+/*!*****************************************!*\
+ !*** ./src/extractors/spectralSlope.js ***!
+ \*****************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-Object.defineProperty(exports, '__esModule', { value: true });
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-var base = {
- 8: "Backspace",
- 9: "Tab",
- 10: "Enter",
- 12: "NumLock",
- 13: "Enter",
- 16: "Shift",
- 17: "Control",
- 18: "Alt",
- 20: "CapsLock",
- 27: "Escape",
- 32: " ",
- 33: "PageUp",
- 34: "PageDown",
- 35: "End",
- 36: "Home",
- 37: "ArrowLeft",
- 38: "ArrowUp",
- 39: "ArrowRight",
- 40: "ArrowDown",
- 44: "PrintScreen",
- 45: "Insert",
- 46: "Delete",
- 59: ";",
- 61: "=",
- 91: "Meta",
- 92: "Meta",
- 106: "*",
- 107: "+",
- 108: ",",
- 109: "-",
- 110: ".",
- 111: "/",
- 144: "NumLock",
- 145: "ScrollLock",
- 160: "Shift",
- 161: "Shift",
- 162: "Control",
- 163: "Control",
- 164: "Alt",
- 165: "Alt",
- 173: "-",
- 186: ";",
- 187: "=",
- 188: ",",
- 189: "-",
- 190: ".",
- 191: "/",
- 192: "`",
- 219: "[",
- 220: "\\",
- 221: "]",
- 222: "'",
- 229: "q"
-};
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.ampSpectrum) !== 'object') {
+ throw new TypeError();
+ } //linear regression
+
+
+ var ampSum = 0;
+ var freqSum = 0;
+ var freqs = new Float32Array(args.ampSpectrum.length);
+ var powFreqSum = 0;
+ var ampFreqSum = 0;
+
+ for (var i = 0; i < args.ampSpectrum.length; i++) {
+ ampSum += args.ampSpectrum[i];
+ var curFreq = i * args.sampleRate / args.bufferSize;
+ freqs[i] = curFreq;
+ powFreqSum += curFreq * curFreq;
+ freqSum += curFreq;
+ ampFreqSum += curFreq * args.ampSpectrum[i];
+ }
+
+ return (args.ampSpectrum.length * ampFreqSum - freqSum * ampSum) / (ampSum * (powFreqSum - Math.pow(freqSum, 2)));
+});
+
+/***/ }),
+
+/***/ "./src/extractors/spectralSpread.js":
+/*!******************************************!*\
+ !*** ./src/extractors/spectralSpread.js ***!
+ \******************************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+
+/* harmony default export */ __webpack_exports__["default"] = (function (args) {
+ if (_typeof(args.ampSpectrum) !== 'object') {
+ throw new TypeError();
+ }
+
+ return Math.sqrt(Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, args.ampSpectrum) - Math.pow(Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, args.ampSpectrum), 2));
+});
+
+/***/ }),
+
+/***/ "./src/extractors/zcr.js":
+/*!*******************************!*\
+ !*** ./src/extractors/zcr.js ***!
+ \*******************************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+/* harmony default export */ __webpack_exports__["default"] = (function () {
+ if (_typeof(arguments[0].signal) !== 'object') {
+ throw new TypeError();
+ }
+
+ var zcr = 0;
+
+ for (var i = 1; i < arguments[0].signal.length; i++) {
+ if (arguments[0].signal[i - 1] >= 0 && arguments[0].signal[i] < 0 || arguments[0].signal[i - 1] < 0 && arguments[0].signal[i] >= 0) {
+ zcr++;
+ }
+ }
+
+ return zcr;
+});
+
+/***/ }),
+
+/***/ "./src/featureExtractors.js":
+/*!**********************************!*\
+ !*** ./src/featureExtractors.js ***!
+ \**********************************/
+/*! exports provided: buffer, rms, energy, complexSpectrum, spectralSlope, spectralCentroid, spectralRolloff, spectralFlatness, spectralSpread, spectralSkewness, spectralKurtosis, amplitudeSpectrum, zcr, loudness, perceptualSpread, perceptualSharpness, powerSpectrum, mfcc, chroma, spectralFlux */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return buffer; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "complexSpectrum", function() { return complexSpectrum; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amplitudeSpectrum", function() { return amplitudeSpectrum; });
+/* harmony import */ var _extractors_rms__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractors/rms */ "./src/extractors/rms.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rms", function() { return _extractors_rms__WEBPACK_IMPORTED_MODULE_0__["default"]; });
+
+/* harmony import */ var _extractors_energy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./extractors/energy */ "./src/extractors/energy.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "energy", function() { return _extractors_energy__WEBPACK_IMPORTED_MODULE_1__["default"]; });
+
+/* harmony import */ var _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./extractors/spectralSlope */ "./src/extractors/spectralSlope.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSlope", function() { return _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__["default"]; });
+
+/* harmony import */ var _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./extractors/spectralCentroid */ "./src/extractors/spectralCentroid.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralCentroid", function() { return _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__["default"]; });
+
+/* harmony import */ var _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./extractors/spectralRolloff */ "./src/extractors/spectralRolloff.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralRolloff", function() { return _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__["default"]; });
+
+/* harmony import */ var _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./extractors/spectralFlatness */ "./src/extractors/spectralFlatness.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralFlatness", function() { return _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__["default"]; });
-var shift = {
- 48: ")",
- 49: "!",
- 50: "@",
- 51: "#",
- 52: "$",
- 53: "%",
- 54: "^",
- 55: "&",
- 56: "*",
- 57: "(",
- 59: ":",
- 61: "+",
- 173: "_",
- 186: ":",
- 187: "+",
- 188: "<",
- 189: "_",
- 190: ">",
- 191: "?",
- 192: "~",
- 219: "{",
- 220: "|",
- 221: "}",
- 222: "\"",
- 229: "Q"
-};
+/* harmony import */ var _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./extractors/spectralSpread */ "./src/extractors/spectralSpread.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSpread", function() { return _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__["default"]; });
-var chrome = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
-var safari = typeof navigator != "undefined" && /Apple Computer/.test(navigator.vendor);
-var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
-var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
-var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
-var brokenModifierNames = chrome && (mac || +chrome[1] < 57) || gecko && mac;
+/* harmony import */ var _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./extractors/spectralSkewness */ "./src/extractors/spectralSkewness.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSkewness", function() { return _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__["default"]; });
-// Fill in the digit keys
-for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
+/* harmony import */ var _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./extractors/spectralKurtosis */ "./src/extractors/spectralKurtosis.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralKurtosis", function() { return _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__["default"]; });
-// The function keys
-for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
+/* harmony import */ var _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./extractors/zcr */ "./src/extractors/zcr.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zcr", function() { return _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__["default"]; });
-// And the alphabetic keys
-for (var i = 65; i <= 90; i++) {
- base[i] = String.fromCharCode(i + 32);
- shift[i] = String.fromCharCode(i);
-}
+/* harmony import */ var _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./extractors/loudness */ "./src/extractors/loudness.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "loudness", function() { return _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__["default"]; });
-// For each code that doesn't have a shift-equivalent, copy the base name
-for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
+/* harmony import */ var _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./extractors/perceptualSpread */ "./src/extractors/perceptualSpread.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "perceptualSpread", function() { return _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__["default"]; });
-function keyName(event) {
- // Don't trust event.key in Chrome when there are modifiers until
- // they fix https://bugs.chromium.org/p/chromium/issues/detail?id=633838
- var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) ||
- (safari || ie) && event.shiftKey && event.key && event.key.length == 1;
- var name = (!ignoreKey && event.key) ||
- (event.shiftKey ? shift : base)[event.keyCode] ||
- event.key || "Unidentified";
- // Edge sometimes produces wrong names (Issue #3)
- if (name == "Esc") name = "Escape";
- if (name == "Del") name = "Delete";
- // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
- if (name == "Left") name = "ArrowLeft";
- if (name == "Up") name = "ArrowUp";
- if (name == "Right") name = "ArrowRight";
- if (name == "Down") name = "ArrowDown";
- return name
-}
+/* harmony import */ var _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./extractors/perceptualSharpness */ "./src/extractors/perceptualSharpness.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "perceptualSharpness", function() { return _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__["default"]; });
-exports.base = base;
-exports.keyName = keyName;
-exports.shift = shift;
+/* harmony import */ var _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./extractors/mfcc */ "./src/extractors/mfcc.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mfcc", function() { return _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__["default"]; });
-},{}],122:[function(require,module,exports){
-/* eslint-disable node/no-deprecated-api */
-var assert = require('assert')
+/* harmony import */ var _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./extractors/chroma */ "./src/extractors/chroma.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "chroma", function() { return _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__["default"]; });
-module.exports = getAllRoutes
+/* harmony import */ var _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./extractors/powerSpectrum */ "./src/extractors/powerSpectrum.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "powerSpectrum", function() { return _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__["default"]; });
-var transform = function (trie, previous) {
- var prev = previous || '/'
- var routes = {}
- var nodes = trie.nodes
- Object.keys(nodes).forEach(function (key) {
- var path = (prev === '/' ? prev : prev + '/') + (key === '$$' ? ':' + trie.name : key)
- var cb = nodes[key].cb
- if (cb !== undefined) {
- routes[path] = cb
- }
- if (Object.keys(nodes[key].nodes).length !== 0) {
- var obj = transform(nodes[key], path)
- Object.keys(obj).forEach(function (r) {
- routes[r] = obj[r]
- })
- }
- })
- return routes
-}
+/* harmony import */ var _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./extractors/spectralFlux */ "./src/extractors/spectralFlux.js");
+/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralFlux", function() { return _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__["default"]; });
-// walk a wayfarer trie
-// (obj, fn) -> null
-function getAllRoutes (router) {
- assert.equal(typeof router, 'function', 'wayfarer.getAllRoutes: router should be an function')
- var trie = router._trie
- assert.equal(typeof trie, 'object', 'wayfarer.getAllRoutes: trie should be an object')
- var tree = trie.trie
- return transform(tree)
-}
-},{"assert":85}],123:[function(require,module,exports){
-/* eslint-disable node/no-deprecated-api */
-var assert = require('assert')
-var trie = require('./trie')
-module.exports = Wayfarer
-// create a router
-// str -> obj
-function Wayfarer (dft) {
- if (!(this instanceof Wayfarer)) return new Wayfarer(dft)
- var _default = (dft || '').replace(/^\//, '')
- var _trie = trie()
- emit._trie = _trie
- emit.on = on
- emit.emit = emit
- emit.match = match
- emit._wayfarer = true
- return emit
- // define a route
- // (str, fn) -> obj
- function on (route, cb) {
- assert.equal(typeof route, 'string')
- assert.equal(typeof cb, 'function')
- route = route || '/'
- if (cb._wayfarer && cb._trie) {
- _trie.mount(route, cb._trie.trie)
- } else {
- var node = _trie.create(route)
- node.cb = cb
- node.route = route
- }
- return emit
- }
- // match and call a route
- // (str, obj?) -> null
- function emit (route) {
- var matched = match(route)
- var args = new Array(arguments.length)
- args[0] = matched.params
- for (var i = 1; i < args.length; i++) {
- args[i] = arguments[i]
- }
- return matched.cb.apply(matched.cb, args)
- }
- function match (route) {
- assert.notEqual(route, undefined, "'route' must be defined")
- var matched = _trie.match(route)
- if (matched && matched.cb) return new Route(matched)
- var dft = _trie.match(_default)
- if (dft && dft.cb) return new Route(dft)
+var buffer = function buffer(args) {
+ return args.signal;
+};
- throw new Error("route '" + route + "' did not match")
- }
+var complexSpectrum = function complexSpectrum(args) {
+ return args.complexSpectrum;
+};
- function Route (matched) {
- this.cb = matched.cb
- this.route = matched.route
- this.params = matched.params
- }
-}
+var amplitudeSpectrum = function amplitudeSpectrum(args) {
+ return args.ampSpectrum;
+};
-},{"./trie":124,"assert":85}],124:[function(require,module,exports){
-/* eslint-disable node/no-deprecated-api */
-var assert = require('assert')
-module.exports = Trie
-// create a new trie
-// null -> obj
-function Trie () {
- if (!(this instanceof Trie)) return new Trie()
- this.trie = { nodes: {} }
-}
+/***/ }),
-// create a node on the trie at route
-// and return a node
-// str -> obj
-Trie.prototype.create = function (route) {
- assert.equal(typeof route, 'string', 'route should be a string')
- // strip leading '/' and split routes
- var routes = route.replace(/^\//, '').split('/')
+/***/ "./src/index.js":
+/*!**********************!*\
+ !*** ./src/index.js ***!
+ \**********************/
+/*! no static exports found */
+/***/ (function(module, exports, __webpack_require__) {
- function createNode (index, trie) {
- var thisRoute = (has(routes, index) && routes[index])
- if (thisRoute === false) return trie
+module.exports = __webpack_require__(/*! ./main */ "./src/main.js")["default"];
- var node = null
- if (/^:|^\*/.test(thisRoute)) {
- // if node is a name match, set name and append to ':' node
- if (!has(trie.nodes, '$$')) {
- node = { nodes: {} }
- trie.nodes.$$ = node
- } else {
- node = trie.nodes.$$
- }
+/***/ }),
- if (thisRoute[0] === '*') {
- trie.wildcard = true
- }
+/***/ "./src/main.js":
+/*!*********************!*\
+ !*** ./src/main.js ***!
+ \*********************/
+/*! exports provided: default */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
- trie.name = thisRoute.replace(/^:|^\*/, '')
- } else if (!has(trie.nodes, thisRoute)) {
- node = { nodes: {} }
- trie.nodes[thisRoute] = node
- } else {
- node = trie.nodes[thisRoute]
- }
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utilities */ "./src/utilities.js");
+/* harmony import */ var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./featureExtractors */ "./src/featureExtractors.js");
+/* harmony import */ var fftjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! fftjs */ "./node_modules/fftjs/dist/fft.js");
+/* harmony import */ var fftjs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fftjs__WEBPACK_IMPORTED_MODULE_2__);
+/* harmony import */ var _meyda_wa__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./meyda-wa */ "./src/meyda-wa.js");
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- // we must recurse deeper
- return createNode(index + 1, node)
- }
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- return createNode(0, this.trie)
-}
-// match a route on the trie
-// and return the node
-// str -> obj
-Trie.prototype.match = function (route) {
- assert.equal(typeof route, 'string', 'route should be a string')
- var routes = route.replace(/^\//, '').split('/')
- var params = {}
- function search (index, trie) {
- // either there's no match, or we're done searching
- if (trie === undefined) return undefined
- var thisRoute = routes[index]
- if (thisRoute === undefined) return trie
- if (has(trie.nodes, thisRoute)) {
- // match regular routes first
- return search(index + 1, trie.nodes[thisRoute])
- } else if (trie.name) {
- // match named routes
- try {
- params[trie.name] = decodeURIComponent(thisRoute)
- } catch (e) {
- return search(index, undefined)
- }
- return search(index + 1, trie.nodes.$$)
- } else if (trie.wildcard) {
- // match wildcards
- try {
- params.wildcard = decodeURIComponent(routes.slice(index).join('/'))
- } catch (e) {
- return search(index, undefined)
- }
- // return early, or else search may keep recursing through the wildcard
- return trie.nodes.$$
- } else {
- // no matches found
- return search(index + 1)
- }
- }
+/**
+ * Meyda Module
+ * @module meyda
+ */
- var node = search(0, this.trie)
+/**
+ * Options for constructing a MeydaAnalyzer
+ * @typedef {Object} MeydaOptions
+ * @property {AudioContext} audioContext - The Audio Context for the MeydaAnalyzer to operate in.
+ * @property {AudioNode} source - The Audio Node for Meyda to listen to.
+ * @property {number} [bufferSize] - The size of the buffer.
+ * @property {number} [hopSize] - The hop size between buffers.
+ * @property {number} [sampleRate] - The number of samples per second in the audio context.
+ * @property {Function} [callback] - A function to receive the frames of audio features
+ * @property {string} [windowingFunction] - The Windowing Function to apply to the signal before transformation to the frequency domain
+ * @property {string|Array.} [featureExtractors] - Specify the feature extractors you want to run on the audio.
+ * @property {boolean} [startImmediately] - Pass `true` to start feature extraction immediately
+ * @property {number} [numberOfMFCCCoefficients] - The number of MFCC co-efficients that the MFCC feature extractor should return
+ */
- if (!node) return undefined
- node = Object.assign({}, node)
- node.params = params
- return node
-}
+/**
+ * Web Audio context
+ * Either an {@link AudioContext|https://developer.mozilla.org/en-US/docs/Web/API/AudioContext}
+ * or an {@link OfflineAudioContext|https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext}
+ * @typedef {Object} AudioContext
+ */
-// mount a trie onto a node at route
-// (str, obj) -> null
-Trie.prototype.mount = function (route, trie) {
- assert.equal(typeof route, 'string', 'route should be a string')
- assert.equal(typeof trie, 'object', 'trie should be a object')
+/**
+ * AudioNode
+ * A Web AudioNode
+ * @typedef {Object} AudioNode
+ */
- var split = route.replace(/^\//, '').split('/')
- var node = null
- var key = null
+/**
+ * ScriptProcessorNode
+ * A Web Audio ScriptProcessorNode
+ * @typedef {Object} ScriptProcessorNode
+ */
- if (split.length === 1) {
- key = split[0]
- node = this.create(key)
- } else {
- var head = split.join('/')
- key = split[0]
- node = this.create(head)
- }
+/**
+ * @class Meyda
+ * @hideconstructor
+ * @classdesc
+ * The schema for the default export of the Meyda library.
+ * @example
+ * var Meyda = require('meyda');
+ */
- Object.assign(node.nodes, trie.nodes)
- if (trie.name) node.name = trie.name
+var Meyda = {
+ /**
+ * Meyda stores a reference to the relevant audio context here for use inside
+ * the Web Audio API.
+ * @instance
+ * @member {AudioContext}
+ */
+ audioContext: null,
- // delegate properties from '/' to the new node
- // '/' cannot be reached once mounted
- if (node.nodes['']) {
- Object.keys(node.nodes['']).forEach(function (key) {
- if (key === 'nodes') return
- node[key] = node.nodes[''][key]
- })
- Object.assign(node.nodes, node.nodes[''].nodes)
- delete node.nodes[''].nodes
- }
-}
+ /**
+ * Meyda keeps an internal ScriptProcessorNode in which it runs audio feature
+ * extraction. The ScriptProcessorNode is stored in this member variable.
+ * @instance
+ * @member {ScriptProcessorNode}
+ */
+ spn: null,
-function has (object, property) {
- return Object.prototype.hasOwnProperty.call(object, property)
-}
+ /**
+ * The length of each buffer that Meyda will extract audio on. When recieving
+ * input via the Web Audio API, the Script Processor Node chunks incoming audio
+ * into arrays of this length. Longer buffers allow for more precision in the
+ * frequency domain, but increase the amount of time it takes for Meyda to
+ * output a set of audio features for the buffer. You can calculate how many
+ * sets of audio features Meyda will output per second by dividing the
+ * buffer size by the sample rate. If you're using Meyda for visualisation,
+ * make sure that you're collecting audio features at a rate that's faster
+ * than or equal to the video frame rate you expect.
+ * @instance
+ * @member {number}
+ */
+ bufferSize: 512,
+
+ /**
+ * The number of samples per second of the incoming audio. This affects
+ * feature extraction outside of the context of the Web Audio API, and must be
+ * set accurately - otherwise calculations will be off.
+ * @instance
+ * @member {number}
+ */
+ sampleRate: 44100,
+
+ /**
+ * The number of Mel bands to use in the Mel Frequency Cepstral Co-efficients
+ * feature extractor
+ * @instance
+ * @member {number}
+ */
+ melBands: 26,
+
+ /**
+ * The number of bands to divide the spectrum into for the Chroma feature
+ * extractor. 12 is the standard number of semitones per octave in the western
+ * music tradition, but Meyda can use an arbitrary number of bands, which
+ * can be useful for microtonal music.
+ * @instance
+ * @member {number}
+ */
+ chromaBands: 12,
+
+ /**
+ * A function you can provide that will be called for each buffer that Meyda
+ * receives from its source node
+ * @instance
+ * @member {Function}
+ */
+ callback: null,
+
+ /**
+ * Specify the windowing function to apply to the buffer before the
+ * transformation from the time domain to the frequency domain is performed
+ *
+ * The default windowing function is the hanning window.
+ *
+ * @instance
+ * @member {string}
+ */
+ windowingFunction: 'hanning',
+
+ /**
+ * @member {object}
+ */
+ featureExtractors: _featureExtractors__WEBPACK_IMPORTED_MODULE_1__,
+ EXTRACTION_STARTED: false,
+
+ /**
+ * The number of MFCC co-efficients that the MFCC feature extractor should return
+ * @instance
+ * @member {number}
+ */
+ numberOfMFCCCoefficients: 13,
+ _featuresToExtract: [],
+ windowing: _utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"],
+ _errors: {
+ notPow2: new Error('Meyda: Buffer size must be a power of 2, e.g. 64 or 512'),
+ featureUndef: new Error('Meyda: No features defined.'),
+ invalidFeatureFmt: new Error('Meyda: Invalid feature format'),
+ invalidInput: new Error('Meyda: Invalid input.'),
+ noAC: new Error('Meyda: No AudioContext specified.'),
+ noSource: new Error('Meyda: No source node specified.')
+ },
+
+ /**
+ * @summary
+ * Create a MeydaAnalyzer
+ *
+ * A factory function for creating a MeydaAnalyzer, the interface for using
+ * Meyda in the context of Web Audio.
+ *
+ * @method
+ * @param {MeydaOptions} options Options - an object containing configuration
+ * @returns {MeydaAnalyzer}
+ * @example
+ * const analyzer = Meyda.createMeydaAnalyzer({
+ * "audioContext": audioContext,
+ * "source": source,
+ * "bufferSize": 512,
+ * "featureExtractors": ["rms"],
+ * "inputs": 2,
+ * "callback": features => {
+ * levelRangeElement.value = features.rms;
+ * }
+ * });
+ */
+ createMeydaAnalyzer: function createMeydaAnalyzer(options) {
+ return new _meyda_wa__WEBPACK_IMPORTED_MODULE_3__["MeydaAnalyzer"](options, Object.assign({}, Meyda));
+ },
+
+ /**
+ * Extract an audio feature from a buffer
+ *
+ * Unless `meyda.windowingFunction` is set otherwise, `extract` will
+ * internally apply a hanning window to the buffer prior to conversion into
+ * the frequency domain.
+ *
+ * @function
+ * @param {(string|Array.)} feature - the feature you want to extract
+ * @param {Array.} signal
+ * An array of numbers that represents the signal. It should be of length
+ * `meyda.bufferSize`
+ * @param {Array.} [previousSignal] - the previous buffer
+ * @returns {object} Features
+ * @example
+ * meyda.bufferSize = 2048;
+ * const features = meyda.extract(['zcr', 'spectralCentroid'], signal);
+ */
+ extract: function extract(feature, signal, previousSignal) {
+ var _this = this;
-},{"assert":85}],125:[function(require,module,exports){
-(function (global){
-'use strict';
+ if (!signal) throw this._errors.invalidInput;else if (_typeof(signal) != 'object') throw this._errors.invalidInput;else if (!feature) throw this._errors.featureUndef;else if (!_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](signal.length)) throw this._errors.notPow2;
-var objectAssign = require('object-assign');
+ if (typeof this.barkScale == 'undefined' || this.barkScale.length != this.bufferSize) {
+ this.barkScale = _utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this.bufferSize, this.sampleRate, this.bufferSize);
+ } // Recalculate mel bank if buffer length changed
-// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
-// original notice:
-/*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-function compare(a, b) {
- if (a === b) {
- return 0;
- }
+ if (typeof this.melFilterBank == 'undefined' || this.barkScale.length != this.bufferSize || this.melFilterBank.length != this.melBands) {
+ this.melFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this.melBands, this.numberOfMFCCCoefficients), this.sampleRate, this.bufferSize);
+ } // Recalculate chroma bank if buffer length changed
- var x = a.length;
- var y = b.length;
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i];
- y = b[i];
- break;
+ if (typeof this.chromaFilterBank == 'undefined' || this.chromaFilterBank.length != this.chromaBands) {
+ this.chromaFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createChromaFilterBank"](this.chromaBands, this.sampleRate, this.bufferSize);
}
- }
-
- if (x < y) {
- return -1;
- }
- if (y < x) {
- return 1;
- }
- return 0;
-}
-function isBuffer(b) {
- if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
- return global.Buffer.isBuffer(b);
- }
- return !!(b != null && b._isBuffer);
-}
-
-// based on node assert, original notice:
-// NB: The URL to the CommonJS spec is kept just for tradition.
-// node-assert has evolved a lot since then, both in API and behavior.
-
-// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
-//
-// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
-//
-// Originally from narwhal.js (http://narwhaljs.org)
-// Copyright (c) 2009 Thomas Robinson <280north.com>
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the 'Software'), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-var util = require('util/');
-var hasOwn = Object.prototype.hasOwnProperty;
-var pSlice = Array.prototype.slice;
-var functionsHaveNames = (function () {
- return function foo() {}.name === 'foo';
-}());
-function pToString (obj) {
- return Object.prototype.toString.call(obj);
-}
-function isView(arrbuf) {
- if (isBuffer(arrbuf)) {
- return false;
- }
- if (typeof global.ArrayBuffer !== 'function') {
- return false;
- }
- if (typeof ArrayBuffer.isView === 'function') {
- return ArrayBuffer.isView(arrbuf);
- }
- if (!arrbuf) {
- return false;
- }
- if (arrbuf instanceof DataView) {
- return true;
- }
- if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
- return true;
- }
- return false;
-}
-// 1. The assert module provides functions that throw
-// AssertionError's when particular conditions are not met. The
-// assert module must conform to the following interface.
+ if (typeof signal.buffer == 'undefined') {
+ //signal is a normal array, convert to F32A
+ this.signal = _utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal);
+ } else {
+ this.signal = signal;
+ }
-var assert = module.exports = ok;
+ var preparedSignal = prepareSignalWithSpectrum(signal, this.windowingFunction, this.bufferSize);
+ this.signal = preparedSignal.windowedSignal;
+ this.complexSpectrum = preparedSignal.complexSpectrum;
+ this.ampSpectrum = preparedSignal.ampSpectrum;
-// 2. The AssertionError is defined in assert.
-// new assert.AssertionError({ message: message,
-// actual: actual,
-// expected: expected })
+ if (previousSignal) {
+ var _preparedSignal = prepareSignalWithSpectrum(previousSignal, this.windowingFunction, this.bufferSize);
-var regex = /\s*function\s+([^\(\s]*)\s*/;
-// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
-function getName(func) {
- if (!util.isFunction(func)) {
- return;
- }
- if (functionsHaveNames) {
- return func.name;
- }
- var str = func.toString();
- var match = str.match(regex);
- return match && match[1];
-}
-assert.AssertionError = function AssertionError(options) {
- this.name = 'AssertionError';
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- if (options.message) {
- this.message = options.message;
- this.generatedMessage = false;
- } else {
- this.message = getMessage(this);
- this.generatedMessage = true;
- }
- var stackStartFunction = options.stackStartFunction || fail;
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- } else {
- // non v8 browsers so we can have a stacktrace
- var err = new Error();
- if (err.stack) {
- var out = err.stack;
+ this.previousSignal = _preparedSignal.windowedSignal;
+ this.previousComplexSpectrum = _preparedSignal.complexSpectrum;
+ this.previousAmpSpectrum = _preparedSignal.ampSpectrum;
+ }
- // try to strip useless frames
- var fn_name = getName(stackStartFunction);
- var idx = out.indexOf('\n' + fn_name);
- if (idx >= 0) {
- // once we have located the function frame
- // we need to strip out everything before it (and its line)
- var next_line = out.indexOf('\n', idx + 1);
- out = out.substring(next_line + 1);
- }
+ var extract = function extract(feature) {
+ return _this.featureExtractors[feature]({
+ ampSpectrum: _this.ampSpectrum,
+ chromaFilterBank: _this.chromaFilterBank,
+ complexSpectrum: _this.complexSpectrum,
+ signal: _this.signal,
+ bufferSize: _this.bufferSize,
+ sampleRate: _this.sampleRate,
+ barkScale: _this.barkScale,
+ melFilterBank: _this.melFilterBank,
+ previousSignal: _this.previousSignal,
+ previousAmpSpectrum: _this.previousAmpSpectrum,
+ previousComplexSpectrum: _this.previousComplexSpectrum,
+ numberOfMFCCCoefficients: _this.numberOfMFCCCoefficients
+ });
+ };
- this.stack = out;
+ if (_typeof(feature) === 'object') {
+ return feature.reduce(function (acc, el) {
+ return Object.assign({}, acc, _defineProperty({}, el, extract(el)));
+ }, {});
+ } else if (typeof feature === 'string') {
+ return extract(feature);
+ } else {
+ throw this._errors.invalidFeatureFmt;
}
}
};
-// assert.AssertionError instanceof Error
-util.inherits(assert.AssertionError, Error);
+var prepareSignalWithSpectrum = function prepareSignalWithSpectrum(signal, windowingFunction, bufferSize) {
+ var preparedSignal = {};
-function truncate(s, n) {
- if (typeof s === 'string') {
- return s.length < n ? s : s.slice(0, n);
+ if (typeof signal.buffer == 'undefined') {
+ //signal is a normal array, convert to F32A
+ preparedSignal.signal = _utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal);
} else {
- return s;
- }
-}
-function inspect(something) {
- if (functionsHaveNames || !util.isFunction(something)) {
- return util.inspect(something);
+ preparedSignal.signal = signal;
}
- var rawname = getName(something);
- var name = rawname ? ': ' + rawname : '';
- return '[Function' + name + ']';
-}
-function getMessage(self) {
- return truncate(inspect(self.actual), 128) + ' ' +
- self.operator + ' ' +
- truncate(inspect(self.expected), 128);
-}
-// At present only the three keys mentioned above are used and
-// understood by the spec. Implementations or sub modules can pass
-// other keys to the AssertionError's constructor - they will be
-// ignored.
+ preparedSignal.windowedSignal = _utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"](preparedSignal.signal, windowingFunction);
+ preparedSignal.complexSpectrum = Object(fftjs__WEBPACK_IMPORTED_MODULE_2__["fft"])(preparedSignal.windowedSignal);
+ preparedSignal.ampSpectrum = new Float32Array(bufferSize / 2);
-// 3. All of the following functions must throw an AssertionError
-// when a corresponding condition is not met, with a message that
-// may be undefined if not provided. All assertion methods provide
-// both the actual and expected values to the assertion error for
-// display purposes.
+ for (var i = 0; i < bufferSize / 2; i++) {
+ preparedSignal.ampSpectrum[i] = Math.sqrt(Math.pow(preparedSignal.complexSpectrum.real[i], 2) + Math.pow(preparedSignal.complexSpectrum.imag[i], 2));
+ }
-function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
-}
+ return preparedSignal;
+};
+/**
+ * The Meyda class
+ * @type {Meyda}
+ */
-// EXTENSION! allows for well behaved errors defined elsewhere.
-assert.fail = fail;
-// 4. Pure assertion tests whether a value is truthy, as determined
-// by !!guard.
-// assert.ok(guard, message_opt);
-// This statement is equivalent to assert.equal(true, !!guard,
-// message_opt);. To test strictly for the value true, use
-// assert.strictEqual(true, guard, message_opt);.
+/* harmony default export */ __webpack_exports__["default"] = (Meyda);
+if (typeof window !== 'undefined') window.Meyda = Meyda;
-function ok(value, message) {
- if (!value) fail(value, true, message, '==', assert.ok);
-}
-assert.ok = ok;
+/***/ }),
-// 5. The equality assertion tests shallow, coercive equality with
-// ==.
-// assert.equal(actual, expected, message_opt);
+/***/ "./src/meyda-wa.js":
+/*!*************************!*\
+ !*** ./src/meyda-wa.js ***!
+ \*************************/
+/*! exports provided: MeydaAnalyzer */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
-assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
-};
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeydaAnalyzer", function() { return MeydaAnalyzer; });
+/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utilities */ "./src/utilities.js");
+/* harmony import */ var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./featureExtractors */ "./src/featureExtractors.js");
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-// 6. The non-equality assertion tests for whether two objects are not equal
-// with != assert.notEqual(actual, expected, message_opt);
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, '!=', assert.notEqual);
- }
-};
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
-// 7. The equivalence assertion tests a deep equality relation.
-// assert.deepEqual(actual, expected, message_opt);
-assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
- }
-};
-assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
- }
-};
+/**
+ * MeydaAnalyzer
+ * @classdesc
+ * Meyda's interface to the Web Audio API. MeydaAnalyzer abstracts an API on
+ * top of the Web Audio API's ScriptProcessorNode, running the Meyda audio
+ * feature extractors inside that context.
+ *
+ * MeydaAnalyzer's constructor should not be called directly - MeydaAnalyzer
+ * objects should be generated using the {@link Meyda.createMeydaAnalyzer}
+ * factory function in the main Meyda class.
+ *
+ * @example
+ * const analyzer = Meyda.createMeydaAnalyzer({
+ * "audioContext": audioContext,
+ * "source": source,
+ * "bufferSize": 512,
+ * "featureExtractors": ["rms"],
+ * "inputs": 2,
+ * "numberOfMFCCCoefficients": 20
+ * "callback": features => {
+ * levelRangeElement.value = features.rms;
+ * }
+ * });
+ * @hideconstructor
+ */
-function _deepEqual(actual, expected, strict, memos) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
- } else if (isBuffer(actual) && isBuffer(expected)) {
- return compare(actual, expected) === 0;
+var MeydaAnalyzer =
+/*#__PURE__*/
+function () {
+ function MeydaAnalyzer(options, _this) {
+ var _this2 = this;
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (util.isDate(actual) && util.isDate(expected)) {
- return actual.getTime() === expected.getTime();
+ _classCallCheck(this, MeydaAnalyzer);
- // 7.3 If the expected value is a RegExp object, the actual value is
- // equivalent if it is also a RegExp object with the same source and
- // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
- } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
- return actual.source === expected.source &&
- actual.global === expected.global &&
- actual.multiline === expected.multiline &&
- actual.lastIndex === expected.lastIndex &&
- actual.ignoreCase === expected.ignoreCase;
+ this._m = _this;
- // 7.4. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if ((actual === null || typeof actual !== 'object') &&
- (expected === null || typeof expected !== 'object')) {
- return strict ? actual === expected : actual == expected;
+ if (!options.audioContext) {
+ throw this._m.errors.noAC;
+ } else if (options.bufferSize && !_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](options.bufferSize)) {
+ throw this._m._errors.notPow2;
+ } else if (!options.source) {
+ throw this._m._errors.noSource;
+ }
- // If both values are instances of typed arrays, wrap their underlying
- // ArrayBuffers in a Buffer each to increase performance
- // This optimization requires the arrays to have the same type as checked by
- // Object.prototype.toString (aka pToString). Never perform binary
- // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
- // bit patterns are not identical.
- } else if (isView(actual) && isView(expected) &&
- pToString(actual) === pToString(expected) &&
- !(actual instanceof Float32Array ||
- actual instanceof Float64Array)) {
- return compare(new Uint8Array(actual.buffer),
- new Uint8Array(expected.buffer)) === 0;
+ this._m.audioContext = options.audioContext; // TODO: validate options
- // 7.5 For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else if (isBuffer(actual) !== isBuffer(expected)) {
- return false;
- } else {
- memos = memos || {actual: [], expected: []};
+ this._m.bufferSize = options.bufferSize || this._m.bufferSize || 256;
+ this._m.hopSize = options.hopSize || this._m.hopSize || this._m.bufferSize;
+ this._m.sampleRate = options.sampleRate || this._m.audioContext.sampleRate || 44100;
+ this._m.callback = options.callback;
+ this._m.windowingFunction = options.windowingFunction || 'hanning';
+ this._m.featureExtractors = _featureExtractors__WEBPACK_IMPORTED_MODULE_1__;
+ this._m.EXTRACTION_STARTED = options.startImmediately || false;
+ this._m.channel = typeof options.channel === 'number' ? options.channel : 0;
+ this._m.inputs = options.inputs || 1;
+ this._m.outputs = options.outputs || 1;
+ this._m.numberOfMFCCCoefficients = options.numberOfMFCCCoefficients || this._m.numberOfMFCCCoefficients || 13; //create nodes
- var actualIndex = memos.actual.indexOf(actual);
- if (actualIndex !== -1) {
- if (actualIndex === memos.expected.indexOf(expected)) {
- return true;
- }
- }
+ this._m.spn = this._m.audioContext.createScriptProcessor(this._m.bufferSize, this._m.inputs, this._m.outputs);
- memos.actual.push(actual);
- memos.expected.push(expected);
+ this._m.spn.connect(this._m.audioContext.destination);
- return objEquiv(actual, expected, strict, memos);
- }
-}
+ this._m._featuresToExtract = options.featureExtractors || []; //always recalculate BS and MFB when a new Meyda analyzer is created.
-function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
-}
+ this._m.barkScale = _utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this._m.bufferSize, this._m.sampleRate, this._m.bufferSize);
+ this._m.melFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this._m.melBands, this._m.numberOfMFCCCoefficients), this._m.sampleRate, this._m.bufferSize);
+ this._m.inputData = null;
+ this._m.previousInputData = null;
+ this._m.frame = null;
+ this._m.previousFrame = null;
+ this.setSource(options.source);
-function objEquiv(a, b, strict, actualVisitedObjects) {
- if (a === null || a === undefined || b === null || b === undefined)
- return false;
- // if one is a primitive, the other must be same
- if (util.isPrimitive(a) || util.isPrimitive(b))
- return a === b;
- if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
- return false;
- var aIsArgs = isArguments(a);
- var bIsArgs = isArguments(b);
- if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
- return false;
- if (aIsArgs) {
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b, strict);
- }
- var ka = objectKeys(a);
- var kb = objectKeys(b);
- var key, i;
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length !== kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] !== kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
- return false;
- }
- return true;
-}
+ this._m.spn.onaudioprocess = function (e) {
+ if (_this2._m.inputData !== null) {
+ _this2._m.previousInputData = _this2._m.inputData;
+ }
-// 8. The non-equivalence assertion tests for any deep inequality.
-// assert.notDeepEqual(actual, expected, message_opt);
+ _this2._m.inputData = e.inputBuffer.getChannelData(_this2._m.channel);
-assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
- }
-};
+ if (!_this2._m.previousInputData) {
+ var buffer = _this2._m.inputData;
+ } else {
+ var buffer = new Float32Array(_this2._m.previousInputData.length + _this2._m.inputData.length - _this2._m.hopSize);
+ buffer.set(_this2._m.previousInputData.slice(_this2._m.hopSize));
+ buffer.set(_this2._m.inputData, _this2._m.previousInputData.length - _this2._m.hopSize);
+ }
-assert.notDeepStrictEqual = notDeepStrictEqual;
-function notDeepStrictEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
- }
-}
+ ;
+ var frames = _utilities__WEBPACK_IMPORTED_MODULE_0__["frame"](buffer, _this2._m.bufferSize, _this2._m.hopSize);
+ frames.forEach(function (f) {
+ _this2._m.frame = f;
+ var features = _this2._m.extract(_this2._m._featuresToExtract, _this2._m.frame, _this2._m.previousFrame); // call callback if applicable
-// 9. The strict equality assertion tests strict equality, as determined by ===.
-// assert.strictEqual(actual, expected, message_opt);
-assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, '===', assert.strictEqual);
+ if (typeof _this2._m.callback === 'function' && _this2._m.EXTRACTION_STARTED) {
+ _this2._m.callback(features);
+ }
+
+ _this2._m.previousFrame = _this2._m.frame;
+ });
+ };
}
-};
+ /**
+ * Start feature extraction
+ * The audio features will be passed to the callback function that was defined
+ * in the MeydaOptions that were passed to the factory when constructing the
+ * MeydaAnalyzer.
+ * @param {(string|Array.)} [features]
+ * Change the features that Meyda is extracting. Defaults to the features that
+ * were set upon construction in the options parameter.
+ * @example
+ * analyzer.start('chroma');
+ */
-// 10. The strict non-equality assertion tests for strict inequality, as
-// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
-assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, '!==', assert.notStrictEqual);
- }
-};
+ _createClass(MeydaAnalyzer, [{
+ key: "start",
+ value: function start(features) {
+ this._m._featuresToExtract = features || this._m._featuresToExtract;
+ this._m.EXTRACTION_STARTED = true;
+ }
+ /**
+ * Stop feature extraction.
+ * @example
+ * analyzer.stop();
+ */
-function expectedException(actual, expected) {
- if (!actual || !expected) {
- return false;
- }
+ }, {
+ key: "stop",
+ value: function stop() {
+ this._m.EXTRACTION_STARTED = false;
+ }
+ /**
+ * Set the Audio Node for Meyda to listen to.
+ * @param {AudioNode} source - The Audio Node for Meyda to listen to
+ * @example
+ * analyzer.setSource(audioSourceNode);
+ */
- if (Object.prototype.toString.call(expected) == '[object RegExp]') {
- return expected.test(actual);
- }
+ }, {
+ key: "setSource",
+ value: function setSource(source) {
+ this._m.source && this._m.source.disconnect(this._m.spn);
+ this._m.source = source;
- try {
- if (actual instanceof expected) {
- return true;
+ this._m.source.connect(this._m.spn);
}
- } catch (e) {
- // Ignore. The instanceof check doesn't work for arrow functions.
- }
+ /**
+ * Set the channel of the audio node for Meyda to listen to
+ * @param {number} channel - the index of the channel on the input audio node
+ * for Meyda to listen to.
+ * @example
+ * analyzer.setChannel(0);
+ */
- if (Error.isPrototypeOf(expected)) {
- return false;
- }
+ }, {
+ key: "setChannel",
+ value: function setChannel(channel) {
+ if (channel <= this._m.inputs) {
+ this._m.channel = channel;
+ } else {
+ console.error("Channel ".concat(channel, " does not exist. Make sure you've provided a value for 'inputs' that is greater than ").concat(channel, " when instantiating the MeydaAnalyzer"));
+ }
+ }
+ /**
+ * Get a set of features from the current frame.
+ * @param {(string|Array.)} [features]
+ * Change the features that Meyda is extracting
+ * @example
+ * analyzer.get('spectralFlatness');
+ */
- return expected.call({}, actual) === true;
-}
+ }, {
+ key: "get",
+ value: function get(features) {
+ if (this._m.inputData) {
+ return this._m.extract(features || this._m._featuresToExtract, this._m.inputData, this._m.previousInputData);
+ } else {
+ return null;
+ }
+ }
+ }]);
-function _tryBlock(block) {
- var error;
- try {
- block();
- } catch (e) {
- error = e;
- }
- return error;
-}
+ return MeydaAnalyzer;
+}();
-function _throws(shouldThrow, block, expected, message) {
- var actual;
+/***/ }),
- if (typeof block !== 'function') {
- throw new TypeError('"block" argument must be a function');
- }
+/***/ "./src/utilities.js":
+/*!**************************!*\
+ !*** ./src/utilities.js ***!
+ \**************************/
+/*! exports provided: isPowerOfTwo, error, pointwiseBufferMult, applyWindow, createBarkScale, typedToArray, arrayToTyped, _normalize, normalize, normalizeToOne, mean, melToFreq, freqToMel, createMelFilterBank, hzToOctaves, normalizeByColumn, createChromaFilterBank, frame */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPowerOfTwo", function() { return isPowerOfTwo; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "error", function() { return error; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pointwiseBufferMult", function() { return pointwiseBufferMult; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyWindow", function() { return applyWindow; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBarkScale", function() { return createBarkScale; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "typedToArray", function() { return typedToArray; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayToTyped", function() { return arrayToTyped; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_normalize", function() { return _normalize; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalize", function() { return normalize; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeToOne", function() { return normalizeToOne; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mean", function() { return mean; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "melToFreq", function() { return melToFreq; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "freqToMel", function() { return freqToMel; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createMelFilterBank", function() { return createMelFilterBank; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hzToOctaves", function() { return hzToOctaves; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeByColumn", function() { return normalizeByColumn; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createChromaFilterBank", function() { return createChromaFilterBank; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frame", function() { return frame; });
+/* harmony import */ var _windowing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./windowing */ "./src/windowing.js");
+function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
- actual = _tryBlock(block);
+function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
- (message ? ' ' + message : '.');
+function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
- if (shouldThrow && !actual) {
- fail(actual, expected, 'Missing expected exception' + message);
- }
+function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
- var userProvidedMessage = typeof message === 'string';
- var isUnwantedException = !shouldThrow && util.isError(actual);
- var isUnexpectedException = !shouldThrow && actual && !expected;
- if ((isUnwantedException &&
- userProvidedMessage &&
- expectedException(actual, expected)) ||
- isUnexpectedException) {
- fail(actual, expected, 'Got unwanted exception' + message);
+var windows = {};
+function isPowerOfTwo(num) {
+ while (num % 2 === 0 && num > 1) {
+ num /= 2;
}
- if ((shouldThrow && actual && expected &&
- !expectedException(actual, expected)) || (!shouldThrow && actual)) {
- throw actual;
- }
+ return num === 1;
+}
+function error(message) {
+ throw new Error('Meyda: ' + message);
}
+function pointwiseBufferMult(a, b) {
+ var c = [];
-// 11. Expected to throw an error:
-// assert.throws(block, Error_opt, message_opt);
+ for (var i = 0; i < Math.min(a.length, b.length); i++) {
+ c[i] = a[i] * b[i];
+ }
-assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws(true, block, error, message);
-};
+ return c;
+}
+function applyWindow(signal, windowname) {
+ if (windowname !== 'rect') {
+ if (windowname === '' || !windowname) windowname = 'hanning';
+ if (!windows[windowname]) windows[windowname] = {};
-// EXTENSION! This is annoying to write outside this module.
-assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws(false, block, error, message);
-};
+ if (!windows[windowname][signal.length]) {
+ try {
+ windows[windowname][signal.length] = _windowing__WEBPACK_IMPORTED_MODULE_0__[windowname](signal.length);
+ } catch (e) {
+ throw new Error('Invalid windowing function');
+ }
+ }
-assert.ifError = function(err) { if (err) throw err; };
+ signal = pointwiseBufferMult(signal, windows[windowname][signal.length]);
+ }
-// Expose a strict only variant of assert
-function strict(value, message) {
- if (!value) fail(value, true, message, '==', strict);
+ return signal;
}
-assert.strict = objectAssign(strict, assert, {
- equal: assert.strictEqual,
- deepEqual: assert.deepStrictEqual,
- notEqual: assert.notStrictEqual,
- notDeepEqual: assert.notDeepStrictEqual
-});
-assert.strict.strict = assert.strict;
+function createBarkScale(length, sampleRate, bufferSize) {
+ var barkScale = new Float32Array(length);
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- if (hasOwn.call(obj, key)) keys.push(key);
+ for (var i = 0; i < barkScale.length; i++) {
+ barkScale[i] = i * sampleRate / bufferSize;
+ barkScale[i] = 13 * Math.atan(barkScale[i] / 1315.8) + 3.5 * Math.atan(Math.pow(barkScale[i] / 7518, 2));
}
- return keys;
-};
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"object-assign":134,"util/":128}],126:[function(require,module,exports){
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
+ return barkScale;
+}
+function typedToArray(t) {
+ // utility to convert typed arrays to normal arrays
+ return Array.prototype.slice.call(t);
+}
+function arrayToTyped(t) {
+ // utility to convert arrays to typed F32 arrays
+ return Float32Array.from(t);
+}
+function _normalize(num, range) {
+ return num / range;
+}
+function normalize(a, range) {
+ return a.map(function (n) {
+ return _normalize(n, range);
+ });
+}
+function normalizeToOne(a) {
+ var max = Math.max.apply(null, a);
+ return a.map(function (n) {
+ return n / max;
+ });
+}
+function mean(a) {
+ return a.reduce(function (prev, cur) {
+ return prev + cur;
+ }) / a.length;
}
-},{}],127:[function(require,module,exports){
-module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
+function _melToFreq(melValue) {
+ var freqValue = 700 * (Math.exp(melValue / 1125) - 1);
+ return freqValue;
}
-},{}],128:[function(require,module,exports){
-(function (process,global){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
+function _freqToMel(freqValue) {
+ var melValue = 1125 * Math.log(1 + freqValue / 700);
+ return melValue;
+}
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
+function melToFreq(mV) {
+ return _melToFreq(mV);
+}
+function freqToMel(fV) {
+ return _freqToMel(fV);
+}
+function createMelFilterBank(numFilters, sampleRate, bufferSize) {
+ //the +2 is the upper and lower limits
+ var melValues = new Float32Array(numFilters + 2);
+ var melValuesInFreq = new Float32Array(numFilters + 2); //Generate limits in Hz - from 0 to the nyquist.
+ var lowerLimitFreq = 0;
+ var upperLimitFreq = sampleRate / 2; //Convert the limits to Mel
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
+ var lowerLimitMel = _freqToMel(lowerLimitFreq);
- if (process.noDeprecation === true) {
- return fn;
- }
+ var upperLimitMel = _freqToMel(upperLimitFreq); //Find the range
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
-};
+ var range = upperLimitMel - lowerLimitMel; //Find the range as part of the linear interpolation
+ var valueToAdd = range / (numFilters + 1);
+ var fftBinsOfFreq = Array(numFilters + 2);
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
-};
+ for (var i = 0; i < melValues.length; i++) {
+ // Initialising the mel frequencies
+ // They're a linear interpolation between the lower and upper limits.
+ melValues[i] = i * valueToAdd; // Convert back to Hz
+ melValuesInFreq[i] = _melToFreq(melValues[i]); // Find the corresponding bins
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
+ fftBinsOfFreq[i] = Math.floor((bufferSize + 1) * melValuesInFreq[i] / sampleRate);
}
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
+ var filterBank = Array(numFilters);
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
+ for (var j = 0; j < filterBank.length; j++) {
+ // Create a two dimensional array of size numFilters * (buffersize/2)+1
+ // pre-populating the arrays with 0s.
+ filterBank[j] = Array.apply(null, new Array(bufferSize / 2 + 1)).map(Number.prototype.valueOf, 0); //creating the lower and upper slopes for each bin
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
+ for (var _i = fftBinsOfFreq[j]; _i < fftBinsOfFreq[j + 1]; _i++) {
+ filterBank[j][_i] = (_i - fftBinsOfFreq[j]) / (fftBinsOfFreq[j + 1] - fftBinsOfFreq[j]);
+ }
+ for (var _i2 = fftBinsOfFreq[j + 1]; _i2 < fftBinsOfFreq[j + 2]; _i2++) {
+ filterBank[j][_i2] = (fftBinsOfFreq[j + 2] - _i2) / (fftBinsOfFreq[j + 2] - fftBinsOfFreq[j + 1]);
+ }
+ }
+
+ return filterBank;
+}
+function hzToOctaves(freq, A440) {
+ return Math.log2(16 * freq / A440);
+}
+function normalizeByColumn(a) {
+ var emptyRow = a[0].map(function () {
+ return 0;
+ });
+ var colDenominators = a.reduce(function (acc, row) {
+ row.forEach(function (cell, j) {
+ acc[j] += Math.pow(cell, 2);
+ });
+ return acc;
+ }, emptyRow).map(Math.sqrt);
+ return a.map(function (row, i) {
+ return row.map(function (v, j) {
+ return v / (colDenominators[j] || 1);
+ });
+ });
+}
+;
+function createChromaFilterBank(numFilters, sampleRate, bufferSize) {
+ var centerOctave = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5;
+ var octaveWidth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 2;
+ var baseC = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
+ var A440 = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 440;
+ var numOutputBins = Math.floor(bufferSize / 2) + 1;
+ var frequencyBins = new Array(bufferSize).fill(0).map(function (_, i) {
+ return numFilters * hzToOctaves(sampleRate * i / bufferSize, A440);
+ }); // Set a value for the 0 Hz bin that is 1.5 octaves below bin 1
+ // (so chroma is 50% rotated from bin 1, and bin width is broad)
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
+ frequencyBins[0] = frequencyBins[1] - 1.5 * numFilters;
+ var binWidthBins = frequencyBins.slice(1).map(function (v, i) {
+ return Math.max(v - frequencyBins[i]);
+ }, 1).concat([1]);
+ var halfNumFilters = Math.round(numFilters / 2);
+ var filterPeaks = new Array(numFilters).fill(0).map(function (_, i) {
+ return frequencyBins.map(function (frq) {
+ return (10 * numFilters + halfNumFilters + frq - i) % numFilters - halfNumFilters;
+ });
+ });
+ var weights = filterPeaks.map(function (row, i) {
+ return row.map(function (_, j) {
+ return Math.exp(-0.5 * Math.pow(2 * filterPeaks[i][j] / binWidthBins[j], 2));
+ });
+ });
+ weights = normalizeByColumn(weights);
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
+ if (octaveWidth) {
+ var octaveWeights = frequencyBins.map(function (v) {
+ return Math.exp(-0.5 * Math.pow((v / numFilters - centerOctave) / octaveWidth, 2));
+ });
+ weights = weights.map(function (row) {
+ return row.map(function (cell, j) {
+ return cell * octaveWeights[j];
+ });
+ });
}
-}
+ if (baseC) {
+ weights = [].concat(_toConsumableArray(weights.slice(3)), _toConsumableArray(weights.slice(0, 3)));
+ }
-function stylizeNoColor(str, styleType) {
- return str;
+ return weights.map(function (row) {
+ return row.slice(0, numOutputBins);
+ });
}
+function frame(buffer, frameLength, hopLength) {
+ if (buffer.length < frameLength) {
+ throw new Error('Buffer is too short for frame length');
+ }
+ if (hopLength < 1) {
+ throw new Error('Hop length cannot be less that 1');
+ }
-function arrayToHash(array) {
- var hash = {};
+ if (frameLength < 1) {
+ throw new Error('Frame length cannot be less that 1');
+ }
- array.forEach(function(val, idx) {
- hash[val] = true;
+ var numFrames = 1 + Math.floor((buffer.length - frameLength) / hopLength);
+ return new Array(numFrames).fill(0).map(function (_, i) {
+ return buffer.slice(i * hopLength, i * hopLength + frameLength);
});
-
- return hash;
}
+/***/ }),
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
+/***/ "./src/windowing.js":
+/*!**************************!*\
+ !*** ./src/windowing.js ***!
+ \**************************/
+/*! exports provided: blackman, sine, hanning, hamming */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "blackman", function() { return blackman; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sine", function() { return sine; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hanning", function() { return hanning; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hamming", function() { return hamming; });
+function blackman(size) {
+ var blackmanBuffer = new Float32Array(size);
+ var coeff1 = 2 * Math.PI / (size - 1);
+ var coeff2 = 2 * coeff1; //According to http://uk.mathworks.com/help/signal/ref/blackman.html
+ //first half of the window
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
+ for (var i = 0; i < size / 2; i++) {
+ blackmanBuffer[i] = 0.42 - 0.5 * Math.cos(i * coeff1) + 0.08 * Math.cos(i * coeff2);
+ } //second half of the window
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
+ for (var _i = size / 2; _i > 0; _i--) {
+ blackmanBuffer[size - _i] = blackmanBuffer[_i - 1];
}
- var base = '', array = false, braces = ['{', '}'];
+ return blackmanBuffer;
+}
+function sine(size) {
+ var coeff = Math.PI / (size - 1);
+ var sineBuffer = new Float32Array(size);
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
+ for (var i = 0; i < size; i++) {
+ sineBuffer[i] = Math.sin(coeff * i);
}
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
+ return sineBuffer;
+}
+function hanning(size) {
+ var hanningBuffer = new Float32Array(size);
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
+ for (var i = 0; i < size; i++) {
+ // According to the R documentation
+ // http://ugrad.stat.ubc.ca/R/library/e1071/html/hanning.window.html
+ hanningBuffer[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (size - 1));
}
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
+ return hanningBuffer;
+}
+function hamming(size) {
+ var hammingBuffer = new Float32Array(size);
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
+ for (var i = 0; i < size; i++) {
+ //According to http://uk.mathworks.com/help/signal/ref/hamming.html
+ hammingBuffer[i] = 0.54 - 0.46 * Math.cos(2 * Math.PI * (i / size - 1));
}
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
+ return hammingBuffer;
+}
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
+/***/ })
- ctx.seen.push(value);
+/******/ });
+});
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
+},{}],93:[function(require,module,exports){
+assert.notEqual = notEqual
+assert.notOk = notOk
+assert.equal = equal
+assert.ok = assert
- ctx.seen.pop();
+module.exports = assert
- return reduceToSingleString(output, base, braces);
+function equal (a, b, m) {
+ assert(a == b, m) // eslint-disable-line eqeqeq
}
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
+function notEqual (a, b, m) {
+ assert(a != b, m) // eslint-disable-line eqeqeq
}
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
+function notOk (t, m) {
+ assert(!t, m)
}
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
+function assert (t, m) {
+ if (!t) throw new Error(m || 'AssertionError')
}
+},{}],94:[function(require,module,exports){
+var splice = require('remove-array-items')
+var nanotiming = require('nanotiming')
+var assert = require('assert')
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
+module.exports = Nanobus
- return name + ': ' + str;
-}
+function Nanobus (name) {
+ if (!(this instanceof Nanobus)) return new Nanobus(name)
+ this._name = name || 'nanobus'
+ this._starListeners = []
+ this._listeners = {}
+}
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
+Nanobus.prototype.emit = function (eventName) {
+ assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.emit: eventName should be type string or symbol')
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
+ var data = []
+ for (var i = 1, len = arguments.length; i < len; i++) {
+ data.push(arguments[i])
}
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
+ var emitTiming = nanotiming(this._name + "('" + eventName.toString() + "')")
+ var listeners = this._listeners[eventName]
+ if (listeners && listeners.length > 0) {
+ this._emit(this._listeners[eventName], data)
+ }
+ if (this._starListeners.length > 0) {
+ this._emit(this._starListeners, eventName, data, emitTiming.uuid)
+ }
+ emitTiming()
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-function isArray(ar) {
- return Array.isArray(ar);
+ return this
}
-exports.isArray = isArray;
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
+Nanobus.prototype.on = Nanobus.prototype.addListener = function (eventName, listener) {
+ assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.on: eventName should be type string or symbol')
+ assert.equal(typeof listener, 'function', 'nanobus.on: listener should be type function')
-function isNull(arg) {
- return arg === null;
+ if (eventName === '*') {
+ this._starListeners.push(listener)
+ } else {
+ if (!this._listeners[eventName]) this._listeners[eventName] = []
+ this._listeners[eventName].push(listener)
+ }
+ return this
}
-exports.isNull = isNull;
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
+Nanobus.prototype.prependListener = function (eventName, listener) {
+ assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.prependListener: eventName should be type string or symbol')
+ assert.equal(typeof listener, 'function', 'nanobus.prependListener: listener should be type function')
-function isNumber(arg) {
- return typeof arg === 'number';
+ if (eventName === '*') {
+ this._starListeners.unshift(listener)
+ } else {
+ if (!this._listeners[eventName]) this._listeners[eventName] = []
+ this._listeners[eventName].unshift(listener)
+ }
+ return this
}
-exports.isNumber = isNumber;
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
+Nanobus.prototype.once = function (eventName, listener) {
+ assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.once: eventName should be type string or symbol')
+ assert.equal(typeof listener, 'function', 'nanobus.once: listener should be type function')
-function isSymbol(arg) {
- return typeof arg === 'symbol';
+ var self = this
+ this.on(eventName, once)
+ function once () {
+ listener.apply(self, arguments)
+ self.removeListener(eventName, once)
+ }
+ return this
}
-exports.isSymbol = isSymbol;
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
+Nanobus.prototype.prependOnceListener = function (eventName, listener) {
+ assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.prependOnceListener: eventName should be type string or symbol')
+ assert.equal(typeof listener, 'function', 'nanobus.prependOnceListener: listener should be type function')
-function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
+ var self = this
+ this.prependListener(eventName, once)
+ function once () {
+ listener.apply(self, arguments)
+ self.removeListener(eventName, once)
+ }
+ return this
}
-exports.isRegExp = isRegExp;
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
+Nanobus.prototype.removeListener = function (eventName, listener) {
+ assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.removeListener: eventName should be type string or symbol')
+ assert.equal(typeof listener, 'function', 'nanobus.removeListener: listener should be type function')
-function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
+ if (eventName === '*') {
+ this._starListeners = this._starListeners.slice()
+ return remove(this._starListeners, listener)
+ } else {
+ if (typeof this._listeners[eventName] !== 'undefined') {
+ this._listeners[eventName] = this._listeners[eventName].slice()
+ }
-function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
+ return remove(this._listeners[eventName], listener)
+ }
-function isFunction(arg) {
- return typeof arg === 'function';
+ function remove (arr, listener) {
+ if (!arr) return
+ var index = arr.indexOf(listener)
+ if (index !== -1) {
+ splice(arr, index, 1)
+ return true
+ }
+ }
}
-exports.isFunction = isFunction;
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
+Nanobus.prototype.removeAllListeners = function (eventName) {
+ if (eventName) {
+ if (eventName === '*') {
+ this._starListeners = []
+ } else {
+ this._listeners[eventName] = []
+ }
+ } else {
+ this._starListeners = []
+ this._listeners = {}
+ }
+ return this
}
-exports.isPrimitive = isPrimitive;
-exports.isBuffer = require('./support/isBuffer');
+Nanobus.prototype.listeners = function (eventName) {
+ var listeners = eventName !== '*'
+ ? this._listeners[eventName]
+ : this._starListeners
-function objectToString(o) {
- return Object.prototype.toString.call(o);
+ var ret = []
+ if (listeners) {
+ var ilength = listeners.length
+ for (var i = 0; i < ilength; i++) ret.push(listeners[i])
+ }
+ return ret
}
+Nanobus.prototype._emit = function (arr, eventName, data, uuid) {
+ if (typeof arr === 'undefined') return
+ if (arr.length === 0) return
+ if (data === undefined) {
+ data = eventName
+ eventName = null
+ }
+
+ if (eventName) {
+ if (uuid !== undefined) {
+ data = [eventName].concat(data, uuid)
+ } else {
+ data = [eventName].concat(data)
+ }
+ }
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
+ var length = arr.length
+ for (var i = 0; i < length; i++) {
+ var listener = arr[i]
+ listener.apply(listener, data)
+ }
}
+},{"assert":93,"nanotiming":113,"remove-array-items":125}],95:[function(require,module,exports){
+var document = require('global/document')
+var nanotiming = require('nanotiming')
+var morph = require('nanomorph')
+var onload = require('on-load')
+var OL_KEY_ID = onload.KEY_ID
+var OL_ATTR_ID = onload.KEY_ATTR
+var assert = require('assert')
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
+module.exports = Nanocomponent
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
+function makeID () {
+ return 'ncid-' + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
}
+function Nanocomponent (name) {
+ this._hasWindow = typeof window !== 'undefined'
+ this._id = null // represents the id of the root node
+ this._ncID = null // internal nanocomponent id
+ this._olID = null
+ this._proxy = null
+ this._loaded = false // Used to debounce on-load when child-reordering
+ this._rootNodeName = null
+ this._name = name || 'nanocomponent'
+ this._rerender = false
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
+ this._handleLoad = this._handleLoad.bind(this)
+ this._handleUnload = this._handleUnload.bind(this)
+ this._arguments = []
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = require('inherits');
+ var self = this
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
+ Object.defineProperty(this, 'element', {
+ get: function () {
+ var el = document.getElementById(self._id)
+ if (el) return el.dataset.nanocomponent === self._ncID ? el : undefined
+ }
+ })
+}
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
+Nanocomponent.prototype.render = function () {
+ var renderTiming = nanotiming(this._name + '.render')
+ var self = this
+ var args = new Array(arguments.length)
+ var el
+ for (var i = 0; i < arguments.length; i++) args[i] = arguments[i]
+ if (!this._hasWindow) {
+ var createTiming = nanotiming(this._name + '.create')
+ el = this.createElement.apply(this, args)
+ createTiming()
+ renderTiming()
+ return el
+ } else if (this.element) {
+ el = this.element // retain reference, as the ID might change on render
+ var updateTiming = nanotiming(this._name + '.update')
+ var shouldUpdate = this._rerender || this.update.apply(this, args)
+ updateTiming()
+ if (this._rerender) this._rerender = false
+ if (shouldUpdate) {
+ var desiredHtml = this._handleRender(args)
+ var morphTiming = nanotiming(this._name + '.morph')
+ morph(el, desiredHtml)
+ morphTiming()
+ if (this.afterupdate) this.afterupdate(el)
+ }
+ if (!this._proxy) { this._proxy = this._createProxy() }
+ renderTiming()
+ return this._proxy
+ } else {
+ this._reset()
+ el = this._handleRender(args)
+ if (this.beforerender) this.beforerender(el)
+ if (this.load || this.unload || this.afterreorder) {
+ onload(el, self._handleLoad, self._handleUnload, self._ncID)
+ this._olID = el.dataset[OL_KEY_ID]
+ }
+ renderTiming()
+ return el
}
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
}
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./support/isBuffer":127,"_process":135,"inherits":126}],129:[function(require,module,exports){
-'use strict'
-
-exports.byteLength = byteLength
-exports.toByteArray = toByteArray
-exports.fromByteArray = fromByteArray
-
-var lookup = []
-var revLookup = []
-var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
-
-var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
-for (var i = 0, len = code.length; i < len; ++i) {
- lookup[i] = code[i]
- revLookup[code.charCodeAt(i)] = i
+Nanocomponent.prototype.rerender = function () {
+ assert(this.element, 'nanocomponent: cant rerender on an unmounted dom node')
+ this._rerender = true
+ this.render.apply(this, this._arguments)
}
-// Support decoding URL-safe base64 strings, as Node.js does.
-// See: https://en.wikipedia.org/wiki/Base64#URL_applications
-revLookup['-'.charCodeAt(0)] = 62
-revLookup['_'.charCodeAt(0)] = 63
-
-function getLens (b64) {
- var len = b64.length
+Nanocomponent.prototype._handleRender = function (args) {
+ var createElementTiming = nanotiming(this._name + '.createElement')
+ var el = this.createElement.apply(this, args)
+ createElementTiming()
+ if (!this._rootNodeName) this._rootNodeName = el.nodeName
+ assert(el instanceof window.Element, 'nanocomponent: createElement should return a single DOM node')
+ assert.equal(this._rootNodeName, el.nodeName, 'nanocomponent: root node types cannot differ between re-renders')
+ this._arguments = args
+ return this._brandNode(this._ensureID(el))
+}
- if (len % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
+Nanocomponent.prototype._createProxy = function () {
+ var proxy = document.createElement(this._rootNodeName)
+ var self = this
+ this._brandNode(proxy)
+ proxy.id = this._id
+ proxy.setAttribute('data-proxy', '')
+ proxy.isSameNode = function (el) {
+ return (el && el.dataset.nanocomponent === self._ncID)
}
+ return proxy
+}
- // Trim off extra bytes after placeholder bytes are found
- // See: https://github.com/beatgammit/base64-js/issues/42
- var validLen = b64.indexOf('=')
- if (validLen === -1) validLen = len
-
- var placeHoldersLen = validLen === len
- ? 0
- : 4 - (validLen % 4)
+Nanocomponent.prototype._reset = function () {
+ this._ncID = makeID()
+ this._olID = null
+ this._id = null
+ this._proxy = null
+ this._rootNodeName = null
+}
- return [validLen, placeHoldersLen]
+Nanocomponent.prototype._brandNode = function (node) {
+ node.setAttribute('data-nanocomponent', this._ncID)
+ if (this._olID) node.setAttribute(OL_ATTR_ID, this._olID)
+ return node
}
-// base64 is 4/3 + up to two characters of the original data
-function byteLength (b64) {
- var lens = getLens(b64)
- var validLen = lens[0]
- var placeHoldersLen = lens[1]
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+Nanocomponent.prototype._ensureID = function (node) {
+ if (node.id) this._id = node.id
+ else node.id = this._id = this._ncID
+ // Update proxy node ID if it changed
+ if (this._proxy && this._proxy.id !== this._id) this._proxy.id = this._id
+ return node
}
-function _byteLength (b64, validLen, placeHoldersLen) {
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+Nanocomponent.prototype._handleLoad = function (el) {
+ if (this._loaded) {
+ if (this.afterreorder) this.afterreorder(el)
+ return // Debounce child-reorders
+ }
+ this._loaded = true
+ if (this.load) this.load(el)
}
-function toByteArray (b64) {
- var tmp
- var lens = getLens(b64)
- var validLen = lens[0]
- var placeHoldersLen = lens[1]
+Nanocomponent.prototype._handleUnload = function (el) {
+ if (this.element) return // Debounce child-reorders
+ this._loaded = false
+ if (this.unload) this.unload(el)
+}
- var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
+Nanocomponent.prototype.createElement = function () {
+ throw new Error('nanocomponent: createElement should be implemented!')
+}
- var curByte = 0
+Nanocomponent.prototype.update = function () {
+ throw new Error('nanocomponent: update should be implemented!')
+}
- // if there are placeholders, only get up to the last complete 4 chars
- var len = placeHoldersLen > 0
- ? validLen - 4
- : validLen
+},{"assert":93,"global/document":64,"nanomorph":106,"nanotiming":113,"on-load":116}],96:[function(require,module,exports){
+var assert = require('assert')
- var i
- for (i = 0; i < len; i += 4) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 18) |
- (revLookup[b64.charCodeAt(i + 1)] << 12) |
- (revLookup[b64.charCodeAt(i + 2)] << 6) |
- revLookup[b64.charCodeAt(i + 3)]
- arr[curByte++] = (tmp >> 16) & 0xFF
- arr[curByte++] = (tmp >> 8) & 0xFF
- arr[curByte++] = tmp & 0xFF
- }
+var safeExternalLink = /(noopener|noreferrer) (noopener|noreferrer)/
+var protocolLink = /^[\w-_]+:/
- if (placeHoldersLen === 2) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 2) |
- (revLookup[b64.charCodeAt(i + 1)] >> 4)
- arr[curByte++] = tmp & 0xFF
- }
+module.exports = href
- if (placeHoldersLen === 1) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 10) |
- (revLookup[b64.charCodeAt(i + 1)] << 4) |
- (revLookup[b64.charCodeAt(i + 2)] >> 2)
- arr[curByte++] = (tmp >> 8) & 0xFF
- arr[curByte++] = tmp & 0xFF
- }
+function href (cb, root) {
+ assert.notEqual(typeof window, 'undefined', 'nanohref: expected window to exist')
- return arr
-}
+ root = root || window.document
-function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] +
- lookup[num >> 12 & 0x3F] +
- lookup[num >> 6 & 0x3F] +
- lookup[num & 0x3F]
-}
+ assert.equal(typeof cb, 'function', 'nanohref: cb should be type function')
+ assert.equal(typeof root, 'object', 'nanohref: root should be type object')
-function encodeChunk (uint8, start, end) {
- var tmp
- var output = []
- for (var i = start; i < end; i += 3) {
- tmp =
- ((uint8[i] << 16) & 0xFF0000) +
- ((uint8[i + 1] << 8) & 0xFF00) +
- (uint8[i + 2] & 0xFF)
- output.push(tripletToBase64(tmp))
- }
- return output.join('')
-}
+ window.addEventListener('click', function (e) {
+ if ((e.button && e.button !== 0) ||
+ e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ||
+ e.defaultPrevented) return
-function fromByteArray (uint8) {
- var tmp
- var len = uint8.length
- var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
- var parts = []
- var maxChunkLength = 16383 // must be multiple of 3
+ var anchor = (function traverse (node) {
+ if (!node || node === root) return
+ if (node.localName !== 'a' || node.href === undefined) {
+ return traverse(node.parentNode)
+ }
+ return node
+ })(e.target)
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
- parts.push(encodeChunk(
- uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
- ))
- }
+ if (!anchor) return
- // pad the end with zeros, but make sure to not forget the extra bytes
- if (extraBytes === 1) {
- tmp = uint8[len - 1]
- parts.push(
- lookup[tmp >> 2] +
- lookup[(tmp << 4) & 0x3F] +
- '=='
- )
- } else if (extraBytes === 2) {
- tmp = (uint8[len - 2] << 8) + uint8[len - 1]
- parts.push(
- lookup[tmp >> 10] +
- lookup[(tmp >> 4) & 0x3F] +
- lookup[(tmp << 2) & 0x3F] +
- '='
- )
- }
+ if (window.location.protocol !== anchor.protocol ||
+ window.location.hostname !== anchor.hostname ||
+ window.location.port !== anchor.port ||
+ anchor.hasAttribute('data-nanohref-ignore') ||
+ anchor.hasAttribute('download') ||
+ (anchor.getAttribute('target') === '_blank' &&
+ safeExternalLink.test(anchor.getAttribute('rel'))) ||
+ protocolLink.test(anchor.getAttribute('href'))) return
- return parts.join('')
+ e.preventDefault()
+ cb(anchor)
+ })
}
-},{}],130:[function(require,module,exports){
-
-},{}],131:[function(require,module,exports){
-(function (Buffer){
-/*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-/* eslint-disable no-proto */
-
+},{"assert":93}],97:[function(require,module,exports){
'use strict'
-var base64 = require('base64-js')
-var ieee754 = require('ieee754')
+var trailingNewlineRegex = /\n[\s]+$/
+var leadingNewlineRegex = /^\n[\s]+/
+var trailingSpaceRegex = /[\s]+$/
+var leadingSpaceRegex = /^[\s]+/
+var multiSpaceRegex = /[\n\s]+/g
-exports.Buffer = Buffer
-exports.SlowBuffer = SlowBuffer
-exports.INSPECT_MAX_BYTES = 50
+var TEXT_TAGS = [
+ 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'data', 'dfn', 'em', 'i',
+ 'kbd', 'mark', 'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'amp', 'small', 'span',
+ 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr'
+]
-var K_MAX_LENGTH = 0x7fffffff
-exports.kMaxLength = K_MAX_LENGTH
+var VERBATIM_TAGS = [
+ 'code', 'pre', 'textarea'
+]
-/**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Print warning and recommend using `buffer` v4.x which has an Object
- * implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * We report that the browser does not support typed arrays if the are not subclassable
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
- * for __proto__ and has a buggy typed array implementation.
- */
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
+module.exports = function appendChild (el, childs) {
+ if (!Array.isArray(childs)) return
-if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
- typeof console.error === 'function') {
- console.error(
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
- )
-}
+ var nodeName = el.nodeName.toLowerCase()
-function typedArraySupport () {
- // Can typed array instances can be augmented?
- try {
- var arr = new Uint8Array(1)
- arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
- return arr.foo() === 42
- } catch (e) {
- return false
- }
-}
+ var hadText = false
+ var value, leader
-Object.defineProperty(Buffer.prototype, 'parent', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.buffer
- }
-})
+ for (var i = 0, len = childs.length; i < len; i++) {
+ var node = childs[i]
+ if (Array.isArray(node)) {
+ appendChild(el, node)
+ continue
+ }
-Object.defineProperty(Buffer.prototype, 'offset', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.byteOffset
- }
-})
+ if (typeof node === 'number' ||
+ typeof node === 'boolean' ||
+ typeof node === 'function' ||
+ node instanceof Date ||
+ node instanceof RegExp) {
+ node = node.toString()
+ }
-function createBuffer (length) {
- if (length > K_MAX_LENGTH) {
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
- }
- // Return an augmented `Uint8Array` instance
- var buf = new Uint8Array(length)
- buf.__proto__ = Buffer.prototype
- return buf
-}
+ var lastChild = el.childNodes[el.childNodes.length - 1]
-/**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
+ // Iterate over text nodes
+ if (typeof node === 'string') {
+ hadText = true
-function Buffer (arg, encodingOrOffset, length) {
- // Common case.
- if (typeof arg === 'number') {
- if (typeof encodingOrOffset === 'string') {
- throw new TypeError(
- 'The "string" argument must be of type string. Received type number'
- )
- }
- return allocUnsafe(arg)
- }
- return from(arg, encodingOrOffset, length)
-}
+ // If we already had text, append to the existing text
+ if (lastChild && lastChild.nodeName === '#text') {
+ lastChild.nodeValue += node
-// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
-if (typeof Symbol !== 'undefined' && Symbol.species != null &&
- Buffer[Symbol.species] === Buffer) {
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true,
- enumerable: false,
- writable: false
- })
-}
+ // We didn't have a text node yet, create one
+ } else {
+ node = el.ownerDocument.createTextNode(node)
+ el.appendChild(node)
+ lastChild = node
+ }
-Buffer.poolSize = 8192 // not used by this implementation
+ // If this is the last of the child nodes, make sure we close it out
+ // right
+ if (i === len - 1) {
+ hadText = false
+ // Trim the child text nodes if the current node isn't a
+ // node where whitespace matters.
+ if (TEXT_TAGS.indexOf(nodeName) === -1 &&
+ VERBATIM_TAGS.indexOf(nodeName) === -1) {
+ value = lastChild.nodeValue
+ .replace(leadingNewlineRegex, '')
+ .replace(trailingSpaceRegex, '')
+ .replace(trailingNewlineRegex, '')
+ .replace(multiSpaceRegex, ' ')
+ if (value === '') {
+ el.removeChild(lastChild)
+ } else {
+ lastChild.nodeValue = value
+ }
+ } else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
+ // The very first node in the list should not have leading
+ // whitespace. Sibling text nodes should have whitespace if there
+ // was any.
+ leader = i === 0 ? '' : ' '
+ value = lastChild.nodeValue
+ .replace(leadingNewlineRegex, leader)
+ .replace(leadingSpaceRegex, ' ')
+ .replace(trailingSpaceRegex, '')
+ .replace(trailingNewlineRegex, '')
+ .replace(multiSpaceRegex, ' ')
+ lastChild.nodeValue = value
+ }
+ }
-function from (value, encodingOrOffset, length) {
- if (typeof value === 'string') {
- return fromString(value, encodingOrOffset)
- }
+ // Iterate over DOM nodes
+ } else if (node && node.nodeType) {
+ // If the last node was a text node, make sure it is properly closed out
+ if (hadText) {
+ hadText = false
- if (ArrayBuffer.isView(value)) {
- return fromArrayLike(value)
- }
+ // Trim the child text nodes if the current node isn't a
+ // text node or a code node
+ if (TEXT_TAGS.indexOf(nodeName) === -1 &&
+ VERBATIM_TAGS.indexOf(nodeName) === -1) {
+ value = lastChild.nodeValue
+ .replace(leadingNewlineRegex, '')
+ .replace(trailingNewlineRegex, ' ')
+ .replace(multiSpaceRegex, ' ')
- if (value == null) {
- throw TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
- }
+ // Remove empty text nodes, append otherwise
+ if (value === '') {
+ el.removeChild(lastChild)
+ } else {
+ lastChild.nodeValue = value
+ }
+ // Trim the child nodes but preserve the appropriate whitespace
+ } else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
+ value = lastChild.nodeValue
+ .replace(leadingSpaceRegex, ' ')
+ .replace(leadingNewlineRegex, '')
+ .replace(trailingNewlineRegex, ' ')
+ .replace(multiSpaceRegex, ' ')
+ lastChild.nodeValue = value
+ }
+ }
- if (isInstance(value, ArrayBuffer) ||
- (value && isInstance(value.buffer, ArrayBuffer))) {
- return fromArrayBuffer(value, encodingOrOffset, length)
- }
+ // Store the last nodename
+ var _nodeName = node.nodeName
+ if (_nodeName) nodeName = _nodeName.toLowerCase()
- if (typeof value === 'number') {
- throw new TypeError(
- 'The "value" argument must not be of type number. Received type number'
- )
+ // Append the node to the DOM
+ el.appendChild(node)
+ }
}
+}
- var valueOf = value.valueOf && value.valueOf()
- if (valueOf != null && valueOf !== value) {
- return Buffer.from(valueOf, encodingOrOffset, length)
- }
+},{}],98:[function(require,module,exports){
+'use strict'
- var b = fromObject(value)
- if (b) return b
+module.exports = [
+ 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default',
+ 'defaultchecked', 'defer', 'disabled', 'formnovalidate', 'hidden',
+ 'ismap', 'loop', 'multiple', 'muted', 'novalidate', 'open', 'playsinline',
+ 'readonly', 'required', 'reversed', 'selected'
+]
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
- typeof value[Symbol.toPrimitive] === 'function') {
- return Buffer.from(
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
- )
- }
+},{}],99:[function(require,module,exports){
+module.exports = require('./dom')(document)
- throw new TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
-}
+},{"./dom":101}],100:[function(require,module,exports){
+'use strict'
-/**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
-Buffer.from = function (value, encodingOrOffset, length) {
- return from(value, encodingOrOffset, length)
-}
+module.exports = [
+ 'indeterminate'
+]
-// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
-// https://github.com/feross/buffer/pull/148
-Buffer.prototype.__proto__ = Uint8Array.prototype
-Buffer.__proto__ = Uint8Array
+},{}],101:[function(require,module,exports){
+'use strict'
-function assertSize (size) {
- if (typeof size !== 'number') {
- throw new TypeError('"size" argument must be of type number')
- } else if (size < 0) {
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
- }
-}
+var hyperx = require('hyperx')
+var appendChild = require('./append-child')
+var SVG_TAGS = require('./svg-tags')
+var BOOL_PROPS = require('./bool-props')
+// Props that need to be set directly rather than with el.setAttribute()
+var DIRECT_PROPS = require('./direct-props')
-function alloc (size, fill, encoding) {
- assertSize(size)
- if (size <= 0) {
- return createBuffer(size)
- }
- if (fill !== undefined) {
- // Only pay attention to encoding if it's a string. This
- // prevents accidentally sending in a number that would
- // be interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(size).fill(fill, encoding)
- : createBuffer(size).fill(fill)
- }
- return createBuffer(size)
-}
+var SVGNS = 'http://www.w3.org/2000/svg'
+var XLINKNS = 'http://www.w3.org/1999/xlink'
-/**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
-Buffer.alloc = function (size, fill, encoding) {
- return alloc(size, fill, encoding)
-}
+var COMMENT_TAG = '!--'
-function allocUnsafe (size) {
- assertSize(size)
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
-}
+module.exports = function (document) {
+ function nanoHtmlCreateElement (tag, props, children) {
+ var el
-/**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
-Buffer.allocUnsafe = function (size) {
- return allocUnsafe(size)
-}
-/**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
-Buffer.allocUnsafeSlow = function (size) {
- return allocUnsafe(size)
-}
+ // If an svg tag, it needs a namespace
+ if (SVG_TAGS.indexOf(tag) !== -1) {
+ props.namespace = SVGNS
+ }
-function fromString (string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8'
- }
+ // If we are using a namespace
+ var ns = false
+ if (props.namespace) {
+ ns = props.namespace
+ delete props.namespace
+ }
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
+ // If we are extending a builtin element
+ var isCustomElement = false
+ if (props.is) {
+ isCustomElement = props.is
+ delete props.is
+ }
- var length = byteLength(string, encoding) | 0
- var buf = createBuffer(length)
+ // Create the element
+ if (ns) {
+ if (isCustomElement) {
+ el = document.createElementNS(ns, tag, { is: isCustomElement })
+ } else {
+ el = document.createElementNS(ns, tag)
+ }
+ } else if (tag === COMMENT_TAG) {
+ return document.createComment(props.comment)
+ } else if (isCustomElement) {
+ el = document.createElement(tag, { is: isCustomElement })
+ } else {
+ el = document.createElement(tag)
+ }
- var actual = buf.write(string, encoding)
+ // Create the properties
+ for (var p in props) {
+ if (props.hasOwnProperty(p)) {
+ var key = p.toLowerCase()
+ var val = props[p]
+ // Normalize className
+ if (key === 'classname') {
+ key = 'class'
+ p = 'class'
+ }
+ // The for attribute gets transformed to htmlFor, but we just set as for
+ if (p === 'htmlFor') {
+ p = 'for'
+ }
+ // If a property is boolean, set itself to the key
+ if (BOOL_PROPS.indexOf(key) !== -1) {
+ if (String(val) === 'true') val = key
+ else if (String(val) === 'false') continue
+ }
+ // If a property prefers being set directly vs setAttribute
+ if (key.slice(0, 2) === 'on' || DIRECT_PROPS.indexOf(key) !== -1) {
+ el[p] = val
+ } else {
+ if (ns) {
+ if (p === 'xlink:href') {
+ el.setAttributeNS(XLINKNS, p, val)
+ } else if (/^xmlns($|:)/i.test(p)) {
+ // skip xmlns definitions
+ } else {
+ el.setAttributeNS(null, p, val)
+ }
+ } else {
+ el.setAttribute(p, val)
+ }
+ }
+ }
+ }
- if (actual !== length) {
- // Writing a hex string, for example, that contains invalid characters will
- // cause everything after the first invalid character to be ignored. (e.g.
- // 'abxxcd' will be treated as 'ab')
- buf = buf.slice(0, actual)
+ appendChild(el, children)
+ return el
}
- return buf
-}
-
-function fromArrayLike (array) {
- var length = array.length < 0 ? 0 : checked(array.length) | 0
- var buf = createBuffer(length)
- for (var i = 0; i < length; i += 1) {
- buf[i] = array[i] & 255
+ function createFragment (nodes) {
+ var fragment = document.createDocumentFragment()
+ for (var i = 0; i < nodes.length; i++) {
+ if (nodes[i] == null) continue
+ if (Array.isArray(nodes[i])) {
+ fragment.appendChild(createFragment(nodes[i]))
+ } else {
+ if (typeof nodes[i] === 'string') nodes[i] = document.createTextNode(nodes[i])
+ fragment.appendChild(nodes[i])
+ }
+ }
+ return fragment
}
- return buf
-}
-function fromArrayBuffer (array, byteOffset, length) {
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('"offset" is outside of buffer bounds')
- }
+ var exports = hyperx(nanoHtmlCreateElement, {
+ comments: true,
+ createFragment: createFragment
+ })
+ exports.default = exports
+ exports.createComment = nanoHtmlCreateElement
+ return exports
+}
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('"length" is outside of buffer bounds')
- }
+},{"./append-child":97,"./bool-props":98,"./direct-props":100,"./svg-tags":103,"hyperx":87}],102:[function(require,module,exports){
+'use strict'
- var buf
- if (byteOffset === undefined && length === undefined) {
- buf = new Uint8Array(array)
- } else if (length === undefined) {
- buf = new Uint8Array(array, byteOffset)
- } else {
- buf = new Uint8Array(array, byteOffset, length)
- }
+function nanohtmlRawBrowser (tag) {
+ var el = document.createElement('div')
+ el.innerHTML = tag
+ return toArray(el.childNodes)
+}
- // Return an augmented `Uint8Array` instance
- buf.__proto__ = Buffer.prototype
- return buf
+function toArray (arr) {
+ return Array.isArray(arr) ? arr : [].slice.call(arr)
}
-function fromObject (obj) {
- if (Buffer.isBuffer(obj)) {
- var len = checked(obj.length) | 0
- var buf = createBuffer(len)
+module.exports = nanohtmlRawBrowser
- if (buf.length === 0) {
- return buf
- }
+},{}],103:[function(require,module,exports){
+'use strict'
- obj.copy(buf, 0, 0, len)
- return buf
- }
+module.exports = [
+ 'svg', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor',
+ 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile',
+ 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix',
+ 'feComponentTransfer', 'feComposite', 'feConvolveMatrix',
+ 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood',
+ 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage',
+ 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight',
+ 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter',
+ 'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src',
+ 'font-face-uri', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image',
+ 'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph',
+ 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect',
+ 'set', 'stop', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref',
+ 'tspan', 'use', 'view', 'vkern'
+]
- if (obj.length !== undefined) {
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
- return createBuffer(0)
- }
- return fromArrayLike(obj)
- }
+},{}],104:[function(require,module,exports){
+var assert = require('assert')
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
- return fromArrayLike(obj.data)
- }
+var emojis = {
+ trace: '🔍',
+ debug: '🐛',
+ info: '✨',
+ warn: '⚠️',
+ error: '🚨',
+ fatal: '💀'
}
-function checked (length) {
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= K_MAX_LENGTH) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
- }
- return length | 0
+var levels = {
+ trace: 10,
+ debug: 20,
+ info: 30,
+ warn: 40,
+ error: 50,
+ fatal: 60
}
-function SlowBuffer (length) {
- if (+length != length) { // eslint-disable-line eqeqeq
- length = 0
- }
- return Buffer.alloc(+length)
+var defaultColors = {
+ foreground: '#d3c0c8',
+ background: '#2d2d2d',
+ black: '#2d2d2d',
+ red: '#f2777a',
+ green: '#99cc99',
+ yellow: '#ffcc66',
+ blue: '#6699cc',
+ magenta: '#cc99cc',
+ cyan: '#66cccc',
+ white: '#d3d0c8',
+ brightBlack: '#747369'
}
-Buffer.isBuffer = function isBuffer (b) {
- return b != null && b._isBuffer === true &&
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
-}
+module.exports = Nanologger
-Buffer.compare = function compare (a, b) {
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError(
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
- )
- }
+function Nanologger (name, opts) {
+ opts = opts || {}
+ if (!(this instanceof Nanologger)) return new Nanologger(name, opts)
- if (a === b) return 0
+ assert.equal(typeof opts, 'object', 'nanologger: opts should be type object')
- var x = a.length
- var y = b.length
+ this._name = name || ''
+ this._colors = Object.assign({}, defaultColors, opts.colors || {})
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i]
- y = b[i]
- break
- }
+ try {
+ this.logLevel = window.localStorage.getItem('logLevel') || 'info'
+ } catch (e) {
+ this.logLevel = 'info'
}
- if (x < y) return -1
- if (y < x) return 1
- return 0
+ this._logLevel = levels[this.logLevel]
}
-Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'latin1':
- case 'binary':
- case 'base64':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
+Nanologger.prototype.trace = function () {
+ var args = [ 'trace' ]
+ for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
+ this._print.apply(this, args)
}
-Buffer.concat = function concat (list, length) {
- if (!Array.isArray(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
-
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
-
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; ++i) {
- length += list[i].length
- }
- }
-
- var buffer = Buffer.allocUnsafe(length)
- var pos = 0
- for (i = 0; i < list.length; ++i) {
- var buf = list[i]
- if (isInstance(buf, Uint8Array)) {
- buf = Buffer.from(buf)
- }
- if (!Buffer.isBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- buf.copy(buffer, pos)
- pos += buf.length
- }
- return buffer
+Nanologger.prototype.debug = function () {
+ var args = [ 'debug' ]
+ for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
+ this._print.apply(this, args)
}
-function byteLength (string, encoding) {
- if (Buffer.isBuffer(string)) {
- return string.length
- }
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
- return string.byteLength
- }
- if (typeof string !== 'string') {
- throw new TypeError(
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
- 'Received type ' + typeof string
- )
- }
+Nanologger.prototype.info = function () {
+ var args = [ 'info' ]
+ for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
+ this._print.apply(this, args)
+}
- var len = string.length
- var mustMatch = (arguments.length > 2 && arguments[2] === true)
- if (!mustMatch && len === 0) return 0
+Nanologger.prototype.warn = function () {
+ var args = [ 'warn' ]
+ for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
+ this._print.apply(this, args)
+}
- // Use a for loop to avoid recursion
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'latin1':
- case 'binary':
- return len
- case 'utf8':
- case 'utf-8':
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) {
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
- }
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
+Nanologger.prototype.error = function () {
+ var args = [ 'error' ]
+ for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
+ this._print.apply(this, args)
}
-Buffer.byteLength = byteLength
-function slowToString (encoding, start, end) {
- var loweredCase = false
+Nanologger.prototype.fatal = function () {
+ var args = [ 'fatal' ]
+ for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
+ this._print.apply(this, args)
+}
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
- // property of a typed array.
+Nanologger.prototype._print = function (level) {
+ if (levels[level] < this._logLevel) return
- // This behaves neither like String nor Uint8Array in that we set start/end
- // to their upper/lower bounds if the value passed is out of range.
- // undefined is handled specially as per ECMA-262 6th Edition,
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
- if (start === undefined || start < 0) {
- start = 0
- }
- // Return early if start > this.length. Done here to prevent potential uint32
- // coercion fail below.
- if (start > this.length) {
- return ''
- }
+ var time = getTimeStamp()
+ var emoji = emojis[level]
+ var name = this._name || 'unknown'
- if (end === undefined || end > this.length) {
- end = this.length
- }
+ var msgColor = (level === 'error' || level.fatal)
+ ? this._colors.red
+ : level === 'warn'
+ ? this._colors.yellow
+ : this._colors.green
- if (end <= 0) {
- return ''
- }
+ var objs = []
+ var args = [ null ]
+ var msg = '%c%s ' + emoji + ' %c%s'
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
- end >>>= 0
- start >>>= 0
+ args.push(color(this._colors.brightBlack), time)
+ args.push(color(this._colors.magenta), name)
- if (end <= start) {
- return ''
+ for (var i = 1, len = arguments.length; i < len; i++) {
+ var arg = arguments[i]
+ if (typeof arg === 'string') {
+ if (i === 1) {
+ // first string argument is in color
+ msg += ' %c%s'
+ args.push(color(msgColor))
+ args.push(arg)
+ } else if (/ms$/.test(arg)) {
+ // arguments finishing with 'ms', grey out
+ msg += ' %c%s'
+ args.push(color(this._colors.brightBlack))
+ args.push(arg)
+ } else {
+ // normal colors
+ msg += ' %c%s'
+ args.push(color(this._colors.white))
+ args.push(arg)
+ }
+ } else if (typeof arg === 'number') {
+ msg += ' %c%d'
+ args.push(color(this._colors.magenta))
+ args.push(arg)
+ } else {
+ objs.push(arg)
+ }
}
- if (!encoding) encoding = 'utf8'
-
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
+ args[0] = msg
+ objs.forEach(function (obj) {
+ args.push(obj)
+ })
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
+ // In IE/Edge console functions don't inherit from Function.prototype
+ // so this is necessary to get all the args applied.
+ Function.prototype.apply.apply(console.log, [console, args])
+}
- case 'ascii':
- return asciiSlice(this, start, end)
+function color (color) {
+ return 'color: ' + color + ';'
+}
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
+function getTimeStamp () {
+ var date = new Date()
+ var hours = pad(date.getHours().toString())
+ var minutes = pad(date.getMinutes().toString())
+ var seconds = pad(date.getSeconds().toString())
+ return hours + ':' + minutes + ':' + seconds
+}
- case 'base64':
- return base64Slice(this, start, end)
+function pad (str) {
+ return str.length !== 2 ? 0 + str : str
+}
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
+},{"assert":37}],105:[function(require,module,exports){
+module.exports = LRU
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase()
- loweredCase = true
- }
- }
+function LRU (opts) {
+ if (!(this instanceof LRU)) return new LRU(opts)
+ if (typeof opts === 'number') opts = {max: opts}
+ if (!opts) opts = {}
+ this.cache = {}
+ this.head = this.tail = null
+ this.length = 0
+ this.max = opts.max || 1000
+ this.maxAge = opts.maxAge || 0
}
-// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
-// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
-// reliably in a browserify context because there could be multiple different
-// copies of the 'buffer' package in use. This method works even for Buffer
-// instances that were created from another copy of the `buffer` package.
-// See: https://github.com/feross/buffer/issues/154
-Buffer.prototype._isBuffer = true
+Object.defineProperty(LRU.prototype, 'keys', {
+ get: function () { return Object.keys(this.cache) }
+})
-function swap (b, n, m) {
- var i = b[n]
- b[n] = b[m]
- b[m] = i
+LRU.prototype.clear = function () {
+ this.cache = {}
+ this.head = this.tail = null
+ this.length = 0
}
-Buffer.prototype.swap16 = function swap16 () {
- var len = this.length
- if (len % 2 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 16-bits')
- }
- for (var i = 0; i < len; i += 2) {
- swap(this, i, i + 1)
- }
- return this
-}
+LRU.prototype.remove = function (key) {
+ if (typeof key !== 'string') key = '' + key
+ if (!this.cache.hasOwnProperty(key)) return
-Buffer.prototype.swap32 = function swap32 () {
- var len = this.length
- if (len % 4 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 32-bits')
- }
- for (var i = 0; i < len; i += 4) {
- swap(this, i, i + 3)
- swap(this, i + 1, i + 2)
- }
- return this
+ var element = this.cache[key]
+ delete this.cache[key]
+ this._unlink(key, element.prev, element.next)
+ return element.value
}
-Buffer.prototype.swap64 = function swap64 () {
- var len = this.length
- if (len % 8 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 64-bits')
- }
- for (var i = 0; i < len; i += 8) {
- swap(this, i, i + 7)
- swap(this, i + 1, i + 6)
- swap(this, i + 2, i + 5)
- swap(this, i + 3, i + 4)
+LRU.prototype._unlink = function (key, prev, next) {
+ this.length--
+
+ if (this.length === 0) {
+ this.head = this.tail = null
+ } else {
+ if (this.head === key) {
+ this.head = prev
+ this.cache[this.head].next = null
+ } else if (this.tail === key) {
+ this.tail = next
+ this.cache[this.tail].prev = null
+ } else {
+ this.cache[prev].next = next
+ this.cache[next].prev = prev
+ }
}
- return this
}
-Buffer.prototype.toString = function toString () {
- var length = this.length
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
-}
+LRU.prototype.peek = function (key) {
+ if (!this.cache.hasOwnProperty(key)) return
-Buffer.prototype.toLocaleString = Buffer.prototype.toString
+ var element = this.cache[key]
-Buffer.prototype.equals = function equals (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
+ if (!this._checkAge(key, element)) return
+ return element.value
}
-Buffer.prototype.inspect = function inspect () {
- var str = ''
- var max = exports.INSPECT_MAX_BYTES
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
- if (this.length > max) str += ' ... '
- return ''
-}
+LRU.prototype.set = function (key, value) {
+ if (typeof key !== 'string') key = '' + key
-Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
- if (isInstance(target, Uint8Array)) {
- target = Buffer.from(target, target.offset, target.byteLength)
- }
- if (!Buffer.isBuffer(target)) {
- throw new TypeError(
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
- 'Received type ' + (typeof target)
- )
- }
+ var element
- if (start === undefined) {
- start = 0
- }
- if (end === undefined) {
- end = target ? target.length : 0
- }
- if (thisStart === undefined) {
- thisStart = 0
- }
- if (thisEnd === undefined) {
- thisEnd = this.length
- }
+ if (this.cache.hasOwnProperty(key)) {
+ element = this.cache[key]
+ element.value = value
+ if (this.maxAge) element.modified = Date.now()
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
- throw new RangeError('out of range index')
- }
+ // If it's already the head, there's nothing more to do:
+ if (key === this.head) return value
+ this._unlink(key, element.prev, element.next)
+ } else {
+ element = {value: value, modified: 0, next: null, prev: null}
+ if (this.maxAge) element.modified = Date.now()
+ this.cache[key] = element
- if (thisStart >= thisEnd && start >= end) {
- return 0
- }
- if (thisStart >= thisEnd) {
- return -1
- }
- if (start >= end) {
- return 1
+ // Eviction is only possible if the key didn't already exist:
+ if (this.length === this.max) this.evict()
}
- start >>>= 0
- end >>>= 0
- thisStart >>>= 0
- thisEnd >>>= 0
+ this.length++
+ element.next = null
+ element.prev = this.head
- if (this === target) return 0
+ if (this.head) this.cache[this.head].next = key
+ this.head = key
- var x = thisEnd - thisStart
- var y = end - start
- var len = Math.min(x, y)
+ if (!this.tail) this.tail = key
+ return value
+}
- var thisCopy = this.slice(thisStart, thisEnd)
- var targetCopy = target.slice(start, end)
+LRU.prototype._checkAge = function (key, element) {
+ if (this.maxAge && (Date.now() - element.modified) > this.maxAge) {
+ this.remove(key)
+ return false
+ }
+ return true
+}
- for (var i = 0; i < len; ++i) {
- if (thisCopy[i] !== targetCopy[i]) {
- x = thisCopy[i]
- y = targetCopy[i]
- break
+LRU.prototype.get = function (key) {
+ if (typeof key !== 'string') key = '' + key
+ if (!this.cache.hasOwnProperty(key)) return
+
+ var element = this.cache[key]
+
+ if (!this._checkAge(key, element)) return
+
+ if (this.head !== key) {
+ if (key === this.tail) {
+ this.tail = element.next
+ this.cache[this.tail].prev = null
+ } else {
+ // Set prev.next -> element.next:
+ this.cache[element.prev].next = element.next
}
+
+ // Set element.next.prev -> element.prev:
+ this.cache[element.next].prev = element.prev
+
+ // Element is the new head
+ this.cache[this.head].next = key
+ element.prev = this.head
+ element.next = null
+ this.head = key
}
- if (x < y) return -1
- if (y < x) return 1
- return 0
+ return element.value
}
-// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
-// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+LRU.prototype.evict = function () {
+ if (!this.tail) return
+ this.remove(this.tail)
+}
+
+},{}],106:[function(require,module,exports){
+var assert = require('nanoassert')
+var morph = require('./lib/morph')
+
+var TEXT_NODE = 3
+// var DEBUG = false
+
+module.exports = nanomorph
+
+// Morph one tree into another tree
//
-// Arguments:
-// - buffer - a Buffer to search
-// - val - a string, Buffer, or number
-// - byteOffset - an index into `buffer`; will be clamped to an int32
-// - encoding - an optional encoding, relevant is val is a string
-// - dir - true for indexOf, false for lastIndexOf
-function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
- // Empty buffer means no match
- if (buffer.length === 0) return -1
+// no parent
+// -> same: diff and walk children
+// -> not same: replace and return
+// old node doesn't exist
+// -> insert new node
+// new node doesn't exist
+// -> delete old node
+// nodes are not the same
+// -> diff nodes and apply patch to old node
+// nodes are the same
+// -> walk all child nodes and append to old node
+function nanomorph (oldTree, newTree, options) {
+ // if (DEBUG) {
+ // console.log(
+ // 'nanomorph\nold\n %s\nnew\n %s',
+ // oldTree && oldTree.outerHTML,
+ // newTree && newTree.outerHTML
+ // )
+ // }
+ assert.equal(typeof oldTree, 'object', 'nanomorph: oldTree should be an object')
+ assert.equal(typeof newTree, 'object', 'nanomorph: newTree should be an object')
- // Normalize byteOffset
- if (typeof byteOffset === 'string') {
- encoding = byteOffset
- byteOffset = 0
- } else if (byteOffset > 0x7fffffff) {
- byteOffset = 0x7fffffff
- } else if (byteOffset < -0x80000000) {
- byteOffset = -0x80000000
- }
- byteOffset = +byteOffset // Coerce to Number.
- if (numberIsNaN(byteOffset)) {
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
- byteOffset = dir ? 0 : (buffer.length - 1)
+ if (options && options.childrenOnly) {
+ updateChildren(newTree, oldTree)
+ return oldTree
}
- // Normalize byteOffset: negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset
- if (byteOffset >= buffer.length) {
- if (dir) return -1
- else byteOffset = buffer.length - 1
- } else if (byteOffset < 0) {
- if (dir) byteOffset = 0
- else return -1
- }
+ assert.notEqual(
+ newTree.nodeType,
+ 11,
+ 'nanomorph: newTree should have one root node (which is not a DocumentFragment)'
+ )
- // Normalize val
- if (typeof val === 'string') {
- val = Buffer.from(val, encoding)
- }
+ return walk(newTree, oldTree)
+}
- // Finally, search either indexOf (if dir is true) or lastIndexOf
- if (Buffer.isBuffer(val)) {
- // Special case: looking for empty string/buffer always fails
- if (val.length === 0) {
- return -1
- }
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
- } else if (typeof val === 'number') {
- val = val & 0xFF // Search for a byte value [0-255]
- if (typeof Uint8Array.prototype.indexOf === 'function') {
- if (dir) {
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
- } else {
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
- }
- }
- return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
+// Walk and morph a dom tree
+function walk (newNode, oldNode) {
+ // if (DEBUG) {
+ // console.log(
+ // 'walk\nold\n %s\nnew\n %s',
+ // oldNode && oldNode.outerHTML,
+ // newNode && newNode.outerHTML
+ // )
+ // }
+ if (!oldNode) {
+ return newNode
+ } else if (!newNode) {
+ return null
+ } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) {
+ return oldNode
+ } else if (newNode.tagName !== oldNode.tagName || getComponentId(newNode) !== getComponentId(oldNode)) {
+ return newNode
+ } else {
+ morph(newNode, oldNode)
+ updateChildren(newNode, oldNode)
+ return oldNode
}
+}
- throw new TypeError('val must be string, number or Buffer')
+function getComponentId (node) {
+ return node.dataset ? node.dataset.nanomorphComponentId : undefined
}
-function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
- var indexSize = 1
- var arrLength = arr.length
- var valLength = val.length
+// Update the children of elements
+// (obj, obj) -> null
+function updateChildren (newNode, oldNode) {
+ // if (DEBUG) {
+ // console.log(
+ // 'updateChildren\nold\n %s\nnew\n %s',
+ // oldNode && oldNode.outerHTML,
+ // newNode && newNode.outerHTML
+ // )
+ // }
+ var oldChild, newChild, morphed, oldMatch
- if (encoding !== undefined) {
- encoding = String(encoding).toLowerCase()
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
- encoding === 'utf16le' || encoding === 'utf-16le') {
- if (arr.length < 2 || val.length < 2) {
- return -1
+ // The offset is only ever increased, and used for [i - offset] in the loop
+ var offset = 0
+
+ for (var i = 0; ; i++) {
+ oldChild = oldNode.childNodes[i]
+ newChild = newNode.childNodes[i - offset]
+ // if (DEBUG) {
+ // console.log(
+ // '===\n- old\n %s\n- new\n %s',
+ // oldChild && oldChild.outerHTML,
+ // newChild && newChild.outerHTML
+ // )
+ // }
+ // Both nodes are empty, do nothing
+ if (!oldChild && !newChild) {
+ break
+
+ // There is no new child, remove old
+ } else if (!newChild) {
+ oldNode.removeChild(oldChild)
+ i--
+
+ // There is no old child, add new
+ } else if (!oldChild) {
+ oldNode.appendChild(newChild)
+ offset++
+
+ // Both nodes are the same, morph
+ } else if (same(newChild, oldChild)) {
+ morphed = walk(newChild, oldChild)
+ if (morphed !== oldChild) {
+ oldNode.replaceChild(morphed, oldChild)
+ offset++
}
- indexSize = 2
- arrLength /= 2
- valLength /= 2
- byteOffset /= 2
- }
- }
- function read (buf, i) {
- if (indexSize === 1) {
- return buf[i]
+ // Both nodes do not share an ID or a placeholder, try reorder
} else {
- return buf.readUInt16BE(i * indexSize)
- }
- }
+ oldMatch = null
- var i
- if (dir) {
- var foundIndex = -1
- for (i = byteOffset; i < arrLength; i++) {
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
- if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
- } else {
- if (foundIndex !== -1) i -= i - foundIndex
- foundIndex = -1
- }
- }
- } else {
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
- for (i = byteOffset; i >= 0; i--) {
- var found = true
- for (var j = 0; j < valLength; j++) {
- if (read(arr, i + j) !== read(val, j)) {
- found = false
+ // Try and find a similar node somewhere in the tree
+ for (var j = i; j < oldNode.childNodes.length; j++) {
+ if (same(oldNode.childNodes[j], newChild)) {
+ oldMatch = oldNode.childNodes[j]
break
}
}
- if (found) return i
- }
- }
-
- return -1
-}
-
-Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
- return this.indexOf(val, byteOffset, encoding) !== -1
-}
-Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
-}
+ // If there was a node with the same ID or placeholder in the old list
+ if (oldMatch) {
+ morphed = walk(newChild, oldMatch)
+ if (morphed !== oldMatch) offset++
+ oldNode.insertBefore(morphed, oldChild)
-Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
-}
+ // It's safe to morph two nodes in-place if neither has an ID
+ } else if (!newChild.id && !oldChild.id) {
+ morphed = walk(newChild, oldChild)
+ if (morphed !== oldChild) {
+ oldNode.replaceChild(morphed, oldChild)
+ offset++
+ }
-function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0
- var remaining = buf.length - offset
- if (!length) {
- length = remaining
- } else {
- length = Number(length)
- if (length > remaining) {
- length = remaining
+ // Insert the node at the index if we couldn't morph or find a matching node
+ } else {
+ oldNode.insertBefore(newChild, oldChild)
+ offset++
+ }
}
}
-
- var strLen = string.length
-
- if (length > strLen / 2) {
- length = strLen / 2
- }
- for (var i = 0; i < length; ++i) {
- var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (numberIsNaN(parsed)) return i
- buf[offset + i] = parsed
- }
- return i
-}
-
-function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
-function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
+function same (a, b) {
+ if (a.id) return a.id === b.id
+ if (a.isSameNode) return a.isSameNode(b)
+ if (a.tagName !== b.tagName) return false
+ if (a.type === TEXT_NODE) return a.nodeValue === b.nodeValue
+ return false
}
-function latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
-}
+},{"./lib/morph":108,"nanoassert":93}],107:[function(require,module,exports){
+module.exports = [
+ // attribute events (can be set with attributes)
+ 'onclick',
+ 'ondblclick',
+ 'onmousedown',
+ 'onmouseup',
+ 'onmouseover',
+ 'onmousemove',
+ 'onmouseout',
+ 'onmouseenter',
+ 'onmouseleave',
+ 'ontouchcancel',
+ 'ontouchend',
+ 'ontouchmove',
+ 'ontouchstart',
+ 'ondragstart',
+ 'ondrag',
+ 'ondragenter',
+ 'ondragleave',
+ 'ondragover',
+ 'ondrop',
+ 'ondragend',
+ 'onkeydown',
+ 'onkeypress',
+ 'onkeyup',
+ 'onunload',
+ 'onabort',
+ 'onerror',
+ 'onresize',
+ 'onscroll',
+ 'onselect',
+ 'onchange',
+ 'onsubmit',
+ 'onreset',
+ 'onfocus',
+ 'onblur',
+ 'oninput',
+ // other common events
+ 'oncontextmenu',
+ 'onfocusin',
+ 'onfocusout'
+]
-function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
-}
+},{}],108:[function(require,module,exports){
+var events = require('./events')
+var eventsLength = events.length
-function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
-}
+var ELEMENT_NODE = 1
+var TEXT_NODE = 3
+var COMMENT_NODE = 8
-Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8'
- length = this.length
- offset = 0
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset
- length = this.length
- offset = 0
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset >>> 0
- if (isFinite(length)) {
- length = length >>> 0
- if (encoding === undefined) encoding = 'utf8'
- } else {
- encoding = length
- length = undefined
- }
- } else {
- throw new Error(
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
- )
- }
+module.exports = morph
- var remaining = this.length - offset
- if (length === undefined || length > remaining) length = remaining
+// diff elements and apply the resulting patch to the old node
+// (obj, obj) -> null
+function morph (newNode, oldNode) {
+ var nodeType = newNode.nodeType
+ var nodeName = newNode.nodeName
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('Attempt to write outside buffer bounds')
+ if (nodeType === ELEMENT_NODE) {
+ copyAttrs(newNode, oldNode)
}
- if (!encoding) encoding = 'utf8'
-
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
+ if (nodeType === TEXT_NODE || nodeType === COMMENT_NODE) {
+ if (oldNode.nodeValue !== newNode.nodeValue) {
+ oldNode.nodeValue = newNode.nodeValue
+ }
+ }
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
+ // Some DOM nodes are weird
+ // https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js
+ if (nodeName === 'INPUT') updateInput(newNode, oldNode)
+ else if (nodeName === 'OPTION') updateOption(newNode, oldNode)
+ else if (nodeName === 'TEXTAREA') updateTextarea(newNode, oldNode)
- case 'ascii':
- return asciiWrite(this, string, offset, length)
+ copyEvents(newNode, oldNode)
+}
- case 'latin1':
- case 'binary':
- return latin1Write(this, string, offset, length)
+function copyAttrs (newNode, oldNode) {
+ var oldAttrs = oldNode.attributes
+ var newAttrs = newNode.attributes
+ var attrNamespaceURI = null
+ var attrValue = null
+ var fromValue = null
+ var attrName = null
+ var attr = null
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
+ for (var i = newAttrs.length - 1; i >= 0; --i) {
+ attr = newAttrs[i]
+ attrName = attr.name
+ attrNamespaceURI = attr.namespaceURI
+ attrValue = attr.value
+ if (attrNamespaceURI) {
+ attrName = attr.localName || attrName
+ fromValue = oldNode.getAttributeNS(attrNamespaceURI, attrName)
+ if (fromValue !== attrValue) {
+ oldNode.setAttributeNS(attrNamespaceURI, attrName, attrValue)
+ }
+ } else {
+ if (!oldNode.hasAttribute(attrName)) {
+ oldNode.setAttribute(attrName, attrValue)
+ } else {
+ fromValue = oldNode.getAttribute(attrName)
+ if (fromValue !== attrValue) {
+ // apparently values are always cast to strings, ah well
+ if (attrValue === 'null' || attrValue === 'undefined') {
+ oldNode.removeAttribute(attrName)
+ } else {
+ oldNode.setAttribute(attrName, attrValue)
+ }
+ }
+ }
+ }
+ }
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
+ // Remove any extra attributes found on the original DOM element that
+ // weren't found on the target element.
+ for (var j = oldAttrs.length - 1; j >= 0; --j) {
+ attr = oldAttrs[j]
+ if (attr.specified !== false) {
+ attrName = attr.name
+ attrNamespaceURI = attr.namespaceURI
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
+ if (attrNamespaceURI) {
+ attrName = attr.localName || attrName
+ if (!newNode.hasAttributeNS(attrNamespaceURI, attrName)) {
+ oldNode.removeAttributeNS(attrNamespaceURI, attrName)
+ }
+ } else {
+ if (!newNode.hasAttributeNS(null, attrName)) {
+ oldNode.removeAttribute(attrName)
+ }
+ }
}
}
}
-Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
+function copyEvents (newNode, oldNode) {
+ for (var i = 0; i < eventsLength; i++) {
+ var ev = events[i]
+ if (newNode[ev]) { // if new element has a whitelisted attribute
+ oldNode[ev] = newNode[ev] // update existing element
+ } else if (oldNode[ev]) { // if existing element has it and new one doesnt
+ oldNode[ev] = undefined // remove it from existing element
+ }
}
}
-function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return base64.fromByteArray(buf)
- } else {
- return base64.fromByteArray(buf.slice(start, end))
- }
+function updateOption (newNode, oldNode) {
+ updateAttribute(newNode, oldNode, 'selected')
}
-function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end)
- var res = []
+// The "value" attribute is special for the element since it sets the
+// initial value. Changing the "value" attribute without changing the "value"
+// property will have no effect since it is only used to the set the initial
+// value. Similar for the "checked" attribute, and "disabled".
+function updateInput (newNode, oldNode) {
+ var newValue = newNode.value
+ var oldValue = oldNode.value
- var i = start
- while (i < end) {
- var firstByte = buf[i]
- var codePoint = null
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
+ updateAttribute(newNode, oldNode, 'checked')
+ updateAttribute(newNode, oldNode, 'disabled')
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint
+ // The "indeterminate" property can not be set using an HTML attribute.
+ // See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
+ if (newNode.indeterminate !== oldNode.indeterminate) {
+ oldNode.indeterminate = newNode.indeterminate
+ }
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte
- }
- break
- case 2:
- secondByte = buf[i + 1]
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint
- }
- }
- break
- case 3:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint
- }
- }
- break
- case 4:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- fourthByte = buf[i + 3]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint
- }
- }
- }
- }
+ // Persist file value since file inputs can't be changed programatically
+ if (oldNode.type === 'file') return
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD
- bytesPerSequence = 1
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000
- res.push(codePoint >>> 10 & 0x3FF | 0xD800)
- codePoint = 0xDC00 | codePoint & 0x3FF
- }
+ if (newValue !== oldValue) {
+ oldNode.setAttribute('value', newValue)
+ oldNode.value = newValue
+ }
- res.push(codePoint)
- i += bytesPerSequence
+ if (newValue === 'null') {
+ oldNode.value = ''
+ oldNode.removeAttribute('value')
}
- return decodeCodePointsArray(res)
+ if (!newNode.hasAttributeNS(null, 'value')) {
+ oldNode.removeAttribute('value')
+ } else if (oldNode.type === 'range') {
+ // this is so elements like slider move their UI thingy
+ oldNode.value = newValue
+ }
}
-// Based on http://stackoverflow.com/a/22747272/680742, the browser with
-// the lowest limit is Chrome, with 0x10000 args.
-// We go 1 magnitude less, for safety
-var MAX_ARGUMENTS_LENGTH = 0x1000
-
-function decodeCodePointsArray (codePoints) {
- var len = codePoints.length
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
+function updateTextarea (newNode, oldNode) {
+ var newValue = newNode.value
+ if (newValue !== oldNode.value) {
+ oldNode.value = newValue
}
- // Decode in chunks to avoid "call stack size exceeded".
- var res = ''
- var i = 0
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- )
+ if (oldNode.firstChild && oldNode.firstChild.nodeValue !== newValue) {
+ // Needed for IE. Apparently IE sets the placeholder as the
+ // node value and vise versa. This ignores an empty update.
+ if (newValue === '' && oldNode.firstChild.nodeValue === oldNode.placeholder) {
+ return
+ }
+
+ oldNode.firstChild.nodeValue = newValue
}
- return res
}
-function asciiSlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
-
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i] & 0x7F)
+function updateAttribute (newNode, oldNode, name) {
+ if (newNode[name] !== oldNode[name]) {
+ oldNode[name] = newNode[name]
+ if (newNode[name]) {
+ oldNode.setAttribute(name, '')
+ } else {
+ oldNode.removeAttribute(name)
+ }
}
- return ret
}
-function latin1Slice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
+},{"./events":107}],109:[function(require,module,exports){
+var reg = /([^?=&]+)(=([^&]*))?/g
+var assert = require('assert')
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i])
- }
- return ret
-}
+module.exports = qs
-function hexSlice (buf, start, end) {
- var len = buf.length
+function qs (url) {
+ assert.equal(typeof url, 'string', 'nanoquery: url should be type string')
- if (!start || start < 0) start = 0
- if (!end || end < 0 || end > len) end = len
+ var obj = {}
+ url.replace(/^.*\?/, '').replace(reg, function (a0, a1, a2, a3) {
+ var value = decodeURIComponent(a3)
+ var key = decodeURIComponent(a1)
+ if (obj.hasOwnProperty(key)) {
+ if (Array.isArray(obj[key])) obj[key].push(value)
+ else obj[key] = [obj[key], value]
+ } else {
+ obj[key] = value
+ }
+ })
- var out = ''
- for (var i = start; i < end; ++i) {
- out += toHex(buf[i])
- }
- return out
+ return obj
}
-function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
- }
- return res
-}
+},{"assert":93}],110:[function(require,module,exports){
+'use strict'
-Buffer.prototype.slice = function slice (start, end) {
- var len = this.length
- start = ~~start
- end = end === undefined ? len : ~~end
+var assert = require('assert')
+
+module.exports = nanoraf
+
+// Only call RAF when needed
+// (fn, fn?) -> fn
+function nanoraf (render, raf) {
+ assert.equal(typeof render, 'function', 'nanoraf: render should be a function')
+ assert.ok(typeof raf === 'function' || typeof raf === 'undefined', 'nanoraf: raf should be a function or undefined')
+
+ if (!raf) raf = window.requestAnimationFrame
+ var redrawScheduled = false
+ var args = null
+
+ return function frame () {
+ if (args === null && !redrawScheduled) {
+ redrawScheduled = true
- if (start < 0) {
- start += len
- if (start < 0) start = 0
- } else if (start > len) {
- start = len
- }
+ raf(function redraw () {
+ redrawScheduled = false
- if (end < 0) {
- end += len
- if (end < 0) end = 0
- } else if (end > len) {
- end = len
- }
+ var length = args.length
+ var _args = new Array(length)
+ for (var i = 0; i < length; i++) _args[i] = args[i]
- if (end < start) end = start
+ render.apply(render, _args)
+ args = null
+ })
+ }
- var newBuf = this.subarray(start, end)
- // Return an augmented `Uint8Array` instance
- newBuf.__proto__ = Buffer.prototype
- return newBuf
+ args = arguments
+ }
}
-/*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
-function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
-}
+},{"assert":93}],111:[function(require,module,exports){
+var assert = require('assert')
+var wayfarer = require('wayfarer')
-Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
+// electron support
+var isLocalFile = (/file:\/\//.test(
+ typeof window === 'object' &&
+ window.location &&
+ window.location.origin
+))
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
+/* eslint-disable no-useless-escape */
+var electron = '^(file:\/\/|\/)(.*\.html?\/?)?'
+var protocol = '^(http(s)?(:\/\/))?(www\.)?'
+var domain = '[a-zA-Z0-9-_\.]+(:[0-9]{1,5})?(\/{1})?'
+var qs = '[\?].*$'
+/* eslint-enable no-useless-escape */
- return val
-}
+var stripElectron = new RegExp(electron)
+var prefix = new RegExp(protocol + domain)
+var normalize = new RegExp('#')
+var suffix = new RegExp(qs)
-Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length)
- }
+module.exports = Nanorouter
- var val = this[offset + --byteLength]
- var mul = 1
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul
- }
+function Nanorouter (opts) {
+ if (!(this instanceof Nanorouter)) return new Nanorouter(opts)
+ opts = opts || {}
+ this.router = wayfarer(opts.default || '/404')
+}
- return val
+Nanorouter.prototype.on = function (routename, listener) {
+ assert.equal(typeof routename, 'string')
+ routename = routename.replace(/^[#/]/, '')
+ this.router.on(routename, listener)
}
-Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
+Nanorouter.prototype.emit = function (routename) {
+ assert.equal(typeof routename, 'string')
+ routename = pathname(routename, isLocalFile)
+ return this.router.emit(routename)
}
-Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return this[offset] | (this[offset + 1] << 8)
+Nanorouter.prototype.match = function (routename) {
+ assert.equal(typeof routename, 'string')
+ routename = pathname(routename, isLocalFile)
+ return this.router.match(routename)
}
-Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
+// replace everything in a route but the pathname and hash
+function pathname (routename, isElectron) {
+ if (isElectron) routename = routename.replace(stripElectron, '')
+ else routename = routename.replace(prefix, '')
+ return decodeURI(routename.replace(suffix, '').replace(normalize, '/'))
}
-Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
+},{"assert":93,"wayfarer":132}],112:[function(require,module,exports){
+var assert = require('assert')
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
-}
+var hasWindow = typeof window !== 'undefined'
-Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
+function createScheduler () {
+ var scheduler
+ if (hasWindow) {
+ if (!window._nanoScheduler) window._nanoScheduler = new NanoScheduler(true)
+ scheduler = window._nanoScheduler
+ } else {
+ scheduler = new NanoScheduler()
+ }
+ return scheduler
+}
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
+function NanoScheduler (hasWindow) {
+ this.hasWindow = hasWindow
+ this.hasIdle = this.hasWindow && window.requestIdleCallback
+ this.method = this.hasIdle ? window.requestIdleCallback.bind(window) : this.setTimeout
+ this.scheduled = false
+ this.queue = []
}
-Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
+NanoScheduler.prototype.push = function (cb) {
+ assert.equal(typeof cb, 'function', 'nanoscheduler.push: cb should be type function')
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- mul *= 0x80
+ this.queue.push(cb)
+ this.schedule()
+}
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+NanoScheduler.prototype.schedule = function () {
+ if (this.scheduled) return
- return val
+ this.scheduled = true
+ var self = this
+ this.method(function (idleDeadline) {
+ var cb
+ while (self.queue.length && idleDeadline.timeRemaining() > 0) {
+ cb = self.queue.shift()
+ cb(idleDeadline)
+ }
+ self.scheduled = false
+ if (self.queue.length) self.schedule()
+ })
}
-Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
+NanoScheduler.prototype.setTimeout = function (cb) {
+ setTimeout(cb, 0, {
+ timeRemaining: function () {
+ return 1
+ }
+ })
+}
- var i = byteLength
- var mul = 1
- var val = this[offset + --i]
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul
- }
- mul *= 0x80
+module.exports = createScheduler
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+},{"assert":93}],113:[function(require,module,exports){
+var scheduler = require('nanoscheduler')()
+var assert = require('assert')
- return val
-}
+var perf
+nanotiming.disabled = true
+try {
+ perf = window.performance
+ nanotiming.disabled = window.localStorage.DISABLE_NANOTIMING === 'true' || !perf.mark
+} catch (e) { }
-Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
-}
+module.exports = nanotiming
-Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset] | (this[offset + 1] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
-}
+function nanotiming (name) {
+ assert.equal(typeof name, 'string', 'nanotiming: name should be type string')
-Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset + 1] | (this[offset] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
-}
+ if (nanotiming.disabled) return noop
-Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
+ var uuid = (perf.now() * 10000).toFixed() % Number.MAX_SAFE_INTEGER
+ var startName = 'start-' + uuid + '-' + name
+ perf.mark(startName)
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
-}
+ function end (cb) {
+ var endName = 'end-' + uuid + '-' + name
+ perf.mark(endName)
-Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
+ scheduler.push(function () {
+ var err = null
+ try {
+ var measureName = name + ' [' + uuid + ']'
+ perf.measure(measureName, startName, endName)
+ perf.clearMarks(startName)
+ perf.clearMarks(endName)
+ } catch (e) { err = e }
+ if (cb) cb(err, name)
+ })
+ }
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
+ end.uuid = uuid
+ return end
}
-Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, true, 23, 4)
+function noop (cb) {
+ if (cb) {
+ scheduler.push(function () {
+ cb(new Error('nanotiming: performance API unavailable'))
+ })
+ }
}
-Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, false, 23, 4)
-}
+},{"assert":93,"nanoscheduler":112}],114:[function(require,module,exports){
+/*
+object-assign
+(c) Sindre Sorhus
+@license MIT
+*/
-Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, true, 52, 8)
-}
+'use strict';
+/* eslint-disable no-unused-vars */
+var getOwnPropertySymbols = Object.getOwnPropertySymbols;
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+var propIsEnumerable = Object.prototype.propertyIsEnumerable;
-Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, false, 52, 8)
-}
+function toObject(val) {
+ if (val === null || val === undefined) {
+ throw new TypeError('Object.assign cannot be called with null or undefined');
+ }
-function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
+ return Object(val);
}
-Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
+function shouldUseNative() {
+ try {
+ if (!Object.assign) {
+ return false;
+ }
- var mul = 1
- var i = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
+ // Detect buggy property enumeration order in older V8 versions.
- return offset + byteLength
-}
+ // https://bugs.chromium.org/p/v8/issues/detail?id=4118
+ var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
+ test1[5] = 'de';
+ if (Object.getOwnPropertyNames(test1)[0] === '5') {
+ return false;
+ }
-Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
+ var test2 = {};
+ for (var i = 0; i < 10; i++) {
+ test2['_' + String.fromCharCode(i)] = i;
+ }
+ var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
+ return test2[n];
+ });
+ if (order2.join('') !== '0123456789') {
+ return false;
+ }
- var i = byteLength - 1
- var mul = 1
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
+ var test3 = {};
+ 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
+ test3[letter] = letter;
+ });
+ if (Object.keys(Object.assign({}, test3)).join('') !==
+ 'abcdefghijklmnopqrst') {
+ return false;
+ }
- return offset + byteLength
+ return true;
+ } catch (err) {
+ // We don't expect any of the above to throw, but better to be safe.
+ return false;
+ }
}
-Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- this[offset] = (value & 0xff)
- return offset + 1
-}
+module.exports = shouldUseNative() ? Object.assign : function (target, source) {
+ var from;
+ var to = toObject(target);
+ var symbols;
-Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- return offset + 2
-}
+ for (var s = 1; s < arguments.length; s++) {
+ from = Object(arguments[s]);
-Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- return offset + 2
-}
+ for (var key in from) {
+ if (hasOwnProperty.call(from, key)) {
+ to[key] = from[key];
+ }
+ }
-Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- return offset + 4
-}
+ if (getOwnPropertySymbols) {
+ symbols = getOwnPropertySymbols(from);
+ for (var i = 0; i < symbols.length; i++) {
+ if (propIsEnumerable.call(from, symbols[i])) {
+ to[symbols[i]] = from[symbols[i]];
+ }
+ }
+ }
+ }
-Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- return offset + 4
-}
+ return to;
+};
-Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- var limit = Math.pow(2, (8 * byteLength) - 1)
+},{}],115:[function(require,module,exports){
+var assert = require('assert')
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
+module.exports = objectChangeCallsite
- var i = 0
- var mul = 1
- var sub = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
+function objectChangeCallsite (target, callback) {
+ assert.equal(typeof target, 'object', 'object-change-callsite: target should be type object')
+ assert.equal(typeof callback, 'function', 'object-change-callsite: callback should be type function')
- return offset + byteLength
+ return new Proxy(target, {
+ set: function (obj, prop, value) {
+ var err = new Error()
+ var trace = strip(err.stack)
+ callback(prop, value, trace)
+ obj[prop] = value
+ return true
+ },
+ deleteProperty: function (target, prop) {
+ var err = new Error()
+ var trace = strip(err.stack)
+ callback(prop, undefined, trace)
+ if (prop in target) {
+ delete target[prop]
+ return true
+ }
+ return false
+ }
+ })
}
-Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- var limit = Math.pow(2, (8 * byteLength) - 1)
+function strip (str) {
+ var arr = str.split('\n')
+ arr = arr.length > 2 ? arr.slice(2) : arr
+ arr[0] = arr[0].replace(/^ {4}at /, '')
+ return '\n' + arr.join('\n')
+}
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
+},{"assert":37}],116:[function(require,module,exports){
+/* global MutationObserver */
+var document = require('global/document')
+var window = require('global/window')
+var assert = require('assert')
+var watch = Object.create(null)
+var KEY_ID = 'onloadid' + (new Date() % 9e6).toString(36)
+var KEY_ATTR = 'data-' + KEY_ID
+var INDEX = 0
- var i = byteLength - 1
- var mul = 1
- var sub = 0
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
- sub = 1
+if (window && window.MutationObserver) {
+ var observer = new MutationObserver(function (mutations) {
+ if (Object.keys(watch).length < 1) return
+ for (var i = 0; i < mutations.length; i++) {
+ if (mutations[i].attributeName === KEY_ATTR) {
+ eachAttr(mutations[i], turnon, turnoff)
+ continue
+ }
+ eachMutation(mutations[i].removedNodes, turnoff)
+ eachMutation(mutations[i].addedNodes, turnon)
}
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ })
+ if (document.body) {
+ beginObserve(observer)
+ } else {
+ document.addEventListener('DOMContentLoaded', function (event) {
+ beginObserve(observer)
+ })
}
-
- return offset + byteLength
}
-Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (value < 0) value = 0xff + value + 1
- this[offset] = (value & 0xff)
- return offset + 1
+function beginObserve (observer) {
+ observer.observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeOldValue: true,
+ attributeFilter: [KEY_ATTR]
+ })
}
-Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- return offset + 2
+module.exports = function onload (el, on, off, caller) {
+ assert(document.body, 'on-load: will not work prior to DOMContentLoaded')
+ on = on || function () {}
+ off = off || function () {}
+ el.setAttribute(KEY_ATTR, 'o' + INDEX)
+ watch['o' + INDEX] = [on, off, 0, caller || onload.caller]
+ INDEX += 1
+ return el
}
-Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- return offset + 2
+module.exports.KEY_ATTR = KEY_ATTR
+module.exports.KEY_ID = KEY_ID
+
+function turnon (index, el) {
+ if (watch[index][0] && watch[index][2] === 0) {
+ watch[index][0](el)
+ watch[index][2] = 1
+ }
}
-Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- return offset + 4
+function turnoff (index, el) {
+ if (watch[index][1] && watch[index][2] === 1) {
+ watch[index][1](el)
+ watch[index][2] = 0
+ }
}
-Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (value < 0) value = 0xffffffff + value + 1
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- return offset + 4
+function eachAttr (mutation, on, off) {
+ var newValue = mutation.target.getAttribute(KEY_ATTR)
+ if (sameOrigin(mutation.oldValue, newValue)) {
+ watch[newValue] = watch[mutation.oldValue]
+ return
+ }
+ if (watch[mutation.oldValue]) {
+ off(mutation.oldValue, mutation.target)
+ }
+ if (watch[newValue]) {
+ on(newValue, mutation.target)
+ }
}
-function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- if (offset < 0) throw new RangeError('Index out of range')
+function sameOrigin (oldValue, newValue) {
+ if (!oldValue || !newValue) return false
+ return watch[oldValue][3] === watch[newValue][3]
}
-function writeFloat (buf, value, offset, littleEndian, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+function eachMutation (nodes, fn) {
+ var keys = Object.keys(watch)
+ for (var i = 0; i < nodes.length; i++) {
+ if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute(KEY_ATTR)) {
+ var onloadid = nodes[i].getAttribute(KEY_ATTR)
+ keys.forEach(function (k) {
+ if (onloadid === k) {
+ fn(k, nodes[i])
+ }
+ })
+ }
+ if (nodes[i].childNodes.length > 0) {
+ eachMutation(nodes[i].childNodes, fn)
+ }
}
- ieee754.write(buf, value, offset, littleEndian, 23, 4)
- return offset + 4
}
-Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
-}
+},{"assert":93,"global/document":64,"global/window":65}],117:[function(require,module,exports){
+var scheduler = require('nanoscheduler')()
+var assert = require('assert')
-Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
-}
+var entryTypes = [
+ 'frame',
+ 'measure',
+ 'navigation',
+ 'resource',
+ 'longtask'
+]
-function writeDouble (buf, value, offset, littleEndian, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
- }
- ieee754.write(buf, value, offset, littleEndian, 52, 8)
- return offset + 8
-}
+module.exports = onPerformance
-Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
-}
+function onPerformance (cb) {
+ assert.equal(typeof cb, 'function', 'on-performance: cb should be type function')
-Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
-}
+ var PerformanceObserver = typeof window !== 'undefined' && window.PerformanceObserver
+ if (!PerformanceObserver) return
-// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
-Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
- if (!start) start = 0
- if (!end && end !== 0) end = this.length
- if (targetStart >= target.length) targetStart = target.length
- if (!targetStart) targetStart = 0
- if (end > 0 && end < start) end = start
+ // Enable singleton.
+ if (window._onperformance) {
+ window._onperformance.push(cb)
+ return stop
+ }
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
+ window._onperformance = [cb]
+ var observer = new PerformanceObserver(parseEntries)
+ setTimeout(function () {
+ parseEntries(window.performance)
+ observer.observe({ entryTypes: entryTypes })
+ }, 0)
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
+ return stop
+
+ function stop () {
+ window._onperformance.splice(window._onperformance.indexOf(cb), 1)
}
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
- // Are we oob?
- if (end > this.length) end = this.length
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start
+ function parseEntries (list) {
+ list.getEntries().forEach(function (entry) {
+ scheduler.push(function () {
+ clear(entry)
+ window._onperformance.forEach(function (cb) {
+ cb(entry)
+ })
+ })
+ })
}
- var len = end - start
+ // Navigation, longtask and frame don't have a clear method (yet)
+ // Resource timings can only be cleared in bulk
+ // see: https://developer.mozilla.org/en-US/docs/Web/API/Performance/clearMeasures
+ function clear (entry) {
+ var type = entry.entryType
+ if (type === 'measure') window.performance.clearMeasures(entry.name)
+ else if (type === 'resource') window.performance.clearResourceTimings()
+ }
+}
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
- // Use built-in when available, missing from IE11
- this.copyWithin(targetStart, start, end)
- } else if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (var i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start]
- }
+},{"assert":93,"nanoscheduler":112}],118:[function(require,module,exports){
+(function (process){(function (){
+// Generated by CoffeeScript 1.12.2
+(function() {
+ var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
+
+ if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
+ module.exports = function() {
+ return performance.now();
+ };
+ } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
+ module.exports = function() {
+ return (getNanoSeconds() - nodeLoadTime) / 1e6;
+ };
+ hrtime = process.hrtime;
+ getNanoSeconds = function() {
+ var hr;
+ hr = hrtime();
+ return hr[0] * 1e9 + hr[1];
+ };
+ moduleLoadTime = getNanoSeconds();
+ upTime = process.uptime() * 1e9;
+ nodeLoadTime = moduleLoadTime - upTime;
+ } else if (Date.now) {
+ module.exports = function() {
+ return Date.now() - loadTime;
+ };
+ loadTime = Date.now();
} else {
- Uint8Array.prototype.set.call(
- target,
- this.subarray(start, end),
- targetStart
- )
+ module.exports = function() {
+ return new Date().getTime() - loadTime;
+ };
+ loadTime = new Date().getTime();
}
- return len
-}
+}).call(this);
-// Usage:
-// buffer.fill(number[, offset[, end]])
-// buffer.fill(buffer[, offset[, end]])
-// buffer.fill(string[, offset[, end]][, encoding])
-Buffer.prototype.fill = function fill (val, start, end, encoding) {
- // Handle string cases:
- if (typeof val === 'string') {
- if (typeof start === 'string') {
- encoding = start
- start = 0
- end = this.length
- } else if (typeof end === 'string') {
- encoding = end
- end = this.length
- }
- if (encoding !== undefined && typeof encoding !== 'string') {
- throw new TypeError('encoding must be a string')
- }
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- if (val.length === 1) {
- var code = val.charCodeAt(0)
- if ((encoding === 'utf8' && code < 128) ||
- encoding === 'latin1') {
- // Fast path: If `val` fits into a single byte, use that numeric value.
- val = code
- }
- }
- } else if (typeof val === 'number') {
- val = val & 255
- }
- // Invalid ranges are not set to a default, so can range check early.
- if (start < 0 || this.length < start || this.length < end) {
- throw new RangeError('Out of range index')
- }
- if (end <= start) {
- return this
- }
+}).call(this)}).call(this,require('_process'))
+},{"_process":121}],119:[function(require,module,exports){
+module.exports = plucker
- start = start >>> 0
- end = end === undefined ? this.length : end >>> 0
+function plucker(path, object) {
+ return arguments.length >= 2
+ ? pluck(path)(object)
+ : pluck(path)
+}
- if (!val) val = 0
+function pluck(path) {
+ path = typeof path === 'string'
+ ? String(path).trim().split('.')
+ : path
- var i
- if (typeof val === 'number') {
- for (i = start; i < end; ++i) {
- this[i] = val
- }
+ if (path.length < 2) {
+ path = path[0]
+ return pluckSingle
} else {
- var bytes = Buffer.isBuffer(val)
- ? val
- : Buffer.from(val, encoding)
- var len = bytes.length
- if (len === 0) {
- throw new TypeError('The value "' + val +
- '" is invalid for argument "value"')
- }
- for (i = 0; i < end - start; ++i) {
- this[i + start] = bytes[i % len]
- }
+ var l = path.length
+ return pluckPath
}
- return this
-}
+ function pluckSingle(object) {
+ return object[path]
+ }
-// HELPER FUNCTIONS
-// ================
+ function pluckPath(object) {
+ for (var i = 0; i < l; i++) {
+ if (typeof object === 'undefined') break
-var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
+ object = object[path[i]]
+ }
-function base64clean (str) {
- // Node takes equal signs as end of the Base64 encoding
- str = str.split('=')[0]
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = str.trim().replace(INVALID_BASE64_RE, '')
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '='
+ return object
}
- return str
}
-function toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
-}
+},{}],120:[function(require,module,exports){
+module.exports = prettierBytes
-function utf8ToBytes (string, units) {
- units = units || Infinity
- var codePoint
- var length = string.length
- var leadSurrogate = null
- var bytes = []
+function prettierBytes (num) {
+ if (typeof num !== 'number' || isNaN(num)) {
+ throw new TypeError('Expected a number, got ' + typeof num)
+ }
- for (var i = 0; i < length; ++i) {
- codePoint = string.charCodeAt(i)
+ var neg = num < 0
+ var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- }
+ if (neg) {
+ num = -num
+ }
- // valid lead
- leadSurrogate = codePoint
+ if (num < 1) {
+ return (neg ? '-' : '') + num + ' B'
+ }
- continue
- }
+ var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
+ num = Number(num / Math.pow(1000, exponent))
+ var unit = units[exponent]
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- leadSurrogate = codePoint
- continue
- }
+ if (num >= 10 || num % 1 === 0) {
+ // Do not show decimals when the number is two-digit, or if the number has no
+ // decimal component.
+ return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit
+ } else {
+ return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit
+ }
+}
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- }
+},{}],121:[function(require,module,exports){
+// shim for using process in browser
+var process = module.exports = {};
- leadSurrogate = null
+// cached from whatever global is present so that test runners that stub it
+// don't break things. But we need to wrap it in a try catch in case it is
+// wrapped in strict mode code which doesn't define any globals. It's inside a
+// function because try/catches deoptimize in certain engines.
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint)
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else {
- throw new Error('Invalid code point')
- }
- }
+var cachedSetTimeout;
+var cachedClearTimeout;
- return bytes
+function defaultSetTimout() {
+ throw new Error('setTimeout has not been defined');
}
-
-function asciiToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF)
- }
- return byteArray
+function defaultClearTimeout () {
+ throw new Error('clearTimeout has not been defined');
}
+(function () {
+ try {
+ if (typeof setTimeout === 'function') {
+ cachedSetTimeout = setTimeout;
+ } else {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ } catch (e) {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ try {
+ if (typeof clearTimeout === 'function') {
+ cachedClearTimeout = clearTimeout;
+ } else {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+ } catch (e) {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+} ())
+function runTimeout(fun) {
+ if (cachedSetTimeout === setTimeout) {
+ //normal enviroments in sane situations
+ return setTimeout(fun, 0);
+ }
+ // if setTimeout wasn't available but was latter defined
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
+ cachedSetTimeout = setTimeout;
+ return setTimeout(fun, 0);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedSetTimeout(fun, 0);
+ } catch(e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedSetTimeout.call(null, fun, 0);
+ } catch(e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
+ return cachedSetTimeout.call(this, fun, 0);
+ }
+ }
-function utf16leToBytes (str, units) {
- var c, hi, lo
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- if ((units -= 2) < 0) break
-
- c = str.charCodeAt(i)
- hi = c >> 8
- lo = c % 256
- byteArray.push(lo)
- byteArray.push(hi)
- }
- return byteArray
}
+function runClearTimeout(marker) {
+ if (cachedClearTimeout === clearTimeout) {
+ //normal enviroments in sane situations
+ return clearTimeout(marker);
+ }
+ // if clearTimeout wasn't available but was latter defined
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
+ cachedClearTimeout = clearTimeout;
+ return clearTimeout(marker);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedClearTimeout(marker);
+ } catch (e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedClearTimeout.call(null, marker);
+ } catch (e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
+ return cachedClearTimeout.call(this, marker);
+ }
+ }
-function base64ToBytes (str) {
- return base64.toByteArray(base64clean(str))
-}
-function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; ++i) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i]
- }
- return i
-}
-// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
-// the `instanceof` check but they should be treated as of that type.
-// See: https://github.com/feross/buffer/issues/166
-function isInstance (obj, type) {
- return obj instanceof type ||
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
- obj.constructor.name === type.name)
}
-function numberIsNaN (obj) {
- // For IE11 support
- return obj !== obj // eslint-disable-line no-self-compare
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
+
+function cleanUpNextTick() {
+ if (!draining || !currentQueue) {
+ return;
+ }
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
+ }
+ if (queue.length) {
+ drainQueue();
+ }
}
-}).call(this,require("buffer").Buffer)
-},{"base64-js":129,"buffer":131,"ieee754":133}],132:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+function drainQueue() {
+ if (draining) {
+ return;
+ }
+ var timeout = runTimeout(cleanUpNextTick);
+ draining = true;
-var objectCreate = Object.create || objectCreatePolyfill
-var objectKeys = Object.keys || objectKeysPolyfill
-var bind = Function.prototype.bind || functionBindPolyfill
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+ queueIndex = -1;
+ len = queue.length;
+ }
+ currentQueue = null;
+ draining = false;
+ runClearTimeout(timeout);
+}
-function EventEmitter() {
- if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- }
+process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ runTimeout(drainQueue);
+ }
+};
- this._maxListeners = this._maxListeners || undefined;
+// v8 likes predictible objects
+function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
}
-module.exports = EventEmitter;
+Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
+};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
-// Backwards-compat with node 0.10.x
-EventEmitter.EventEmitter = EventEmitter;
+function noop() {}
-EventEmitter.prototype._events = undefined;
-EventEmitter.prototype._maxListeners = undefined;
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+process.prependListener = noop;
+process.prependOnceListener = noop;
-// By default EventEmitters will print a warning if more than 10 listeners are
-// added to it. This is a useful default which helps finding memory leaks.
-var defaultMaxListeners = 10;
+process.listeners = function (name) { return [] }
-var hasDefineProperty;
-try {
- var o = {};
- if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
- hasDefineProperty = o.x === 0;
-} catch (err) { hasDefineProperty = false }
-if (hasDefineProperty) {
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
- enumerable: true,
- get: function() {
- return defaultMaxListeners;
- },
- set: function(arg) {
- // check whether the input is a positive number (whose value is zero or
- // greater and not a NaN).
- if (typeof arg !== 'number' || arg < 0 || arg !== arg)
- throw new TypeError('"defaultMaxListeners" must be a positive number');
- defaultMaxListeners = arg;
- }
- });
-} else {
- EventEmitter.defaultMaxListeners = defaultMaxListeners;
-}
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+};
-// Obviously not all Emitters should be limited to 10. This function allows
-// that to be increased. Set to zero for unlimited.
-EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
- if (typeof n !== 'number' || n < 0 || isNaN(n))
- throw new TypeError('"n" argument must be a positive number');
- this._maxListeners = n;
- return this;
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
};
+process.umask = function() { return 0; };
-function $getMaxListeners(that) {
- if (that._maxListeners === undefined)
- return EventEmitter.defaultMaxListeners;
- return that._maxListeners;
-}
+},{}],122:[function(require,module,exports){
+var inherits = require('inherits')
+var EventEmitter = require('events').EventEmitter
+var now = require('right-now')
+var raf = require('raf')
-EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
- return $getMaxListeners(this);
-};
+module.exports = Engine
+function Engine(fn) {
+ if (!(this instanceof Engine))
+ return new Engine(fn)
+ this.running = false
+ this.last = now()
+ this._frame = 0
+ this._tick = this.tick.bind(this)
-// These standalone emit* functions are used to optimize calling of event
-// handlers for fast cases because emit() itself often has a variable number of
-// arguments and can be deoptimized because of that. These functions always have
-// the same number of arguments and thus do not get deoptimized, so the code
-// inside them can execute faster.
-function emitNone(handler, isFn, self) {
- if (isFn)
- handler.call(self);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self);
- }
-}
-function emitOne(handler, isFn, self, arg1) {
- if (isFn)
- handler.call(self, arg1);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1);
- }
+ if (fn)
+ this.on('tick', fn)
}
-function emitTwo(handler, isFn, self, arg1, arg2) {
- if (isFn)
- handler.call(self, arg1, arg2);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2);
- }
+
+inherits(Engine, EventEmitter)
+
+Engine.prototype.start = function() {
+ if (this.running)
+ return
+ this.running = true
+ this.last = now()
+ this._frame = raf(this._tick)
+ return this
}
-function emitThree(handler, isFn, self, arg1, arg2, arg3) {
- if (isFn)
- handler.call(self, arg1, arg2, arg3);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2, arg3);
- }
+
+Engine.prototype.stop = function() {
+ this.running = false
+ if (this._frame !== 0)
+ raf.cancel(this._frame)
+ this._frame = 0
+ return this
}
-function emitMany(handler, isFn, self, args) {
- if (isFn)
- handler.apply(self, args);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].apply(self, args);
- }
+Engine.prototype.tick = function() {
+ this._frame = raf(this._tick)
+ var time = now()
+ var dt = time - this.last
+ this.emit('tick', dt)
+ this.last = time
}
+},{"events":43,"inherits":91,"raf":123,"right-now":126}],123:[function(require,module,exports){
+(function (global){(function (){
+var now = require('performance-now')
+ , root = typeof window === 'undefined' ? global : window
+ , vendors = ['moz', 'webkit']
+ , suffix = 'AnimationFrame'
+ , raf = root['request' + suffix]
+ , caf = root['cancel' + suffix] || root['cancelRequest' + suffix]
-EventEmitter.prototype.emit = function emit(type) {
- var er, handler, len, args, i, events;
- var doError = (type === 'error');
+for(var i = 0; !raf && i < vendors.length; i++) {
+ raf = root[vendors[i] + 'Request' + suffix]
+ caf = root[vendors[i] + 'Cancel' + suffix]
+ || root[vendors[i] + 'CancelRequest' + suffix]
+}
- events = this._events;
- if (events)
- doError = (doError && events.error == null);
- else if (!doError)
- return false;
+// Some versions of FF have rAF but not cAF
+if(!raf || !caf) {
+ var last = 0
+ , id = 0
+ , queue = []
+ , frameDuration = 1000 / 60
- // If there is no 'error' event listener then throw.
- if (doError) {
- if (arguments.length > 1)
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Unhandled "error" event. (' + er + ')');
- err.context = er;
- throw err;
+ raf = function(callback) {
+ if(queue.length === 0) {
+ var _now = now()
+ , next = Math.max(0, frameDuration - (_now - last))
+ last = next + _now
+ setTimeout(function() {
+ var cp = queue.slice(0)
+ // Clear queue here to prevent
+ // callbacks from appending listeners
+ // to the current frame's queue
+ queue.length = 0
+ for(var i = 0; i < cp.length; i++) {
+ if(!cp[i].cancelled) {
+ try{
+ cp[i].callback(last)
+ } catch(e) {
+ setTimeout(function() { throw e }, 0)
+ }
+ }
+ }
+ }, Math.round(next))
}
- return false;
+ queue.push({
+ handle: ++id,
+ callback: callback,
+ cancelled: false
+ })
+ return id
}
- handler = events[type];
-
- if (!handler)
- return false;
-
- var isFn = typeof handler === 'function';
- len = arguments.length;
- switch (len) {
- // fast cases
- case 1:
- emitNone(handler, isFn, this);
- break;
- case 2:
- emitOne(handler, isFn, this, arguments[1]);
- break;
- case 3:
- emitTwo(handler, isFn, this, arguments[1], arguments[2]);
- break;
- case 4:
- emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
- break;
- // slower
- default:
- args = new Array(len - 1);
- for (i = 1; i < len; i++)
- args[i - 1] = arguments[i];
- emitMany(handler, isFn, this, args);
+ caf = function(handle) {
+ for(var i = 0; i < queue.length; i++) {
+ if(queue[i].handle === handle) {
+ queue[i].cancelled = true
+ }
+ }
}
+}
- return true;
-};
-
-function _addListener(target, type, listener, prepend) {
- var m;
- var events;
- var existing;
-
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
-
- events = target._events;
- if (!events) {
- events = target._events = objectCreate(null);
- target._eventsCount = 0;
- } else {
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (events.newListener) {
- target.emit('newListener', type,
- listener.listener ? listener.listener : listener);
-
- // Re-assign `events` because a newListener handler could have caused the
- // this._events to be assigned to a new object
- events = target._events;
- }
- existing = events[type];
+module.exports = function(fn) {
+ // Wrap in a new function to prevent
+ // `cancel` potentially being assigned
+ // to the native rAF function
+ return raf.call(root, fn)
+}
+module.exports.cancel = function() {
+ caf.apply(root, arguments)
+}
+module.exports.polyfill = function(object) {
+ if (!object) {
+ object = root;
}
+ object.requestAnimationFrame = raf
+ object.cancelAnimationFrame = caf
+}
- if (!existing) {
- // Optimize the case of one listener. Don't need the extra array object.
- existing = events[type] = listener;
- ++target._eventsCount;
- } else {
- if (typeof existing === 'function') {
- // Adding the second element, need to change to array.
- existing = events[type] =
- prepend ? [listener, existing] : [existing, listener];
- } else {
- // If we've already got an array, just append.
- if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- }
+}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"performance-now":118}],124:[function(require,module,exports){
+(function(U,X){"object"===typeof exports&&"undefined"!==typeof module?module.exports=X():"function"===typeof define&&define.amd?define(X):U.createREGL=X()})(this,function(){function U(a,b){this.id=Eb++;this.type=a;this.data=b}function X(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1>>=b;c=(255>>=c;b|=c;c=(15>>=c;b|=c;c=(3>>c>>1}function hb(){function a(a){a:{for(var b=16;268435456>=b;b*=16)if(a<=b){a=b;break a}a=0}b=c[gb(a)>>2];return 0>2].push(a)}var c=J(8,function(){return[]});return{alloc:a,free:b,allocType:function(b,c){var d=null;switch(b){case 5120:d=new Int8Array(a(c),0,c);break;case 5121:d=new Uint8Array(a(c),0,c);break;case 5122:d=new Int16Array(a(2*c),0,c);break;case 5123:d=new Uint16Array(a(2*c),0,c);break;case 5124:d=new Int32Array(a(4*c),0,c);break;case 5125:d=new Uint32Array(a(4*c),0,c);break;case 5126:d=new Float32Array(a(4*c),0,c);break;default:return null}return d.length!==
+c?d.subarray(0,c):d},freeType:function(a){b(a.buffer)}}}function da(a){return!!a&&"object"===typeof a&&Array.isArray(a.shape)&&Array.isArray(a.stride)&&"number"===typeof a.offset&&a.shape.length===a.stride.length&&(Array.isArray(a.data)||M(a.data))}function ib(a,b,c,e,f,d){for(var p=0;pd&&(d=e.buffer.byteLength,5123===m?d>>=1:5125===m&&(d>>=2));e.vertCount=d;d=h;0>h&&(d=4,h=e.buffer.dimension,1===h&&(d=0),2===h&&(d=1),3===h&&(d=4));e.primType=d}function p(a){e.elementsCount--;delete n[a.id];a.buffer.destroy();a.buffer=null}var n={},u=0,t={uint8:5121,uint16:5123};b.oes_element_index_uint&&(t.uint32=5125);f.prototype.bind=function(){this.buffer.bind()};var w=[];return{create:function(a,
+b){function l(a){if(a)if("number"===typeof a)h(a),g.primType=4,g.vertCount=a|0,g.type=5121;else{var b=null,c=35044,e=-1,f=-1,k=0,n=0;if(Array.isArray(a)||M(a)||da(a))b=a;else if("data"in a&&(b=a.data),"usage"in a&&(c=ob[a.usage]),"primitive"in a&&(e=Ta[a.primitive]),"count"in a&&(f=a.count|0),"type"in a&&(n=t[a.type]),"length"in a)k=a.length|0;else if(k=f,5123===n||5122===n)k*=2;else if(5125===n||5124===n)k*=4;d(g,b,c,e,f,k,n)}else h(),g.primType=4,g.vertCount=0,g.type=5121;return l}var h=c.create(null,
+34963,!0),g=new f(h._buffer);e.elementsCount++;l(a);l._reglType="elements";l._elements=g;l.subdata=function(a,b){h.subdata(a,b);return l};l.destroy=function(){p(g)};return l},createStream:function(a){var b=w.pop();b||(b=new f(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){w.push(a)},getElements:function(a){return"function"===typeof a&&a._elements instanceof f?a._elements:null},clear:function(){S(n).forEach(p)}}}function pb(a){for(var b=E.allocType(5123,
+a.length),c=0;c>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?f:-14>d?f+(e+1024>>-14-d):15>=e,c.height>>=e,B(c,g[e]),a.mipmask|=1<b;++b)a.images[b]=null;return a}function nb(a){for(var b=a.images,c=0;cb){for(var c=0;c=--this.refCount&&D(this)}});p.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(ia).forEach(function(b){a+=ia[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;Z.call(c);var g=Ha();"number"===typeof a?"number"===typeof b?r(g,a|0,b|0):r(g,a|0,a|0):a?(G(c,a),m(g,a)):r(g,1,1);c.genMipmaps&&(g.mipmask=(g.width<<1)-1);f.mipmask=g.mipmask;u(f,
+g);f.internalformat=g.internalformat;e.width=g.width;e.height=g.height;xa(f);z(g,3553);H(c,3553);ya();nb(g);p.profile&&(f.stats.size=Ja(f.internalformat,f.type,g.width,g.height,c.genMipmaps,!1));e.format=aa[f.internalformat];e.type=K[f.type];e.mag=fa[c.magFilter];e.min=Da[c.minFilter];e.wrapS=ua[c.wrapS];e.wrapT=ua[c.wrapT];return e}var f=new O(3553);ia[f.id]=f;d.textureCount++;e(b,c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var m=h();u(m,f);m.width=0;m.height=0;B(m,a);m.width=m.width||(f.width>>
+d)-b;m.height=m.height||(f.height>>d)-c;xa(f);l(m,3553,b,c,d);ya();g(m);return e};e.resize=function(b,c){var g=b|0,d=c|0||g;if(g===f.width&&d===f.height)return e;e.width=f.width=g;e.height=f.height=d;xa(f);for(var h=0;f.mipmask>>h;++h){var m=g>>h,x=d>>h;if(!m||!x)break;a.texImage2D(3553,h,f.format,m,x,0,f.format,f.type,null)}ya();p.profile&&(f.stats.size=Ja(f.internalformat,f.type,g,d,!1,!1));return e};e._reglType="texture2d";e._texture=f;p.profile&&(e.stats=f.stats);e.destroy=function(){f.decRef()};
+return e},createCube:function(b,c,e,f,q,n){function k(a,b,c,g,e,d){var f,ca=y.texInfo;Z.call(ca);for(f=0;6>f;++f)D[f]=Ha();if("number"===typeof a||!a)for(a=a|0||1,f=0;6>f;++f)r(D[f],a,a);else if("object"===typeof a)if(b)m(D[0],a),m(D[1],b),m(D[2],c),m(D[3],g),m(D[4],e),m(D[5],d);else if(G(ca,a),t(y,a),"faces"in a)for(a=a.faces,f=0;6>f;++f)u(D[f],y),m(D[f],a[f]);else for(f=0;6>f;++f)m(D[f],a);u(y,D[0]);y.mipmask=ca.genMipmaps?(D[0].width<<1)-1:D[0].mipmask;y.internalformat=D[0].internalformat;k.width=
+D[0].width;k.height=D[0].height;xa(y);for(f=0;6>f;++f)z(D[f],34069+f);H(ca,34067);ya();p.profile&&(y.stats.size=Ja(y.internalformat,y.type,k.width,k.height,ca.genMipmaps,!0));k.format=aa[y.internalformat];k.type=K[y.type];k.mag=fa[ca.magFilter];k.min=Da[ca.minFilter];k.wrapS=ua[ca.wrapS];k.wrapT=ua[ca.wrapT];for(f=0;6>f;++f)nb(D[f]);return k}var y=new O(34067);ia[y.id]=y;d.cubeCount++;var D=Array(6);k(b,c,e,f,q,n);k.subimage=function(a,b,c,e,f){c|=0;e|=0;f|=0;var d=h();u(d,y);d.width=0;d.height=0;
+B(d,b);d.width=d.width||(y.width>>f)-c;d.height=d.height||(y.height>>f)-e;xa(y);l(d,34069+a,c,e,f);ya();g(d);return k};k.resize=function(b){b|=0;if(b!==y.width){k.width=y.width=b;k.height=y.height=b;xa(y);for(var c=0;6>c;++c)for(var g=0;y.mipmask>>g;++g)a.texImage2D(34069+c,g,y.format,b>>g,b>>g,0,y.format,y.type,null);ya();p.profile&&(y.stats.size=Ja(y.internalformat,y.type,k.width,k.height,!1,!0));return k}};k._reglType="textureCube";k._texture=y;p.profile&&(k.stats=y.stats);k.destroy=function(){y.decRef()};
+return k},clear:function(){for(var b=0;bc;++c)if(0!==(b.mipmask&1<>c,b.height>>c,0,b.internalformat,
+b.type,null);else for(var g=0;6>g;++g)a.texImage2D(34069+g,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);H(b.texInfo,b.target)})},refresh:function(){for(var b=0;bg;++g){for(r=
+0;ra;++a)c[a].resize(g);b.width=b.height=g;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})},clear:function(){S(H).forEach(q)},
+restore:function(){z.cur=null;z.next=null;z.dirty=!0;S(H).forEach(function(b){b.framebuffer=a.createFramebuffer();r(b)})}})}function Za(){this.w=this.z=this.y=this.x=this.state=0;this.buffer=null;this.size=0;this.normalized=!1;this.type=5126;this.divisor=this.stride=this.offset=0}function Sb(a,b,c,e,f){function d(a){if(a!==h.currentVAO){var c=b.oes_vertex_array_object;a?c.bindVertexArrayOES(a.vao):c.bindVertexArrayOES(null);h.currentVAO=a}}function p(c){if(c!==h.currentVAO){if(c)c.bindAttrs();else for(var e=
+b.angle_instanced_arrays,f=0;f=
+l.byteLength?n.subdata(l):(n.destroy(),c.buffers[d]=null));c.buffers[d]||(n=c.buffers[d]=f.create(h,34962,!1,!0));k.buffer=f.getBuffer(n);k.size=k.buffer.dimension|0;k.normalized=!1;k.type=k.buffer.dtype;k.offset=0;k.stride=0;k.divisor=0;k.state=1;g[d]=1}else f.getBuffer(h)?(k.buffer=f.getBuffer(h),k.size=k.buffer.dimension|0,k.normalized=!1,k.type=k.buffer.dtype,k.offset=0,k.stride=0,k.divisor=0,k.state=1):f.getBuffer(h.buffer)?(k.buffer=f.getBuffer(h.buffer),k.size=(+h.size||k.buffer.dimension)|
+0,k.normalized=!!h.normalized||!1,k.type="type"in h?Ia[h.type]:k.buffer.dtype,k.offset=(h.offset||0)|0,k.stride=(h.stride||0)|0,k.divisor=(h.divisor||0)|0,k.state=1):"x"in h&&(k.x=+h.x||0,k.y=+h.y||0,k.z=+h.z||0,k.w=+h.w||0,k.state=2)}for(a=0;aa&&(a=b.stats.uniformsCount)});
+return a},c.getMaxAttributesCount=function(){var a=0;B.forEach(function(b){b.stats.attributesCount>a&&(a=b.stats.attributesCount)});return a});return{clear:function(){var b=a.deleteShader.bind(a);S(t).forEach(b);t={};S(w).forEach(b);w={};B.forEach(function(b){a.deleteProgram(b.program)});B.length=0;k={};c.shaderCount=0},program:function(b,e,d,f){var l=k[e];l||(l=k[e]={});var p=l[b];if(p&&(p.refCount++,!f))return p;var v=new n(e,b);c.shaderCount++;u(v,d,f);p||(l[b]=v);B.push(v);return A(v,{destroy:function(){v.refCount--;
+if(0>=v.refCount){a.deleteProgram(v.program);var b=B.indexOf(v);B.splice(b,1);c.shaderCount--}0>=l[v.vertId].refCount&&(a.deleteShader(w[v.vertId]),delete w[v.vertId],delete k[v.fragId][v.vertId]);Object.keys(k[v.fragId]).length||(a.deleteShader(t[v.fragId]),delete t[v.fragId],delete k[v.fragId])}})},restore:function(){t={};w={};for(var a=0;a"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{",
+"if(",x,"(",e,".buffer)){",k,"=",f,".createStream(",34962,",",e,".buffer);","}else{",k,"=",f,".getBuffer(",e,".buffer);","}",l,'="type" in ',e,"?",g.glTypes,"[",e,".type]:",k,".dtype;",h.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",h.isStream,"){",f,".destroyStream(",k,");","}");return h})});return g}function D(a,b){var c=a["static"],d=a.dynamic;if("vao"in c){var e=c.vao;null!==e&&null===t.getVAO(e)&&(e=t.createVAO(e));return v(function(a){return a.link(t.getVAO(e))})}if("vao"in
+d){var f=d.vao;return L(f,function(a,b){var c=a.invoke(b,f);return b.def(a.shared.vao+".getVAO("+c+")")})}return null}function y(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=v(function(a,b){return"number"===typeof c||"boolean"===typeof c?""+c:a.link(c)})});Object.keys(c).forEach(function(a){var b=c[a];d[a]=L(b,function(a,c){return a.invoke(c,b)})});return d}function la(a,b,d,e,f){function h(a){var b=m[a];b&&($a[a]=b)}var k=Z(a,b),l=E(a,f),m=F(a,l,f),n=H(a,
+f),$a=O(a,f),p=G(a,f,k);h("viewport");h(g("scissor.box"));var q=0>1)",t],");")}function b(){c(w,".drawArraysInstancedANGLE(",
+[p,r,q,t],");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(k+".drawElements("+[p,q,u,r+"<<(("+u+"-5121)>>1)"]+");")}function b(){c(k+".drawArrays("+[p,r,q]+");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}var h=a.shared,k=h.gl,l=h.draw,m=d.draw,n=function(){var e=m.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(l,".","elements");e&&f("if("+e+")"+k+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),
+p=e("primitive"),r=e("offset"),q=function(){var e=m.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(l,".","count");return e}();if("number"===typeof q){if(0===q)return}else c("if(",q,"){"),c.exit("}");var t,w;oa&&(t=e("instances"),w=a.instancing);var u=n+".type",B=m.elements&&sa(m.elements);oa&&("number"!==typeof t||0<=t)?"string"===typeof t?(c("if(",t,">0){"),f(),c("}else if(",t,"<0){"),g(),c("}")):f():g()}function X(a,b,c,d,e){b=m();e=b.proc("body",e);
+oa&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function fa(a,b,c,d){C(a,b);c.useVAO?c.drawVAO?b(a.shared.vao,".setVAO(",c.drawVAO.append(a,b),");"):b(a.shared.vao,".setVAO(",a.shared.vao,".targetVAO);"):(b(a.shared.vao,".setVAO(null);"),U(a,b,c,d.attributes,function(){return!0}));ta(a,b,c,d.uniforms,function(){return!0});aa(a,b,b,c)}function Da(a,b){var c=a.proc("draw",1);C(a,c);V(a,c,b.context);R(a,c,b.framebuffer);T(a,c,b);N(a,c,b.state);
+Q(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(",d,".program);");if(b.shader.program)fa(a,c,b,b.shader.program);else{c(a.shared.vao,".setVAO(null);");var e=a.global.def("{}"),f=c.def(d,".id"),g=c.def(e,"[",f,"]");c(a.cond(g).then(g,".call(this,a0);")["else"](g,"=",e,"[",f,"]=",a.link(function(c){return X(fa,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0=--this.refCount&&p(this)};f.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(w).forEach(function(b){a+=w[b].stats.size});return a});return{create:function(b,c){function l(b,c){var d=0,e=0,k=32854;
+"object"===typeof b&&b?("shape"in b?(e=b.shape,d=e[0]|0,e=e[1]|0):("radius"in b&&(d=e=b.radius|0),"width"in b&&(d=b.width|0),"height"in b&&(e=b.height|0)),"format"in b&&(k=n[b.format])):"number"===typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==h.width||e!==h.height||k!==h.format)return l.width=h.width=d,l.height=h.height=e,h.format=k,a.bindRenderbuffer(36161,h.renderbuffer),a.renderbufferStorage(36161,k,d,e),f.profile&&(h.stats.size=T[h.format]*h.width*h.height),l.format=u[h.format],
+l}var h=new d(a.createRenderbuffer());w[h.id]=h;e.renderbufferCount++;l(b,c);l.resize=function(b,c){var d=b|0,e=c|0||d;if(d===h.width&&e===h.height)return l;l.width=h.width=d;l.height=h.height=e;a.bindRenderbuffer(36161,h.renderbuffer);a.renderbufferStorage(36161,h.format,d,e);f.profile&&(h.stats.size=T[h.format]*h.width*h.height);return l};l._reglType="renderbuffer";l._renderbuffer=h;f.profile&&(l.stats=h.stats);l.destroy=function(){h.decRef()};return l},clear:function(){S(w).forEach(p)},restore:function(){S(w).forEach(function(b){b.renderbuffer=
+a.createRenderbuffer();a.bindRenderbuffer(36161,b.renderbuffer);a.renderbufferStorage(36161,b.format,b.width,b.height)});a.bindRenderbuffer(36161,null)}}},Ya=[];Ya[6408]=4;Ya[6407]=3;var Pa=[];Pa[5121]=1;Pa[5126]=4;Pa[36193]=2;var Ba=["x","y","z","w"],Xb="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),Ea={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,
+"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},ab={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Ra={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,
+invert:5386},Ab={cw:2304,ccw:2305},Bb=new K(!1,!1,!1,function(){}),$b=function(a,b){function c(){this.endQueryIndex=this.startQueryIndex=-1;this.sum=0;this.stats=null}function e(a,b,d){var e=p.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;n.push(e)}if(!b.ext_disjoint_timer_query)return null;var f=[],d=[],p=[],n=[],u=[],t=[];return{beginQuery:function(a){var c=f.pop()||b.ext_disjoint_timer_query.createQueryEXT();b.ext_disjoint_timer_query.beginQueryEXT(35007,c);d.push(c);e(d.length-
+1,d.length,a)},endQuery:function(){b.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,c;a=d.length;if(0!==a){t.length=Math.max(t.length,a+1);u.length=Math.max(u.length,a+1);u[0]=0;var e=t[0]=0;for(c=a=0;c=C.length&&e()}var c=Cb(C,a);C[c]=b}}}function t(){var a=Q.viewport,b=Q.scissor_box;a[0]=a[1]=b[0]=b[1]=0;G.viewportWidth=G.framebufferWidth=G.drawingBufferWidth=a[2]=b[2]=l.drawingBufferWidth;G.viewportHeight=G.framebufferHeight=G.drawingBufferHeight=a[3]=b[3]=l.drawingBufferHeight}function w(){G.tick+=1;G.time=v();t();R.procs.poll()}function k(){y.refresh();t();R.procs.refresh();z&&z.update()}function v(){return(Db()-
+E)/1E3}a=Ib(a);if(!a)return null;var l=a.gl,h=l.getContextAttributes();l.isContextLost();var g=Jb(l,a);if(!g)return null;var q=Fb(),r={vaoCount:0,bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},m=g.extensions,z=$b(l,m),E=Db(),F=l.drawingBufferWidth,K=l.drawingBufferHeight,G={tick:0,time:0,viewportWidth:F,viewportHeight:K,framebufferWidth:F,framebufferHeight:K,drawingBufferWidth:F,drawingBufferHeight:K,pixelRatio:a.pixelRatio},
+H=Yb(l,m),O=Kb(l,r,a,function(a){return J.destroyBuffer(a)}),J=Sb(l,m,H,r,O),M=Lb(l,m,O,r),D=Tb(l,q,r,a),y=Ob(l,m,H,function(){R.procs.poll()},G,r,a),L=Zb(l,m,H,r,a),V=Rb(l,m,H,y,L,r),R=Wb(l,q,m,H,O,M,y,V,{},J,D,{elements:null,primitive:4,count:-1,offset:0,instances:-1},G,z,a),q=Ub(l,V,R.procs.poll,G,h,m,H),Q=R.next,N=l.canvas,C=[],S=[],T=[],U=[a.onDestroy],aa=null;N&&(N.addEventListener("webglcontextlost",f,!1),N.addEventListener("webglcontextrestored",d,!1));var X=V.setFBO=p({framebuffer:Y.define.call(null,
+1,"framebuffer")});k();h=A(p,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)X(A({framebuffer:a.framebuffer.faces[b]},a),n);else X(a,n);else n(null,a)},prop:Y.define.bind(null,1),context:Y.define.bind(null,2),"this":Y.define.bind(null,3),draw:p({}),buffer:function(a){return O.create(a,34962,!1,!1)},elements:function(a){return M.create(a,!1)},texture:y.create2D,cube:y.createCube,renderbuffer:L.create,framebuffer:V.create,framebufferCube:V.createCube,
+vao:J.createVAO,attributes:h,frame:u,on:function(a,b){var c;switch(a){case "frame":return u(b);case "lost":c=S;break;case "restore":c=T;break;case "destroy":c=U}c.push(b);return{cancel:function(){for(var a=0;a 0 && existing.length > m) {
- existing.warned = true;
- var w = new Error('Possible EventEmitter memory leak detected. ' +
- existing.length + ' "' + String(type) + '" listeners ' +
- 'added. Use emitter.setMaxListeners() to ' +
- 'increase limit.');
- w.name = 'MaxListenersExceededWarning';
- w.emitter = target;
- w.type = type;
- w.count = existing.length;
- if (typeof console === 'object' && console.warn) {
- console.warn('%s: %s', w.name, w.message);
- }
- }
- }
- }
+},{}],125:[function(require,module,exports){
+'use strict'
- return target;
-}
+/**
+ * Remove a range of items from an array
+ *
+ * @function removeItems
+ * @param {Array<*>} arr The target array
+ * @param {number} startIdx The index to begin removing from (inclusive)
+ * @param {number} removeCount How many items to remove
+ */
+module.exports = function removeItems (arr, startIdx, removeCount) {
+ var i, length = arr.length
-EventEmitter.prototype.addListener = function addListener(type, listener) {
- return _addListener(this, type, listener, false);
-};
+ if (startIdx >= length || removeCount === 0) {
+ return
+ }
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
+ removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount)
-EventEmitter.prototype.prependListener =
- function prependListener(type, listener) {
- return _addListener(this, type, listener, true);
- };
+ var len = length - removeCount
-function onceWrapper() {
- if (!this.fired) {
- this.target.removeListener(this.type, this.wrapFn);
- this.fired = true;
- switch (arguments.length) {
- case 0:
- return this.listener.call(this.target);
- case 1:
- return this.listener.call(this.target, arguments[0]);
- case 2:
- return this.listener.call(this.target, arguments[0], arguments[1]);
- case 3:
- return this.listener.call(this.target, arguments[0], arguments[1],
- arguments[2]);
- default:
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; ++i)
- args[i] = arguments[i];
- this.listener.apply(this.target, args);
- }
+ for (i = startIdx; i < len; ++i) {
+ arr[i] = arr[i + removeCount]
}
-}
-function _onceWrap(target, type, listener) {
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
- var wrapped = bind.call(onceWrapper, state);
- wrapped.listener = listener;
- state.wrapFn = wrapped;
- return wrapped;
+ arr.length = len
}
-EventEmitter.prototype.once = function once(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.on(type, _onceWrap(this, type, listener));
- return this;
-};
-
-EventEmitter.prototype.prependOnceListener =
- function prependOnceListener(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.prependListener(type, _onceWrap(this, type, listener));
- return this;
- };
+},{}],126:[function(require,module,exports){
+(function (global){(function (){
+module.exports =
+ global.performance &&
+ global.performance.now ? function now() {
+ return performance.now()
+ } : Date.now || function now() {
+ return +new Date
+ }
-// Emits a 'removeListener' event if and only if the listener was removed.
-EventEmitter.prototype.removeListener =
- function removeListener(type, listener) {
- var list, events, position, i, originalListener;
+}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],127:[function(require,module,exports){
+module.exports = scrollToAnchor
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
+function scrollToAnchor (anchor, options) {
+ if (anchor) {
+ try {
+ var el = document.querySelector(anchor)
+ if (el) el.scrollIntoView(options)
+ } catch (e) {}
+ }
+}
- events = this._events;
- if (!events)
- return this;
+},{}],128:[function(require,module,exports){
+var fastSafeStringify = require('fast-safe-stringify')
+var copy = require('clipboard-copy')
- list = events[type];
- if (!list)
- return this;
+function tryStringify (obj) {
+ try {
+ return JSON.stringify(obj)
+ } catch (e) {}
+}
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else {
- delete events[type];
- if (events.removeListener)
- this.emit('removeListener', type, list.listener || listener);
- }
- } else if (typeof list !== 'function') {
- position = -1;
+function stateCopy (obj) {
+ var str = tryStringify(obj) || fastSafeStringify(obj)
+ copy(str)
+}
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || list[i].listener === listener) {
- originalListener = list[i].listener;
- position = i;
- break;
- }
- }
+module.exports = stateCopy
- if (position < 0)
- return this;
+},{"clipboard-copy":60,"fast-safe-stringify":63}],129:[function(require,module,exports){
+var C = "\u037c"
+var COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C)
+var SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet")
+var top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}
- if (position === 0)
- list.shift();
- else
- spliceOne(list, position);
+// :: - Style modules encapsulate a set of CSS rules defined from
+// JavaScript. Their definitions are only available in a given DOM
+// root after it has been _mounted_ there with `StyleModule.mount`.
+//
+// Style modules should be created once and stored somewhere, as
+// opposed to re-creating them every time you need them. The amount of
+// CSS rules generated for a given DOM root is bounded by the amount
+// of style modules that were used. So to avoid leaking rules, don't
+// create these dynamically, but treat them as one-time allocations.
+var StyleModule = exports.StyleModule = function StyleModule(spec, options) {
+ this.rules = []
+ var ref = options || {};
+ var finish = ref.finish;
- if (list.length === 1)
- events[type] = list[0];
+ function splitSelector(selector) {
+ return /^@/.test(selector) ? [selector] : selector.split(/,\s*/)
+ }
- if (events.removeListener)
- this.emit('removeListener', type, originalListener || listener);
+ function render(selectors, spec, target, isKeyframes) {
+ var local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"
+ if (isAt && spec == null) { return target.push(selectors[0] + ";") }
+ for (var prop in spec) {
+ var value = spec[prop]
+ if (/&/.test(prop)) {
+ render(prop.split(/,\s*/).map(function (part) { return selectors.map(function (sel) { return part.replace(/&/, sel); }); }).reduce(function (a, b) { return a.concat(b); }),
+ value, target)
+ } else if (value && typeof value == "object") {
+ if (!isAt) { throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") }
+ render(splitSelector(prop), value, local, keyframes)
+ } else if (value != null) {
+ local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, function (l) { return "-" + l.toLowerCase(); }) + ": " + value + ";")
}
+ }
+ if (local.length || keyframes) {
+ target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") +
+ " {" + local.join(" ") + "}")
+ }
+ }
- return this;
- };
-
-EventEmitter.prototype.removeAllListeners =
- function removeAllListeners(type) {
- var listeners, events, i;
-
- events = this._events;
- if (!events)
- return this;
+ for (var prop in spec) { render(splitSelector(prop), spec[prop], this.rules) }
+};
- // not listening for removeListener, no need to emit
- if (!events.removeListener) {
- if (arguments.length === 0) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- } else if (events[type]) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else
- delete events[type];
- }
- return this;
- }
+// :: () → string
+// Returns a string containing the module's CSS rules.
+StyleModule.prototype.getRules = function getRules () { return this.rules.join("\n") };
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- var keys = objectKeys(events);
- var key;
- for (i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = objectCreate(null);
- this._eventsCount = 0;
- return this;
- }
+// :: () → string
+// Generate a new unique CSS class name.
+StyleModule.newName = function newName () {
+ var id = top[COUNT] || 1
+ top[COUNT] = id + 1
+ return C + id.toString(36)
+};
- listeners = events[type];
+// :: (union, union<[StyleModule], StyleModule>)
+//
+// Mount the given set of modules in the given DOM root, which ensures
+// that the CSS rules defined by the module are available in that
+// context.
+//
+// Rules are only added to the document once per root.
+//
+// Rule order will follow the order of the modules, so that rules from
+// modules later in the array take precedence of those from earlier
+// modules. If you call this function multiple times for the same root
+// in a way that changes the order of already mounted modules, the old
+// order will be changed.
+StyleModule.mount = function mount (root, modules) {
+ (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules])
+};
- if (typeof listeners === 'function') {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- for (i = listeners.length - 1; i >= 0; i--) {
- this.removeListener(type, listeners[i]);
- }
- }
+var adoptedSet = null
- return this;
- };
+var StyleSet = function StyleSet(root) {
+ if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") {
+ if (adoptedSet) {
+ root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets)
+ return root[SET] = adoptedSet
+ }
+ this.sheet = new CSSStyleSheet
+ root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets)
+ adoptedSet = this
+ } else {
+ this.styleTag = (root.ownerDocument || root).createElement("style")
+ var target = root.head || root
+ target.insertBefore(this.styleTag, target.firstChild)
+ }
+ this.modules = []
+ root[SET] = this
+};
-function _listeners(target, type, unwrap) {
- var events = target._events;
+StyleSet.prototype.mount = function mount (modules) {
+ var sheet = this.sheet
+ var pos = 0 /* Current rule offset */, j = 0 /* Index into this.modules */
+ for (var i = 0; i < modules.length; i++) {
+ var mod = modules[i], index = this.modules.indexOf(mod)
+ if (index < j && index > -1) { // Ordering conflict
+ this.modules.splice(index, 1)
+ j--
+ index = -1
+ }
+ if (index == -1) {
+ this.modules.splice(j++, 0, mod)
+ if (sheet) { for (var k = 0; k < mod.rules.length; k++)
+ { sheet.insertRule(mod.rules[k], pos++) } }
+ } else {
+ while (j < index) { pos += this.modules[j++].rules.length }
+ pos += mod.rules.length
+ j++
+ }
+ }
- if (!events)
- return [];
+ if (!sheet) {
+ var text = ""
+ for (var i$1 = 0; i$1 < this.modules.length; i$1++)
+ { text += this.modules[i$1].getRules() + "\n" }
+ this.styleTag.textContent = text
+ }
+};
- var evlistener = events[type];
- if (!evlistener)
- return [];
+// Style::Object>
+//
+// A style is an object that, in the simple case, maps CSS property
+// names to strings holding their values, as in `{color: "red",
+// fontWeight: "bold"}`. The property names can be given in
+// camel-case—the library will insert a dash before capital letters
+// when converting them to CSS.
+//
+// If you include an underscore in a property name, it and everything
+// after it will be removed from the output, which can be useful when
+// providing a property multiple times, for browser compatibility
+// reasons.
+//
+// A property in a style object can also be a sub-selector, which
+// extends the current context to add a pseudo-selector or a child
+// selector. Such a property should contain a `&` character, which
+// will be replaced by the current selector. For example `{"&:before":
+// {content: '"hi"'}}`. Sub-selectors and regular properties can
+// freely be mixed in a given object. Any property containing a `&` is
+// assumed to be a sub-selector.
+//
+// Finally, a property can specify an @-block to be wrapped around the
+// styles defined inside the object that's the property's value. For
+// example to create a media query you can do `{"@media screen and
+// (min-width: 400px)": {...}}`.
- if (typeof evlistener === 'function')
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
- return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
-}
+},{}],130:[function(require,module,exports){
+'use strict';
-EventEmitter.prototype.listeners = function listeners(type) {
- return _listeners(this, type, true);
-};
+Object.defineProperty(exports, '__esModule', { value: true });
-EventEmitter.prototype.rawListeners = function rawListeners(type) {
- return _listeners(this, type, false);
+var base = {
+ 8: "Backspace",
+ 9: "Tab",
+ 10: "Enter",
+ 12: "NumLock",
+ 13: "Enter",
+ 16: "Shift",
+ 17: "Control",
+ 18: "Alt",
+ 20: "CapsLock",
+ 27: "Escape",
+ 32: " ",
+ 33: "PageUp",
+ 34: "PageDown",
+ 35: "End",
+ 36: "Home",
+ 37: "ArrowLeft",
+ 38: "ArrowUp",
+ 39: "ArrowRight",
+ 40: "ArrowDown",
+ 44: "PrintScreen",
+ 45: "Insert",
+ 46: "Delete",
+ 59: ";",
+ 61: "=",
+ 91: "Meta",
+ 92: "Meta",
+ 106: "*",
+ 107: "+",
+ 108: ",",
+ 109: "-",
+ 110: ".",
+ 111: "/",
+ 144: "NumLock",
+ 145: "ScrollLock",
+ 160: "Shift",
+ 161: "Shift",
+ 162: "Control",
+ 163: "Control",
+ 164: "Alt",
+ 165: "Alt",
+ 173: "-",
+ 186: ";",
+ 187: "=",
+ 188: ",",
+ 189: "-",
+ 190: ".",
+ 191: "/",
+ 192: "`",
+ 219: "[",
+ 220: "\\",
+ 221: "]",
+ 222: "'",
+ 229: "q"
};
-EventEmitter.listenerCount = function(emitter, type) {
- if (typeof emitter.listenerCount === 'function') {
- return emitter.listenerCount(type);
- } else {
- return listenerCount.call(emitter, type);
- }
+var shift = {
+ 48: ")",
+ 49: "!",
+ 50: "@",
+ 51: "#",
+ 52: "$",
+ 53: "%",
+ 54: "^",
+ 55: "&",
+ 56: "*",
+ 57: "(",
+ 59: ":",
+ 61: "+",
+ 173: "_",
+ 186: ":",
+ 187: "+",
+ 188: "<",
+ 189: "_",
+ 190: ">",
+ 191: "?",
+ 192: "~",
+ 219: "{",
+ 220: "|",
+ 221: "}",
+ 222: "\"",
+ 229: "Q"
};
-EventEmitter.prototype.listenerCount = listenerCount;
-function listenerCount(type) {
- var events = this._events;
+var chrome = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
+var safari = typeof navigator != "undefined" && /Apple Computer/.test(navigator.vendor);
+var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
+var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
+var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
+var brokenModifierNames = chrome && (mac || +chrome[1] < 57) || gecko && mac;
- if (events) {
- var evlistener = events[type];
+// Fill in the digit keys
+for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
- if (typeof evlistener === 'function') {
- return 1;
- } else if (evlistener) {
- return evlistener.length;
- }
- }
+// The function keys
+for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
- return 0;
+// And the alphabetic keys
+for (var i = 65; i <= 90; i++) {
+ base[i] = String.fromCharCode(i + 32);
+ shift[i] = String.fromCharCode(i);
}
-EventEmitter.prototype.eventNames = function eventNames() {
- return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
-};
-
-// About 1.5x faster than the two-arg version of Array#splice().
-function spliceOne(list, index) {
- for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
- list[i] = list[k];
- list.pop();
-}
+// For each code that doesn't have a shift-equivalent, copy the base name
+for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
-function arrayClone(arr, n) {
- var copy = new Array(n);
- for (var i = 0; i < n; ++i)
- copy[i] = arr[i];
- return copy;
+function keyName(event) {
+ // Don't trust event.key in Chrome when there are modifiers until
+ // they fix https://bugs.chromium.org/p/chromium/issues/detail?id=633838
+ var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) ||
+ (safari || ie) && event.shiftKey && event.key && event.key.length == 1;
+ var name = (!ignoreKey && event.key) ||
+ (event.shiftKey ? shift : base)[event.keyCode] ||
+ event.key || "Unidentified";
+ // Edge sometimes produces wrong names (Issue #3)
+ if (name == "Esc") name = "Escape";
+ if (name == "Del") name = "Delete";
+ // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
+ if (name == "Left") name = "ArrowLeft";
+ if (name == "Up") name = "ArrowUp";
+ if (name == "Right") name = "ArrowRight";
+ if (name == "Down") name = "ArrowDown";
+ return name
}
-function unwrapListeners(arr) {
- var ret = new Array(arr.length);
- for (var i = 0; i < ret.length; ++i) {
- ret[i] = arr[i].listener || arr[i];
- }
- return ret;
-}
+exports.base = base;
+exports.keyName = keyName;
+exports.shift = shift;
-function objectCreatePolyfill(proto) {
- var F = function() {};
- F.prototype = proto;
- return new F;
-}
-function objectKeysPolyfill(obj) {
- var keys = [];
- for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
- keys.push(k);
- }
- return k;
-}
-function functionBindPolyfill(context) {
- var fn = this;
- return function () {
- return fn.apply(context, arguments);
- };
-}
+},{}],131:[function(require,module,exports){
+/* eslint-disable node/no-deprecated-api */
+var assert = require('assert')
-},{}],133:[function(require,module,exports){
-exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
+module.exports = getAllRoutes
- i += d
+var transform = function (trie, previous) {
+ var prev = previous || '/'
+ var routes = {}
+ var nodes = trie.nodes
+ Object.keys(nodes).forEach(function (key) {
+ var path = (prev === '/' ? prev : prev + '/') + (key === '$$' ? ':' + trie.name : key)
+ var cb = nodes[key].cb
+ if (cb !== undefined) {
+ routes[path] = cb
+ }
+ if (Object.keys(nodes[key].nodes).length !== 0) {
+ var obj = transform(nodes[key], path)
+ Object.keys(obj).forEach(function (r) {
+ routes[r] = obj[r]
+ })
+ }
+ })
+ return routes
+}
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
+// walk a wayfarer trie
+// (obj, fn) -> null
+function getAllRoutes (router) {
+ assert.equal(typeof router, 'function', 'wayfarer.getAllRoutes: router should be an function')
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
+ var trie = router._trie
+ assert.equal(typeof trie, 'object', 'wayfarer.getAllRoutes: trie should be an object')
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
+ var tree = trie.trie
+ return transform(tree)
}
-exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+},{"assert":93}],132:[function(require,module,exports){
+/* eslint-disable node/no-deprecated-api */
+var assert = require('assert')
+var trie = require('./trie')
- value = Math.abs(value)
+module.exports = Wayfarer
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
+// create a router
+// str -> obj
+function Wayfarer (dft) {
+ if (!(this instanceof Wayfarer)) return new Wayfarer(dft)
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = ((value * c) - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
+ var _default = (dft || '').replace(/^\//, '')
+ var _trie = trie()
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
+ emit._trie = _trie
+ emit.on = on
+ emit.emit = emit
+ emit.match = match
+ emit._wayfarer = true
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
+ return emit
- buffer[offset + i - d] |= s * 128
-}
+ // define a route
+ // (str, fn) -> obj
+ function on (route, cb) {
+ assert.equal(typeof route, 'string')
+ assert.equal(typeof cb, 'function')
-},{}],134:[function(require,module,exports){
-/*
-object-assign
-(c) Sindre Sorhus
-@license MIT
-*/
+ route = route || '/'
-'use strict';
-/* eslint-disable no-unused-vars */
-var getOwnPropertySymbols = Object.getOwnPropertySymbols;
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+ if (cb._wayfarer && cb._trie) {
+ _trie.mount(route, cb._trie.trie)
+ } else {
+ var node = _trie.create(route)
+ node.cb = cb
+ node.route = route
+ }
-function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
+ return emit
+ }
- return Object(val);
-}
+ // match and call a route
+ // (str, obj?) -> null
+ function emit (route) {
+ var matched = match(route)
-function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- }
+ var args = new Array(arguments.length)
+ args[0] = matched.params
+ for (var i = 1; i < args.length; i++) {
+ args[i] = arguments[i]
+ }
- // Detect buggy property enumeration order in older V8 versions.
+ return matched.cb.apply(matched.cb, args)
+ }
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
- test1[5] = 'de';
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- }
+ function match (route) {
+ assert.notEqual(route, undefined, "'route' must be defined")
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
- if (order2.join('') !== '0123456789') {
- return false;
- }
+ var matched = _trie.match(route)
+ if (matched && matched.cb) return new Route(matched)
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join('') !==
- 'abcdefghijklmnopqrst') {
- return false;
- }
+ var dft = _trie.match(_default)
+ if (dft && dft.cb) return new Route(dft)
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
-}
+ throw new Error("route '" + route + "' did not match")
+ }
-module.exports = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
+ function Route (matched) {
+ this.cb = matched.cb
+ this.route = matched.route
+ this.params = matched.params
+ }
+}
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
+},{"./trie":133,"assert":93}],133:[function(require,module,exports){
+/* eslint-disable node/no-deprecated-api */
+var assert = require('assert')
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
+module.exports = Trie
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
+// create a new trie
+// null -> obj
+function Trie () {
+ if (!(this instanceof Trie)) return new Trie()
+ this.trie = { nodes: {} }
+}
- return to;
-};
+// create a node on the trie at route
+// and return a node
+// str -> obj
+Trie.prototype.create = function (route) {
+ assert.equal(typeof route, 'string', 'route should be a string')
+ // strip leading '/' and split routes
+ var routes = route.replace(/^\//, '').split('/')
-},{}],135:[function(require,module,exports){
-// shim for using process in browser
-var process = module.exports = {};
+ function createNode (index, trie) {
+ var thisRoute = (has(routes, index) && routes[index])
+ if (thisRoute === false) return trie
-// cached from whatever global is present so that test runners that stub it
-// don't break things. But we need to wrap it in a try catch in case it is
-// wrapped in strict mode code which doesn't define any globals. It's inside a
-// function because try/catches deoptimize in certain engines.
+ var node = null
+ if (/^:|^\*/.test(thisRoute)) {
+ // if node is a name match, set name and append to ':' node
+ if (!has(trie.nodes, '$$')) {
+ node = { nodes: {} }
+ trie.nodes.$$ = node
+ } else {
+ node = trie.nodes.$$
+ }
-var cachedSetTimeout;
-var cachedClearTimeout;
+ if (thisRoute[0] === '*') {
+ trie.wildcard = true
+ }
-function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
-}
-function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
-}
-(function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
-} ())
-function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
+ trie.name = thisRoute.replace(/^:|^\*/, '')
+ } else if (!has(trie.nodes, thisRoute)) {
+ node = { nodes: {} }
+ trie.nodes[thisRoute] = node
+ } else {
+ node = trie.nodes[thisRoute]
}
+ // we must recurse deeper
+ return createNode(index + 1, node)
+ }
+ return createNode(0, this.trie)
}
-function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
+// match a route on the trie
+// and return the node
+// str -> obj
+Trie.prototype.match = function (route) {
+ assert.equal(typeof route, 'string', 'route should be a string')
+ var routes = route.replace(/^\//, '').split('/')
+ var params = {}
-}
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
+ function search (index, trie) {
+ // either there's no match, or we're done searching
+ if (trie === undefined) return undefined
+ var thisRoute = routes[index]
+ if (thisRoute === undefined) return trie
-function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
+ if (has(trie.nodes, thisRoute)) {
+ // match regular routes first
+ return search(index + 1, trie.nodes[thisRoute])
+ } else if (trie.name) {
+ // match named routes
+ try {
+ params[trie.name] = decodeURIComponent(thisRoute)
+ } catch (e) {
+ return search(index, undefined)
+ }
+ return search(index + 1, trie.nodes.$$)
+ } else if (trie.wildcard) {
+ // match wildcards
+ try {
+ params.wildcard = decodeURIComponent(routes.slice(index).join('/'))
+ } catch (e) {
+ return search(index, undefined)
+ }
+ // return early, or else search may keep recursing through the wildcard
+ return trie.nodes.$$
} else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
+ // no matches found
+ return search(index + 1)
}
-}
+ }
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
+ var node = search(0, this.trie)
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
+ if (!node) return undefined
+ node = Object.assign({}, node)
+ node.params = params
+ return node
}
-process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
-};
+// mount a trie onto a node at route
+// (str, obj) -> null
+Trie.prototype.mount = function (route, trie) {
+ assert.equal(typeof route, 'string', 'route should be a string')
+ assert.equal(typeof trie, 'object', 'trie should be a object')
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
+ var split = route.replace(/^\//, '').split('/')
+ var node = null
+ var key = null
-function noop() {}
+ if (split.length === 1) {
+ key = split[0]
+ node = this.create(key)
+ } else {
+ var head = split.join('/')
+ key = split[0]
+ node = this.create(head)
+ }
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-process.prependListener = noop;
-process.prependOnceListener = noop;
+ Object.assign(node.nodes, trie.nodes)
+ if (trie.name) node.name = trie.name
-process.listeners = function (name) { return [] }
+ // delegate properties from '/' to the new node
+ // '/' cannot be reached once mounted
+ if (node.nodes['']) {
+ Object.keys(node.nodes['']).forEach(function (key) {
+ if (key === 'nodes') return
+ node[key] = node.nodes[''][key]
+ })
+ Object.assign(node.nodes, node.nodes[''].nodes)
+ delete node.nodes[''].nodes
+ }
+}
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
+function has (object, property) {
+ return Object.prototype.hasOwnProperty.call(object, property)
+}
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
+},{"assert":93}],134:[function(require,module,exports){
+module.exports = [
+ {
+ key: 'src',
+ // color: '#f33'
+ },
+ {
+ key: 'coord',
+ // color: '#ff3'
+ },
+ {
+ key: 'color',
+ // color: '#3f3'
+ },
+ {
+ key: 'combine',
+ // color: '#3ff'
+ },
+ {
+ key: 'combineCoord',
+ // color: '#33f'
+ },
+ {
+ key: 'ext',
+ },
+ {
+ key: 'settings',
+ },
+ {
+ key: 'array',
+ },
+ {
+ key: 'audio',
+ },
+]
},{}]},{},[6]);
diff --git a/examples.js b/examples.js
index 796f8a3..8d83be8 100644
--- a/examples.js
+++ b/examples.js
@@ -6,6 +6,7 @@ module.exports = {
code: `noise(10, 0.1).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -15,6 +16,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
.out(o0)`,
comments: {
en: "noise interpolating between different scales and offsets",
+ es: "ruido (noise) cambiando entre varias escalas y offsets",
ja: "noise の異なるスケールやオフセットを補間",
}
}
@@ -27,6 +29,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `voronoi(5,0.3,0.3).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -34,6 +37,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `voronoi(25,2,10).color(1,1,0).brightness(0.15).out(o0)`,
comments: {
en: "fireflies",
+ es: "luciérnagas",
ja: "蛍",
}
}
@@ -45,6 +49,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `osc( [1,10,50,100,250,500].fast(2) ).out(o0)`,
comments: {
en: "frequency",
+ es: "frecuencia",
ja: "周波数",
}
},
@@ -52,6 +57,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `osc( () => Math.sin(time/10) * 100 ).out(o0)`,
comments: {
en: "frequency 2",
+ es: "frecuencia 2",
ja: "周波数 2",
}
},
@@ -59,6 +65,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `osc( 10, [-10,-1,-0.1,0,0.1,1,10], 0 ).out(o0)`,
comments: {
en: "sync",
+ es: "sincronización",
ja: "シンク(同期)",
}
},
@@ -66,6 +73,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `osc(10,0.1, ({time}) => Math.sin(time/10) * 100 ).out(o0)`,
comments: {
en: "offset",
+ es: "offset",
ja: "オフセット",
}
},
@@ -77,6 +85,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `shape(3,0.5,0.001).out(o0)`,
comments: {
en: "triangle",
+ es: "triángulo",
ja: "三角形",
}
},
@@ -84,6 +93,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `shape(100,0.5,0.001).out(o0)`,
comments: {
en: "ellipse",
+ es: "elipse",
ja: "楕円",
}
},
@@ -91,6 +101,7 @@ noise( () => Math.sin(time/10)*50 , () => Math.sin(time/2)/500 )
code: `shape(100,0.01,1).invert(()=>Math.sin(time)*2).out(o0)`,
comments: {
en: "inverting blurry circle",
+ es: "círculo difuminado que se invierte",
ja: "反転するぼかした円",
}
},
@@ -106,6 +117,7 @@ shape(5,0.5,0.1).repeat(19,19)
.out(o0)`,
comments: {
en: "a... rainbow ball?",
+ es: "una... ¿bola de arcoíris?",
ja: "虹色のボール…?",
}
},
@@ -117,6 +129,7 @@ shape(5,0.5,0.1).repeat(19,19)
code: `gradient([1,2,4]).out(o0)`,
comments: {
en: "gradient sequence at speeds of 1, 2 & 4",
+ es: "secuencia de degradés con velocidades de 1, 2 y 4",
ja: "グラデーションのスピードを 1, 2, 4 の順に変える",
}
},
@@ -124,6 +137,7 @@ shape(5,0.5,0.1).repeat(19,19)
code: `gradient(0).r().repeat(16,1).scrollX(0,0.1).out(o0)`,
comments: {
en: "saw oscillator",
+ es: "oscilador de cierra",
ja: "のこぎり波",
}
},
@@ -136,6 +150,7 @@ shape(5,0.5,0.1).repeat(19,19)
code: `src(o0).modulate(noise(3),0.005).blend(shape(4),0.01).out(o0)`,
comments: {
en: "feedback",
+ es: "retroalimentación (feedback)",
ja: "フィードバック",
}
},
@@ -147,6 +162,7 @@ shape(5,0.5,0.1).repeat(19,19)
code: `solid([1,0,0],[0,1,0],[0,0,1],1).out(o0)`,
comments: {
en: "cycling through red, green and blue",
+ es: "cambiando entre rojo, verde y azul",
ja: "赤、緑、青を行き来する",
}
},
@@ -159,6 +175,7 @@ shape(5,0.5,0.1).repeat(19,19)
code: `osc(50).rotate( () => time%360 ).out(o0)`,
comments: {
en: "constant rotation",
+ es: "rotación constante",
ja: "一定速度で回転",
}
},
@@ -169,6 +186,7 @@ osc(10,1,1)
.out(o0)`,
comments: {
en: "modulate rotation speed",
+ es: "modulando la velocidad de rotación",
ja: "回転速度を変化させる",
}
},
@@ -181,6 +199,7 @@ osc(10,1,1)
code: `shape().scale(1.5,1,1).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -195,6 +214,7 @@ shape().scale(1.5,[0.25,0.5,0.75,1].fast(0.25),[3,2,1])
.out(o0)`,
comments: {
en: "flower",
+ es: "flor",
ja: "花",
}
},
@@ -207,6 +227,7 @@ shape().scale(1.5,[0.25,0.5,0.75,1].fast(0.25),[3,2,1])
code: `noise().pixelate(20,20).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -214,6 +235,7 @@ shape().scale(1.5,[0.25,0.5,0.75,1].fast(0.25),[3,2,1])
code: `noise().pixelate(2000,1).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -228,6 +250,7 @@ noise()
.out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -239,6 +262,7 @@ noise()
code: `gradient(0).posterize( [1, 5, 15, 30] , 0.5 ).out(o0)`,
comments: {
en: "static gradient posterized, varying bins",
+ es: "gradiente estático, con una posterización cuya cantidad de tonos varía en el tiempo",
ja: "",
}
},
@@ -246,6 +270,7 @@ noise()
code: `gradient(0).posterize( 3, [0.1, 0.5, 1.0, 2.0] ).out(o0)`,
comments: {
en: "static gradient posterized, varying gamma",
+ es: "gradiente estático, con una posterización cuyo gamma varía en el tiempo",
ja: "",
}
},
@@ -257,6 +282,7 @@ osc().posterize(3,1)
.out(o0)`,
comments: {
en: "posterize (top); compare with pixelate (bottom)",
+ es: "posteriación (arriba); comparar con la pixelización (abajo)",
ja: "",
}
},
@@ -268,6 +294,7 @@ osc().posterize(3,1)
code: `osc().shift(0.1,0.9,0.3).out()`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -279,6 +306,7 @@ osc().posterize(3,1)
code: `shape().repeat(3.0, 3.0, 0.0, 0.0).out()`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -291,6 +319,7 @@ shape(1.25,0.5,0.25)
.out(o0)`,
comments: {
en: "dogtooth factory",
+ es: "pata de gallo",
ja: "",
}
},
@@ -307,6 +336,7 @@ shape(4,0.9)
.out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -318,6 +348,7 @@ shape(4,0.9)
code: `shape().repeatX(3.0, 0.0).out()`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -329,6 +360,7 @@ osc(5,0,1)
.out()`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -346,6 +378,7 @@ shape(4,0.9)
.out(o0)`,
comments: {
en: "straight lines illusion",
+ es: "ilusión de líneas rectas",
ja: "",
}
},
@@ -357,6 +390,7 @@ shape(4,0.9)
code: `shape().repeatY(3.0, 0.0).out()`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -367,6 +401,7 @@ osc(5,0,1)
.out()`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -384,6 +419,7 @@ shape(4,0.9)
.out(o0)`,
comments: {
en: "morphing grid",
+ es: "cuadrícula cambiante",
ja: "",
}
},
@@ -396,6 +432,7 @@ shape(4,0.9)
code: `osc(25,-0.1,0.5).kaleid(50).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -403,6 +440,7 @@ shape(4,0.9)
code: `osc(25,-0.1,0.5).kaleid(4).kaleid(4).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -421,6 +459,7 @@ osc(9,-0.1,0.1)
.out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -430,6 +469,7 @@ osc(9,-0.1,0.1)
.out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -441,6 +481,7 @@ osc(9,-0.1,0.1)
code: `shape(3).scroll(0.1,-0.3).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -452,6 +493,7 @@ osc(9,-0.1,0.1)
code: `osc(10,0,1).scrollX(0.5,0).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -459,6 +501,7 @@ osc(9,-0.1,0.1)
code: `osc(10,0,1).scrollX([0,0.25,0.5,0.75,1].fast(4),0).out(o0)`,
comments: {
en: "x position",
+ es: "posición x (horizontal)",
ja: "",
}
},
@@ -466,6 +509,7 @@ osc(9,-0.1,0.1)
code: `gradient(1).scrollX(0, () => Math.sin(time*0.05)*0.05 ).out(o0)`,
comments: {
en: "scroll speed",
+ es: "velocidad de desplazamiento (scroll)",
ja: "",
}
},
@@ -479,6 +523,7 @@ osc(9,-0.1,0.1)
.out()`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -494,6 +539,7 @@ voronoi(25,0,0)
.out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -504,6 +550,7 @@ voronoi(25,0,0)
.out(o0)`,
comments: {
en: "different scroll and speed",
+ es: "distinto desplazamiento y velocidad",
ja: "",
}
},
@@ -515,6 +562,7 @@ voronoi(25,0,0)
code: `osc(10,0,1).scrollY(0.5,0).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -522,6 +570,7 @@ voronoi(25,0,0)
code: `osc(10,0,1).scrollY([0,0.25,0.5,0.75,1].fast(4),0).out(o0)`,
comments: {
en: "y position",
+ es: "posición y (vertical)",
ja: "",
}
},
@@ -529,6 +578,7 @@ voronoi(25,0,0)
code: `gradient(1).scrollY(0, ({time}) => Math.sin(time*0.05)*0.05 ).out()`,
comments: {
en: "scroll speed",
+ es: "velocidad de desplazamiento (scroll)",
ja: "",
}
},
@@ -557,6 +607,7 @@ voronoi(25,0,0)
.out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -567,6 +618,7 @@ voronoi(25,0,0)
.out(o0)`,
comments: {
en: "different scroll and speed",
+ es: "distinto desplazamiento y velocidad",
ja: "",
}
},
@@ -579,6 +631,7 @@ voronoi(25,0,0)
code: `shape().scale(0.5).add(shape(4),[0,0.25,0.5,0.75,1]).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -586,6 +639,7 @@ voronoi(25,0,0)
code: `osc(9,0.1,1).add(osc(13,0.5,5)).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -597,6 +651,7 @@ voronoi(25,0,0)
code: `osc().sub(osc(6)).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -604,6 +659,7 @@ voronoi(25,0,0)
code: `osc(6,0,1.5).modulate(noise(3).sub(gradient()),1).out(o0)`,
comments: {
en: "color remapping",
+ es: "reasignación de colores",
ja: "",
}
},
@@ -616,6 +672,7 @@ voronoi(25,0,0)
code: `solid(1,0,0,1).layer(shape(4).color(0,1,0,()=>Math.sin(time*2))).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -623,6 +680,7 @@ voronoi(25,0,0)
code: `osc(30).layer(osc(15).rotate(1).luma()).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -635,6 +693,7 @@ voronoi(25,0,0)
code: `shape().scale(0.5).blend(shape(4),[0,0.25,0.5,0.75,1]).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -642,6 +701,7 @@ voronoi(25,0,0)
code: `osc(9,0.1,1).blend(osc(13,0.5,5)).out()`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -649,6 +709,7 @@ voronoi(25,0,0)
code: `osc().thresh().blend(o0,0.9).out(o0)`,
comments: {
en: "motion-blur like feedback",
+ es: "feedback con apariencia difuminada",
ja: "",
}
},
@@ -661,6 +722,7 @@ voronoi(25,0,0)
code: `osc(9,0.1,2).mult(osc(13,0.5,5)).out()`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -671,6 +733,7 @@ osc()
.out(o0)`,
comments: {
en: "mult is *not* transparent; compare with mask",
+ es: "mult *no* es transparente; compárese con mask",
ja: "",
}
},
@@ -683,6 +746,7 @@ osc()
code: `osc(9,0.1,1).diff(osc(13,0.5,5)).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -696,6 +760,7 @@ osc(1,1,2)
.out()`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -717,6 +782,7 @@ voronoi()
.out(o0)`,
comments: {
en: "chocolate whirlpool",
+ es: "remolino de chocolate",
ja: "",
}
},
@@ -727,6 +793,7 @@ osc(3,0,2)
.out(o0)`,
comments: {
en: "color remapping",
+ es: "reasignación de colores",
ja: "",
}
},
@@ -742,6 +809,7 @@ gradient(5).repeat(50,50).kaleid([3,5,7,9].fast(0.5))
.out(o0)`,
comments: {
en: "cosmic radiation",
+ es: "radiación cósmica",
ja: "",
}
},
@@ -749,6 +817,7 @@ gradient(5).repeat(50,50).kaleid([3,5,7,9].fast(0.5))
code: `shape(4).modulateScale(gradient().g(),2,0.5).out(o0)`,
comments: {
en: "perspective",
+ es: "perspectiva",
ja: "",
}
},
@@ -764,6 +833,7 @@ voronoi(10,1,5).brightness(()=>Math.random()*0.15)
.out(o0)`,
comments: {
en: "what lies beneath",
+ es: "lo que se encuentra por debajo",
ja: "",
}
},
@@ -773,6 +843,7 @@ noise(3).modulatePixelate(noise(3).pixelate(8,8),1024,8)
.out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -789,6 +860,7 @@ voronoi(100,3,5)
.out(o0)`,
comments: {
en: "wormhole",
+ es: "agujero de gusano",
ja: "",
}
},
@@ -796,6 +868,7 @@ voronoi(100,3,5)
code: `osc().modulateRotate(shape(999,0.3,0.5),1.57).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -812,6 +885,7 @@ src(o0)
.out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -824,6 +898,7 @@ src(o0)
code: `solid(1,1,1).invert([0,1]).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -834,6 +909,7 @@ osc(4,0.1,2).invert().luma().invert()
.mask(shape(2,0.5).scrollY(-0.25))).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -846,6 +922,7 @@ osc(4,0.1,2).invert().luma().invert()
code: `osc(20).contrast( () => Math.sin(time) * 5 ).out(o0)`,
comments: {
en: "20Hz oscillator with contrast interpolating between 0.0-5.0",
+ es: "oscilador a 20Hz con un contraste que cambia entre 0.0-5.0",
ja: "",
}
},
@@ -860,6 +937,7 @@ osc(20,0,2)
.out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -867,6 +945,7 @@ osc(20,0,2)
code: `noise().brightness(1).color(0.5,0.5,0.5).out(o0)`,
comments: {
en: "scaling noise value to 0-1",
+ es: "escalando el valor de noise a un rango de 0-1",
ja: "",
}
},
@@ -878,6 +957,7 @@ osc(20,0,2)
code: `gradient(5).mask(voronoi(),3,0.5).invert([0,1]).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -888,6 +968,7 @@ osc()
.out(o0)`,
comments: {
en: "mask is transparent; compare with mult",
+ es: "mask es transparente; compárese con mult",
ja: "",
}
},
@@ -901,6 +982,7 @@ osc(10,-0.25,1).color(0,0,1).saturate(2).kaleid(50)
.out(o0)`,
comments: {
en: "algae pulse",
+ es: "pulso de algas",
ja: "",
}
},
@@ -912,6 +994,7 @@ osc(10,-0.25,1).color(0,0,1).saturate(2).kaleid(50)
code: `osc(10,0,1).luma(0.5,0.1).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -919,6 +1002,7 @@ osc(10,-0.25,1).color(0,0,1).saturate(2).kaleid(50)
code: `osc(10,0,[0,0.5,1,2]).luma([0.1,0.25,0.75,1].fast(0.25),0.1).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -926,6 +1010,7 @@ osc(10,-0.25,1).color(0,0,1).saturate(2).kaleid(50)
code: `osc(30).layer(osc(15).rotate(1).luma()).out(o0)`,
comments: {
en: "luma is transparent; compare with thresh",
+ es: "luma es transparente; compárese con thresh",
ja: "",
}
},
@@ -937,6 +1022,7 @@ osc(10,-0.25,1).color(0,0,1).saturate(2).kaleid(50)
code: `noise(3,0.1).thresh(0.5,0.04).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -947,6 +1033,7 @@ noise(3,0.1)
.out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -954,6 +1041,7 @@ noise(3,0.1)
code: `osc(30).layer(osc(15).rotate(1).thresh()).out(o0)`,
comments: {
en: "thresh is *not* transparent; compare with luma",
+ es: "thresh *no* es transparente; compárese con luma",
ja: "",
}
},
@@ -965,6 +1053,7 @@ noise(3,0.1)
code: `osc().color(1,0,3).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -976,6 +1065,7 @@ noise(3,0.1)
code: `osc(10,0,1).saturate( () => Math.sin(time) * 10 ).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -987,6 +1077,7 @@ noise(3,0.1)
code: `osc(30,0.1,1).hue(() => Math.sin(time)).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1007,6 +1098,11 @@ osc(20)
// color sequence of Red, Green, Blue, White, Black
// colorama sequence of 0.005, 0.5, 1.0 at 1/8 speed
// output to buffer o0`,
+ es: `
+// oscilador de 20Hz
+// secuencia de color que cambia entre rojo, verde, azul, blanco y negro
+// secuencia de colorama de 0.005, 0.5, 1.0 a un octavo de velocidad
+// salida al buffer o0`,
ja: "デフォルト",
}
},
@@ -1014,6 +1110,7 @@ osc(20)
code: `osc(30,0.1,1).colorama(-0.1).out(o0)`,
comments: {
en: "negative value is less harsh",
+ es: "los valores negativos son más suaves",
ja: "",
}
},
@@ -1025,6 +1122,7 @@ osc(20)
code: `osc(60,0.1,1.5).layer(gradient().r()).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1036,6 +1134,7 @@ osc(20)
code: `osc(60,0.1,1.5).layer(gradient().g()).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1047,6 +1146,7 @@ osc(20)
code: `osc(60,0.1,1.5).layer(gradient().colorama(1).b()).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1060,6 +1160,7 @@ s0.initCam()
src(s0).invert().out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1073,6 +1174,7 @@ s0.initImage("https://upload.wikimedia.org/wikipedia/commons/2/25/Hydra-Foto.jpg
osc(6).modulate(src(s0),1).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1086,6 +1188,7 @@ s0.initVideo("https://media.giphy.com/media/AS9LIFttYzkc0/giphy.mp4")
src(s0).modulate(noise(3)).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1105,6 +1208,7 @@ s0.init({src:canvas})
src(s0).modulate(osc().kaleid(999)).out(o0)`,
comments: {
en: "load canvas",
+ es: "cargar canvas",
ja: "canvas をロード",
}
},
@@ -1118,6 +1222,7 @@ s0.initScreen()
src(s0).colorama(0.5).out(o0)`,
comments: {
en: "select a window",
+ es: "selecciona una ventana",
ja: "画面を選択",
}
},
@@ -1134,6 +1239,7 @@ gradient().out(o3)
render()`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1143,6 +1249,7 @@ voronoi().out(o1)
render(o1)`,
comments: {
en: "specify display buffer",
+ es: "especifica salida a renderizar",
ja: "",
}
},
@@ -1157,6 +1264,7 @@ update = () => b += 0.01 * Math.sin(time)
shape().scrollX(()=>b).out(o0)`,
comments: {
en: "update is called every frame",
+ es: "update es llamada cada fotograma",
ja: "",
}
},
@@ -1170,6 +1278,7 @@ setResolution(100,100)
osc().out(o0)`,
comments: {
en: "make the canvas small (100 pixel x 100 pixel)",
+ es: "hace al canvas muy pequeño (100 pixeles x 100 pixeles)",
ja: "",
}
},
@@ -1183,6 +1292,7 @@ osc().out(o0)
hush()`,
comments: {
en: "clear the buffers",
+ es: "limpia los buffers",
ja: "",
}
},
@@ -1208,6 +1318,7 @@ setFunction({
osc(60,0.1,1.5).chroma().out(o0)`,
comments: {
en: "from https://www.shadertoy.com/view/XsfGzn",
+ es: "sacado de https://www.shadertoy.com/view/XsfGzn",
ja: "",
}
},
@@ -1221,6 +1332,7 @@ speed = 3
osc(60,0.1,[0,1.5]).out(o0)`,
comments: {
en: "change overall speed",
+ es: "cambia la velocidad global",
ja: "",
}
},
@@ -1230,6 +1342,7 @@ speed = 0.1
osc(60,0.1,[0,1.5]).out(o0)`,
comments: {
en: "change overall speed",
+ es: "cambia la velocidad global",
ja: "",
}
},
@@ -1243,6 +1356,7 @@ bpm = 60
osc(60,0.1,[0,1.5]).out(o0)`,
comments: {
en: "change array speed",
+ es: "cambia la velocidad de los arrays",
ja: "",
}
},
@@ -1252,6 +1366,7 @@ bpm = 15
osc(60,0.1,[0,1.5]).out(o0)`,
comments: {
en: "change array speed",
+ es: "cambia la velocidad de los arrays",
ja: "",
}
},
@@ -1264,6 +1379,7 @@ osc(60,0.1,[0,1.5]).out(o0)`,
shape(99).scrollX(() => -mouse.x / width).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -1276,6 +1392,7 @@ shape(99).scrollX(() => -mouse.x / width).out(o0)`,
shape(99).scrollY(() => -mouse.y / height).out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -1287,6 +1404,7 @@ shape(99).scrollY(() => -mouse.y / height).out(o0)`,
code: `shape(2,0.8).kaleid(()=>6+Math.sin(time)*4).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1302,6 +1420,7 @@ shape(99).scroll(
.out(o0)`,
comments: {
en: "",
+ es: "",
ja: "",
}
},
@@ -1313,6 +1432,7 @@ shape(99).scroll(
code: `osc([10,30,60].fast(2),0.1,1.5).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1320,6 +1440,7 @@ shape(99).scroll(
code: `osc([10,30,60].fast(0.5),0.1,1.5).out(o0)`,
comments: {
en: "argument less than 1 makes transition slower",
+ es: "un argumento menor a 1 hace a las transiciones más lentas",
ja: "",
}
},
@@ -1331,6 +1452,7 @@ shape(99).scroll(
code: `shape(999).scrollX([-0.2,0.2].smooth()).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1342,6 +1464,7 @@ shape(99).scroll(
code: `shape(4).rotate([-3.14,3.14].ease('easeInOutCubic')).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1357,6 +1480,7 @@ shape(999).scrollY(.2).scrollX([-0.2,0.2])
).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1368,6 +1492,7 @@ shape(999).scrollY(.2).scrollX([-0.2,0.2])
code: `shape().scrollX([0,1,2,3,4].fit(-0.2,0.2)).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1379,6 +1504,7 @@ shape(999).scrollY(.2).scrollX([-0.2,0.2])
code: `osc().modulate(noise(3),()=>a.fft[0]).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1392,6 +1518,7 @@ a.setSmooth(0.8)
osc().modulate(noise(3),()=>a.fft[0]).out(o0)`,
comments: {
en: "default",
+ es: "default",
ja: "デフォルト",
}
},
@@ -1405,6 +1532,7 @@ a.setCutoff(4)
osc().modulate(noise(3),()=>a.fft[0]).out(o0)`,
comments: {
en: "threshold",
+ es: "umbral (threshold)",
ja: "",
}
},
@@ -1418,6 +1546,7 @@ a.setBins(8)
osc(60,0.1,()=>a.fft[7]*3).modulate(noise(3),()=>a.fft[0]).out(o0)`,
comments: {
en: "change color with hissing noise",
+ es: "cambiando el color con ruido",
ja: "",
}
},
@@ -1431,6 +1560,7 @@ a.setScale(5)
osc().modulate(noise(3),()=>a.fft[0]).out(o0)`,
comments: {
en: "the smaller the scale is, the bigger the output is",
+ es: "cuanto menor la escala, mayor es la salida",
ja: "",
}
},
diff --git a/index.js b/index.js
index 65055cc..b4e64d9 100644
--- a/index.js
+++ b/index.js
@@ -203,7 +203,7 @@ function mainView (state, emit) {
emit('clear details') }>
${i18next.t('title')}
- ${state.page.selected === null ? '' : `::: ${state.page.selected.name}`}
+ ${state.page.selected === null ? '' : ` ::: ${state.page.selected.name}`}
${ languageView(state, emit) }
diff --git a/locales.js b/locales.js
index fa49225..5afa9a6 100644
--- a/locales.js
+++ b/locales.js
@@ -24,6 +24,30 @@ module.exports = {
'openin': 'open in editor',
}
},
+ es: {
+ translation: {
+ 'language-name': 'Spanish',
+ 'example': 'Ejemplo',
+ 'usage': 'Uso',
+ 'title': 'Funciones de hydra',
+ 'intro': `Hay 5 tipos de funciones en hydra: señales generadoras (sources), de geometría, de color, de fusón, y de modulación.
+ Haz click en cualquier función aquí abajo para ver su uso. (Para una documentación más detallada, puedes ver la página web de hydra,
+ primeros pasos o el Hydra Book.)`,
+ 'editor-info': 'Edita el código y presiona el botón "▶" o usa "ctrl+enter" para ejecutarlo!',
+ 'src': 'Source',
+ 'coord': 'Geometría',
+ 'color': 'Color',
+ 'combine': 'Fusión',
+ 'combineCoord': 'Modulación',
+ 'ext': 'Fuentes externas',
+ 'settings': 'Ajustes del sintetizador',
+ 'array': 'Array',
+ 'audio': 'Audio',
+ 'run': 'ejecutar',
+ 'reset': 'reset',
+ 'openin': 'abrir en el editor',
+ }
+ },
ja: {
translation: {
'language-name': '日本語',