diff --git a/experiments/pilot-02b/css/chunk-vendors.fde1dbb5.css b/experiments/pilot-02b/css/chunk-vendors.fde1dbb5.css new file mode 100644 index 0000000..4ba108a --- /dev/null +++ b/experiments/pilot-02b/css/chunk-vendors.fde1dbb5.css @@ -0,0 +1 @@ +.experiment{box-sizing:border-box;margin:3% auto;width:900px;min-height:600px;border-radius:10px;border:1px solid #ababab;padding:20px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-align:center;position:relative;display:flex;flex-direction:column;color:rgba(0,0,0,.87);font-size:17px;line-height:27px;font-family:Lato,Noto Sans,sans-serif}.experiment.wide{width:100%;margin:0;min-height:98vh;border:none}.header{text-align:left;display:flex;flex-direction:row;flex-grow:0}.header .col{flex-shrink:0;flex-grow:1}.header .col:last-child{display:flex;flex-direction:row-reverse}.experiment.wide .header .col:last-child{flex-direction:row}.header .k-progress-outer{padding-right:0}h1,h2,h3,h4{color:rgba(0,0,0,.87);font-family:Playfair Display,"Noto Serif",serif;text-align:center}h1{font-size:34px}button{background-color:#5187ba;border:none;border-radius:2px;color:#fff;display:block;font-family:Lato,Noto Sans,sans-serif;font-size:12px;line-height:20px;font-weight:700;letter-spacing:.9px;margin:40px auto 20px auto;outline:none;padding:5px 10px;text-transform:uppercase}button:focus,button:hover{background-color:#324d93}img,video{max-width:100%;height:auto;max-height:400px;width:auto}.debug-statement[data-v-5a63c536]{border:2px solid #aa2935;border-radius:4px;color:#aa2935;text-align:left;padding:15px;position:fixed;bottom:10px;width:830px}.debug-statement[data-v-5a63c536],.debug-statement [data-v-5a63c536]{color:#aa2935}.screen[data-v-2db71145]{flex-grow:1;position:relative}textarea[data-v-20ec9a19]{border:2px solid #5187ba;border-radius:10px;display:block;font-size:16px;margin:0 auto;outline:none;padding:10px 20px}.option[data-v-0428af94]{background-color:#5187ba;border:none;border-radius:2px;color:#fff;cursor:pointer;display:inline-block;font-family:Lato,Noto Sans,sans-serif;font-size:12px;line-height:20px;font-weight:700;letter-spacing:.9px;margin:0 5px 20px 5px;outline:none;padding:5px 10px;text-transform:uppercase}.option[data-v-0428af94]:hover{background-color:#324d93}.options[data-v-36baf217]{display:flex;justify-content:center}.option img[data-v-36baf217]{margin:20px;height:100px;width:auto;cursor:pointer}.options[data-v-50f61df4]{display:flex;justify-content:center;gap:15px;margin:20px 0}.options .left[data-v-50f61df4],.options .right[data-v-50f61df4]{flex-grow:0;padding:0 15px}.options label[data-v-50f61df4]{flex-grow:0}.vue-slider-disabled{opacity:.5;cursor:not-allowed}.vue-slider-rail{background-color:#ccc;border-radius:15px}.vue-slider-process{background-color:#3498db;border-radius:15px}.vue-slider-mark{z-index:4}.vue-slider-mark:first-child .vue-slider-mark-step,.vue-slider-mark:last-child .vue-slider-mark-step{display:none}.vue-slider-mark-step{width:100%;height:100%;border-radius:50%;background-color:rgba(0,0,0,.16)}.vue-slider-mark-label{font-size:14px;white-space:nowrap}.vue-slider-dot-handle{cursor:pointer;width:100%;height:100%;border-radius:50%;background-color:#fff;box-sizing:border-box;box-shadow:.5px .5px 2px 1px rgba(0,0,0,.32)}.vue-slider-dot-handle-focus{box-shadow:0 0 1px 2px rgba(52,152,219,.36)}.vue-slider-dot-handle-disabled{cursor:not-allowed;background-color:#ccc}.vue-slider-dot-tooltip-inner{font-size:14px;white-space:nowrap;padding:2px 5px;min-width:20px;text-align:center;color:#fff;border-radius:5px;border-color:#3498db;background-color:#3498db;box-sizing:content-box}.vue-slider-dot-tooltip-inner:after{content:"";position:absolute}.vue-slider-dot-tooltip-inner-top:after{top:100%;left:50%;transform:translate(-50%);height:0;width:0;border-color:transparent;border-style:solid;border-width:5px;border-top-color:inherit}.vue-slider-dot-tooltip-inner-bottom:after{bottom:100%;left:50%;transform:translate(-50%);height:0;width:0;border-color:transparent;border-style:solid;border-width:5px;border-bottom-color:inherit}.vue-slider-dot-tooltip-inner-left:after{left:100%;top:50%;transform:translateY(-50%);height:0;width:0;border-color:transparent;border-style:solid;border-width:5px;border-left-color:inherit}.vue-slider-dot-tooltip-inner-right:after{right:100%;top:50%;transform:translateY(-50%);height:0;width:0;border-color:transparent;border-style:solid;border-width:5px;border-right-color:inherit}.vue-slider-dot-tooltip-wrapper{opacity:0;transition:all .3s}.vue-slider-dot-tooltip-wrapper-show{opacity:1}.slider-element[data-v-6c73a9d4]{display:flex;margin:20px 0}.slider-element .left[data-v-6c73a9d4],.slider-element .right[data-v-6c73a9d4]{flex-grow:0;padding:0 20px}.slider[data-v-6c73a9d4]{flex-grow:1}.textarea[data-v-7a50d03b]{position:relative;max-width:95%}textarea[data-v-7a50d03b]{border:2px solid #5187ba;border-radius:10px;display:block;font-size:16px;margin:0 auto;outline:none;padding:10px 20px;height:100%;width:100%}.options label[data-v-f03be8e0],.options label [data-v-f03be8e0]{cursor:pointer}.multiple-choice.vertical[data-v-f03be8e0]{text-align:left;width:500px;margin:0 auto}.multiple-choice.vertical label[data-v-f03be8e0]{display:block}.multiple-choice.horizontal label[data-v-f03be8e0]{display:inline-block;margin:0 10px}.option[data-v-f03be8e0]:hover{background-color:#324d93}.matrix-choice{text-align:left;width:100%}.matrix-choice .row{display:flex;flex-direction:row;align-items:center}.matrix-choice .row>:first-child{width:50%;text-align:right}.matrix-choice .row label{width:50px;display:inline-block;font-size:13px;margin:0 10px;text-align:center}.slider-element[data-v-5fcc2cd1]{display:flex;margin:20px 0}.slider-element .left[data-v-5fcc2cd1],.slider-element .right[data-v-5fcc2cd1]{flex-grow:0;padding:0 20px}.slider[data-v-5fcc2cd1]{flex-grow:1}.rankorder-input[data-v-cde501dc]{width:500px;text-align:left;margin:0 auto}.rankorder-input .item[data-v-cde501dc]{cursor:move;margin-bottom:10px}.pill[data-v-cde501dc]{background:#add8e6;border-radius:10px;display:inline-block;padding:0 3px;margin-right:10px}.option[data-v-e124492a]{background-color:#5187ba;border:none;border-radius:2px;color:#fff;cursor:pointer;display:inline-block;font-family:Lato,Noto Sans,sans-serif;font-size:30px;line-height:40px;font-weight:700;letter-spacing:.9px;margin:0 70px 70px 70px;outline:none;padding:5px 10px;text-transform:uppercase}.option[data-v-e124492a]:hover{background-color:#324d93}.text[data-v-752e72bd]{margin:30px auto}.text [data-v-752e72bd]{margin-right:5px}.text.underline-sentence [data-v-752e72bd]{margin-right:0;padding-right:5px;border-bottom:1px solid #000}.text.underline-words [data-v-752e72bd]{border-bottom:1px solid #000}.text[data-v-752e72bd] :not(.current){display:none}.text.show-all[data-v-752e72bd] :not(.current){color:transparent;display:inline}.text .current[data-v-752e72bd]{color:#000;display:inline}.chat{width:450px}.chat-box{overflow:auto;height:400px}.userEvent{width:45%;clear:both;text-align:center;margin:5px auto}.userEvent.me{color:rgba(112,186,81,.47843137254901963)!important}.message{width:55%;float:left;text-align:left;background:rgba(81,135,186,.47843137254901963);border-radius:4px;padding:4px;margin:5px 0}.message.me{float:right;background:rgba(112,186,81,.47843137254901963)!important}.chat-input{display:flex}.chat-input textarea{flex-grow:1;height:32px}.chat-input button{margin:0}td[data-v-681a623c]{max-width:150px;overflow:hidden;text-overflow:ellipsis}.debugResults[data-v-681a623c]{overflow-x:scroll}.instructions[data-v-286444fe]{width:600px;margin:0 auto;text-align:justify}.point[data-v-8ef3bc36]{position:absolute}.point.check[data-v-8ef3bc36]{position:fixed;left:50vw;top:40vh}.point[data-v-249dc640]{position:absolute}.point.check[data-v-249dc640]{position:fixed}.options[data-v-22cf83e4]{display:flex;flex-direction:row}.options .space[data-v-22cf83e4]{flex:1}.options .option1[data-v-22cf83e4],.options .option2[data-v-22cf83e4]{flex:0}.stimulus[data-v-22cf83e4]{bottom:200px;position:absolute;width:100%}button[data-v-22cf83e4]{bottom:20px;left:50%;position:absolute}.qud[data-v-22cf83e4]{position:relative;top:150px}.text[data-v-18f4a5b4]{margin:30px auto}.text [data-v-18f4a5b4]{margin-right:5px}.text.underline-sentence [data-v-18f4a5b4]{margin-right:0;padding-right:5px;border-bottom:1px solid #000}.text.underline-words [data-v-18f4a5b4]{border-bottom:1px solid #000}.text[data-v-18f4a5b4] :not(.current){display:none}.text.show-all[data-v-18f4a5b4] :not(.current){color:transparent;display:inline}.text .current[data-v-18f4a5b4]{color:#000;display:inline}.nocursor,.nocursor *{cursor:none!important}.noselect,.noselect *{user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none} \ No newline at end of file diff --git a/experiments/pilot-02b/index.html b/experiments/pilot-02b/index.html new file mode 100644 index 0000000..eefcc90 --- /dev/null +++ b/experiments/pilot-02b/index.html @@ -0,0 +1 @@ +Vue App
\ No newline at end of file diff --git a/experiments/pilot-02b/js/app.d366cdde.js b/experiments/pilot-02b/js/app.d366cdde.js new file mode 100644 index 0000000..efdbfed --- /dev/null +++ b/experiments/pilot-02b/js/app.d366cdde.js @@ -0,0 +1,2 @@ +(function(e){function o(o){for(var n,i,s=o[0],l=o[1],c=o[2],u=0,d=[];u1){var t=this.$magpie.socket.lastIterationResults,n=d.a.filter(t,(function(e){return"reproduction"==e.measure})),r=n[0];o=null==r?null:r.response}return o}}},f=h,m=t("2877"),v=Object(m["a"])(f,s,l,!1,null,null,null),y=v.exports,g={experimentId:"2",serverUrl:"https://magpie-temp.herokuapp.com/",socketUrl:"wss://magpie-temp.herokuapp.com/socket",completionUrl:"https://app.prolific.co/submissions/complete?cc=C13NOKGZ",contactEmail:"mchfranke@gmail.com",mode:"prolific",language:"en"};n["default"].config.productionTip=!1,n["default"].use(a.a,{prefix:"Canvas"}),n["default"].use(i["a"],g),new n["default"]({render:e=>e(y)}).$mount("#app")}}); +//# sourceMappingURL=app.d366cdde.js.map \ No newline at end of file diff --git a/experiments/pilot-02b/js/app.d366cdde.js.map b/experiments/pilot-02b/js/app.d366cdde.js.map new file mode 100644 index 0000000..286054a --- /dev/null +++ b/experiments/pilot-02b/js/app.d366cdde.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./trials/items.csv","webpack:///./src/App.vue?3502","webpack:///src/App.vue","webpack:///./src/App.vue?d83e","webpack:///./src/App.vue","webpack:///./src/magpie.config.js","webpack:///./src/main.js"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","executeModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","deferredModules","apply","checkDeferredModules","result","deferredModule","fulfilled","j","depId","splice","__webpack_require__","s","installedModules","jsonpScriptSrc","p","exports","module","l","e","promises","installedChunkData","promise","Promise","resolve","reject","onScriptComplete","script","document","createElement","charset","timeout","nc","setAttribute","src","error","Error","event","onerror","onload","clearTimeout","chunk","errorType","type","realSrc","target","message","name","request","undefined","setTimeout","head","appendChild","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","err","console","jsonpArray","window","oldJsonpFunction","slice","render","_vm","this","_c","_self","attrs","_v","on","$event","prepareData","$magpie","nextScreen","_l","trial","staticStyle","_s","getPreviousResponse","measurements","response","$set","saveAndNextScreen","trialNR","itemNr","itemName","condition","measure","getChoice","_e","staticRenderFns","log","items","computed","methods","output","trialData","socket","variant","chain","generation","guessingTrials","shuffle","filter","addExpData","lastIterationResults","filteredData","extractedRow","component","experimentId","serverUrl","socketUrl","completionUrl","contactEmail","language","config","productionTip","use","prefix","h","App","$mount"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GACnBK,EAAiBL,EAAK,GAIHM,EAAI,EAAGC,EAAW,GACpCD,EAAIH,EAASK,OAAQF,IACzBJ,EAAUC,EAASG,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBX,IAAYW,EAAgBX,IACpFK,EAASO,KAAKD,EAAgBX,GAAS,IAExCW,EAAgBX,GAAW,EAE5B,IAAID,KAAYG,EACZK,OAAOC,UAAUC,eAAeC,KAAKR,EAAaH,KACpDc,EAAQd,GAAYG,EAAYH,IAG/Be,GAAqBA,EAAoBhB,GAE5C,MAAMO,EAASC,OACdD,EAASU,OAATV,GAOD,OAHAW,EAAgBJ,KAAKK,MAAMD,EAAiBb,GAAkB,IAGvDe,IAER,SAASA,IAER,IADA,IAAIC,EACIf,EAAI,EAAGA,EAAIY,EAAgBV,OAAQF,IAAK,CAG/C,IAFA,IAAIgB,EAAiBJ,EAAgBZ,GACjCiB,GAAY,EACRC,EAAI,EAAGA,EAAIF,EAAed,OAAQgB,IAAK,CAC9C,IAAIC,EAAQH,EAAeE,GACG,IAA3BX,EAAgBY,KAAcF,GAAY,GAE3CA,IACFL,EAAgBQ,OAAOpB,IAAK,GAC5Be,EAASM,EAAoBA,EAAoBC,EAAIN,EAAe,KAItE,OAAOD,EAIR,IAAIQ,EAAmB,GAKnBhB,EAAkB,CACrB,IAAO,GAGJK,EAAkB,GAGtB,SAASY,EAAe5B,GACvB,OAAOyB,EAAoBI,EAAI,OAAS,GAAG7B,IAAUA,GAAW,IAAM,CAAC,iBAAiB,YAAYA,GAAW,MAIhH,SAASyB,EAAoB1B,GAG5B,GAAG4B,EAAiB5B,GACnB,OAAO4B,EAAiB5B,GAAU+B,QAGnC,IAAIC,EAASJ,EAAiB5B,GAAY,CACzCK,EAAGL,EACHiC,GAAG,EACHF,QAAS,IAUV,OANAjB,EAAQd,GAAUW,KAAKqB,EAAOD,QAASC,EAAQA,EAAOD,QAASL,GAG/DM,EAAOC,GAAI,EAGJD,EAAOD,QAKfL,EAAoBQ,EAAI,SAAuBjC,GAC9C,IAAIkC,EAAW,GAKXC,EAAqBxB,EAAgBX,GACzC,GAA0B,IAAvBmC,EAGF,GAAGA,EACFD,EAAStB,KAAKuB,EAAmB,QAC3B,CAEN,IAAIC,EAAU,IAAIC,SAAQ,SAASC,EAASC,GAC3CJ,EAAqBxB,EAAgBX,GAAW,CAACsC,EAASC,MAE3DL,EAAStB,KAAKuB,EAAmB,GAAKC,GAGtC,IACII,EADAC,EAASC,SAASC,cAAc,UAGpCF,EAAOG,QAAU,QACjBH,EAAOI,QAAU,IACbpB,EAAoBqB,IACvBL,EAAOM,aAAa,QAAStB,EAAoBqB,IAElDL,EAAOO,IAAMpB,EAAe5B,GAG5B,IAAIiD,EAAQ,IAAIC,MAChBV,EAAmB,SAAUW,GAE5BV,EAAOW,QAAUX,EAAOY,OAAS,KACjCC,aAAaT,GACb,IAAIU,EAAQ5C,EAAgBX,GAC5B,GAAa,IAAVuD,EAAa,CACf,GAAGA,EAAO,CACT,IAAIC,EAAYL,IAAyB,SAAfA,EAAMM,KAAkB,UAAYN,EAAMM,MAChEC,EAAUP,GAASA,EAAMQ,QAAUR,EAAMQ,OAAOX,IACpDC,EAAMW,QAAU,iBAAmB5D,EAAU,cAAgBwD,EAAY,KAAOE,EAAU,IAC1FT,EAAMY,KAAO,iBACbZ,EAAMQ,KAAOD,EACbP,EAAMa,QAAUJ,EAChBH,EAAM,GAAGN,GAEVtC,EAAgBX,QAAW+D,IAG7B,IAAIlB,EAAUmB,YAAW,WACxBxB,EAAiB,CAAEiB,KAAM,UAAWE,OAAQlB,MAC1C,MACHA,EAAOW,QAAUX,EAAOY,OAASb,EACjCE,SAASuB,KAAKC,YAAYzB,GAG5B,OAAOJ,QAAQ8B,IAAIjC,IAIpBT,EAAoB2C,EAAIvD,EAGxBY,EAAoB4C,EAAI1C,EAGxBF,EAAoB6C,EAAI,SAASxC,EAAS+B,EAAMU,GAC3C9C,EAAoB+C,EAAE1C,EAAS+B,IAClCtD,OAAOkE,eAAe3C,EAAS+B,EAAM,CAAEa,YAAY,EAAMC,IAAKJ,KAKhE9C,EAAoBmD,EAAI,SAAS9C,GACX,qBAAX+C,QAA0BA,OAAOC,aAC1CvE,OAAOkE,eAAe3C,EAAS+C,OAAOC,YAAa,CAAEC,MAAO,WAE7DxE,OAAOkE,eAAe3C,EAAS,aAAc,CAAEiD,OAAO,KAQvDtD,EAAoBuD,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQtD,EAAoBsD,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,kBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAK5E,OAAO6E,OAAO,MAGvB,GAFA3D,EAAoBmD,EAAEO,GACtB5E,OAAOkE,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOtD,EAAoB6C,EAAEa,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,GAIR1D,EAAoB8D,EAAI,SAASxD,GAChC,IAAIwC,EAASxC,GAAUA,EAAOmD,WAC7B,WAAwB,OAAOnD,EAAO,YACtC,WAA8B,OAAOA,GAEtC,OADAN,EAAoB6C,EAAEC,EAAQ,IAAKA,GAC5BA,GAIR9C,EAAoB+C,EAAI,SAASgB,EAAQC,GAAY,OAAOlF,OAAOC,UAAUC,eAAeC,KAAK8E,EAAQC,IAGzGhE,EAAoBI,EAAI,qDAGxBJ,EAAoBiE,GAAK,SAASC,GAA2B,MAApBC,QAAQ3C,MAAM0C,GAAYA,GAEnE,IAAIE,EAAaC,OAAO,gBAAkBA,OAAO,iBAAmB,GAChEC,EAAmBF,EAAWjF,KAAK0E,KAAKO,GAC5CA,EAAWjF,KAAOf,EAClBgG,EAAaA,EAAWG,QACxB,IAAI,IAAI5F,EAAI,EAAGA,EAAIyF,EAAWvF,OAAQF,IAAKP,EAAqBgG,EAAWzF,IAC3E,IAAIU,EAAsBiF,EAI1B/E,EAAgBJ,KAAK,CAAC,EAAE,kBAEjBM,K,kGC5NTa,EAAOD,QAAU,CAAC,CAAC,OAAS,EAAE,SAAW,cAAc,UAAY,cAAc,QAAU,uWAAuW,iBAAmB,iGAAiG,eAAiB,4EAA4E,aAAe,+MAA+M,CAAC,OAAS,EAAE,SAAW,cAAc,UAAY,eAAe,QAAU,uWAAuW,iBAAmB,2GAA2G,eAAiB,4EAA4E,aAAe,+MAA+M,CAAC,OAAS,EAAE,SAAW,cAAc,UAAY,cAAc,QAAU,uWAAuW,iBAAmB,+KAA+K,eAAiB,4EAA4E,aAAe,+MAA+M,CAAC,OAAS,EAAE,SAAW,cAAc,UAAY,kBAAkB,QAAU,uWAAuW,iBAAmB,8LAA8L,eAAiB,4EAA4E,aAAe,iN,4FCAr3GmE,EAAS,WAAkB,IAAIC,EAAIC,KAAKC,EAAGF,EAAIG,MAAMD,GAAG,OAAOA,EAAG,aAAa,CAACE,MAAM,CAAC,MAAQ,+BAA+B,CAACF,EAAG,oBAAoB,CAACE,MAAM,CAAC,MAAQ,YAAY,CAACJ,EAAIK,GAAG,qRAAqRH,EAAG,KAAKF,EAAIK,GAAG,iFAAiFH,EAAG,2BAA2B,CAACE,MAAM,CAAC,MAAQ,mBAAmBF,EAAG,4BAA4B,CAACE,MAAM,CAAC,MAAQ,gDAAgDF,EAAG,OAAO,CAACE,MAAM,CAAC,KAAO,GAAGE,GAAG,CAAC,KAAO,SAASC,GAAQP,EAAIQ,cAAcR,EAAIS,QAAQC,iBAAiBV,EAAIW,GAAIX,EAAS,OAAE,SAASY,EAAM1G,GAAG,MAAO,CAACgG,EAAG,SAAS,CAACf,IAAIjF,GAAG,CAACgG,EAAG,QAAQ,CAACA,EAAG,KAAK,CAACA,EAAG,SAAS,CAACF,EAAIK,GAAG,eAAeH,EAAG,IAAI,CAACF,EAAIK,GAAG,yKAAyKH,EAAG,MAAM,CAACW,YAAY,CAAC,mBAAmB,YAAY,CAACX,EAAG,SAAS,CAACF,EAAIK,GAAG,uCAAuCL,EAAIK,GAAG,KAAKH,EAAG,MAAMF,EAAIK,GAAG,oOAAoOH,EAAG,IAAI,CAACF,EAAIK,GAAG,0GAA0GH,EAAG,MAAM,CAACW,YAAY,CAAC,mBAAmB,YAAY,CAACX,EAAG,SAAS,CAACF,EAAIK,GAAG,qCAAqCH,EAAG,MAAMF,EAAIK,GAAG,IAAIL,EAAIc,GAAGd,EAAIe,uBAAuB,OAAOb,EAAG,IAAI,CAACA,EAAG,SAAS,CAACF,EAAIK,GAAG,eAAeL,EAAIK,GAAG,iNAAiNH,EAAG,oBAAoB,CAACE,MAAM,CAAC,SAAWJ,EAAIS,QAAQO,aAAaC,SAAS,QAAU,CAAC,6BAA8B,kBAAkBX,GAAG,CAAC,kBAAkB,CAAC,SAASC,GAAQ,OAAOP,EAAIkB,KAAKlB,EAAIS,QAAQO,aAAc,WAAYT,IAAS,SAASA,GAAQ,OAAOP,EAAIS,QAAQU,yBAAyBjB,EAAG,SAAS,CAACE,MAAM,CAAC,KAAO,CAC/zEgB,QAASlH,EACTmH,OAAQT,EAAMS,OACdC,SAAUV,EAAMU,SAChBC,UAAWX,EAAMW,UACjBC,QAAS,cACL,IAAI,GAAGtB,EAAG,SAAS,CAACf,IAAIjF,GAAG,CAACgG,EAAG,QAAQ,CAACA,EAAG,IAAI,CAACF,EAAIK,GAAG,mEAAmEL,EAAIc,GAAGd,EAAIyB,aAAa,QAAQvB,EAAG,gBAAgB,CAACE,MAAM,CAAC,SAAWJ,EAAIS,QAAQO,aAAaC,UAAUX,GAAG,CAAC,kBAAkB,SAASC,GAAQ,OAAOP,EAAIkB,KAAKlB,EAAIS,QAAQO,aAAc,WAAYT,OACpUP,EAAIS,QAAQO,aACd,SAAEd,EAAG,SAAS,CAACI,GAAG,CAAC,MAAQ,SAASC,GAAQ,OAAOP,EAAIS,QAAQU,uBAAuB,CAACnB,EAAIK,GAAG,cAAcL,EAAI0B,KAAKxB,EAAG,SAAS,CAACE,MAAM,CAAC,KAAO,CACzIgB,QAASlH,EAAE,EACXmH,OAAQT,EAAMS,OACdC,SAAUV,EAAMU,SAChBC,UAAWX,EAAMW,UACjBC,QAAS,qBACV,IAAI,GAAGtB,EAAG,SAAS,CAACf,IAAIjF,GAAG,CAACgG,EAAG,QAAQ,CAACA,EAAG,KAAK,CAACA,EAAG,SAAS,CAACF,EAAIK,GAAG,0CAA0CH,EAAG,IAAI,CAACF,EAAIK,GAAG,+NAA+NH,EAAG,SAAS,CAACF,EAAIK,GAAG,gGAAgGH,EAAG,gBAAgB,CAACE,MAAM,CAAC,SAAWJ,EAAIS,QAAQO,aAAaC,UAAUX,GAAG,CAAC,kBAAkB,SAASC,GAAQ,OAAOP,EAAIkB,KAAKlB,EAAIS,QAAQO,aAAc,WAAYT,OAAYL,EAAG,IAAI,CAACF,EAAIK,GAAG,+MAA+MH,EAAG,MAAM,CAACW,YAAY,CAAC,mBAAmB,YAAY,CAACX,EAAG,SAAS,CAACF,EAAIK,GAAG,uCAAuCL,EAAIK,GAAG,KAAKH,EAAG,MAAMF,EAAIK,GAAG,oOACn/BL,EAAIS,QAAQO,aACd,SAAEd,EAAG,SAAS,CAACI,GAAG,CAAC,MAAQ,SAASC,GAAQ,OAAOP,EAAIS,QAAQU,uBAAuB,CAACnB,EAAIK,GAAG,cAAcL,EAAI0B,KAAKxB,EAAG,SAAS,CAACE,MAAM,CAAC,KAAO,CACzIgB,QAASlH,EAAE,EACXmH,OAAQT,EAAMS,OACdC,SAAUV,EAAMU,SAChBC,UAAWX,EAAMW,UACjBC,QAAS,oBACV,IAAI,OAAMtB,EAAG,kBAAkBA,EAAG,wBAAwB,IAExEyB,EAAkB,G,0CC8GtBjC,QAAQkC,IAAI,gCAEG,OACbjE,KAAM,MACN,OAEE,MAAO,CAAEkE,MAAO,IAAM/B,MAAM,EAAG,KAEjCgC,SAAU,CAER,IACE,OAAO,MAGXC,QAAS,CACPN,UAAW,WAET,IAAIO,EAAsC,MAA7B/B,KAAKQ,QAAQwB,UAAU,GAAY,KAAOhC,KAAKQ,QAAQwB,UAAU,GAAG,GAAGhB,SACpF,OAAO,GAGTT,YAAa,WACXd,QAAQkC,IAAI,YAAa3B,KAAKQ,QAAQyB,OAAOC,SAC7CzC,QAAQkC,IAAI,UAAW3B,KAAKQ,QAAQyB,OAAOE,OAC3C1C,QAAQkC,IAAI,eAAgB3B,KAAKQ,QAAQyB,OAAOG,YAChD,IAAIF,EAAUlC,KAAKQ,QAAQyB,OAAOC,QAClClC,KAAKqC,eAAiB,IAAEC,QAAQ,IAAEC,OAAOvC,KAAKqC,eAAgB,CAAC,QAAYH,KAC3ElC,KAAKQ,QAAQgC,WAAW,CAAC,QAAWxC,KAAKQ,QAAQyB,OAAOC,QAC/B,WAAclC,KAAKQ,QAAQyB,OAAOG,WAClC,MAASpC,KAAKQ,QAAQyB,OAAOE,MAC7B,eAAmBnC,KAAKc,yBAEnDA,oBAAqB,WAGnB,IAAIsB,EAAapC,KAAKQ,QAAQyB,OAAOG,WAEjCL,EAAS,wEAGb,GAAIK,EAAa,EAAG,CAGjB,IAAIK,EAAuBzC,KAAKQ,QAAQyB,OAAOQ,qBAO3CC,EAAe,IAAEH,OAAOE,GAAsB,SAASpE,GAAI,MAAoB,gBAAbA,EAAEkD,WACpEoB,EAAeD,EAAa,GAGhCX,EAAyB,MAAhBY,EAAuB,KAAOA,EAAa3B,SAGvD,OAAM,KC/L0K,I,YCOlL4B,EAAY,eACd,EACA9C,EACA4B,GACA,EACA,KACA,KACA,MAIa,EAAAkB,E,QClBA,GACbC,aAAc,IACdC,UAAW,qCACXC,UAAW,yCACXC,cAAe,2DACfC,aAAc,sBAEdnE,KAAM,WACNoE,SAAU,MCFZ,aAAIC,OAAOC,eAAgB,EAG3B,aAAIC,IAAI,IAAU,CAAEC,OAAQ,WAG5B,aAAID,IAAI,OAAW,GAGnB,IAAI,aAAI,CACNvD,OAASyD,GAAMA,EAAEC,KAChBC,OAAO","file":"js/app.d366cdde.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n \t\tvar executeModules = data[2];\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t\t// add entry modules from loaded chunk to deferred list\n \t\tdeferredModules.push.apply(deferredModules, executeModules || []);\n\n \t\t// run deferred modules when all chunks ready\n \t\treturn checkDeferredModules();\n \t};\n \tfunction checkDeferredModules() {\n \t\tvar result;\n \t\tfor(var i = 0; i < deferredModules.length; i++) {\n \t\t\tvar deferredModule = deferredModules[i];\n \t\t\tvar fulfilled = true;\n \t\t\tfor(var j = 1; j < deferredModule.length; j++) {\n \t\t\t\tvar depId = deferredModule[j];\n \t\t\t\tif(installedChunks[depId] !== 0) fulfilled = false;\n \t\t\t}\n \t\t\tif(fulfilled) {\n \t\t\t\tdeferredModules.splice(i--, 1);\n \t\t\t\tresult = __webpack_require__(__webpack_require__.s = deferredModule[0]);\n \t\t\t}\n \t\t}\n\n \t\treturn result;\n \t}\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t\"app\": 0\n \t};\n\n \tvar deferredModules = [];\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"js/\" + ({}[chunkId]||chunkId) + \".\" + {\"chunk-1335a3e6\":\"3abed9a7\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\n \t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n \t\t\t// a Promise means \"currently loading\".\n \t\t\tif(installedChunkData) {\n \t\t\t\tpromises.push(installedChunkData[2]);\n \t\t\t} else {\n \t\t\t\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/magpie3-causal-implicature/experiments/pilot-02b/\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// add entry module to deferred list\n \tdeferredModules.push([0,\"chunk-vendors\"]);\n \t// run deferred modules when ready\n \treturn checkDeferredModules();\n","module.exports = [{\"itemNr\":1,\"itemName\":\"spaceColony\",\"condition\":\"association\",\"context\":\"You are leading a group of colonists to a far away planet called Xelifan-3. To survive on Xelifan-3, the colonists need constant supply of the seeds of a plant called xeliherb, which grows sparsely and only on Xelifan-3. You will need to cultivate xeliherb to ensure survival of the colonists. Your science team have explored the planet and found that ... \",\"criticalSentence\":\"... a high yield of xeliherb is associated with the presence of another plant called ralocrop.\",\"furtherContext\":\"However, the cultivation of ralocrop is costly (water, energy resources).\",\"taskQuestion\":\"Based on the evidence reported by your science team, would you decide to cultivate both xeliherb and ralocrop on the fields available to your colony for agriculture, or would you only cultivate xeliherb?\"},{\"itemNr\":1,\"itemName\":\"spaceColony\",\"condition\":\"intervention\",\"context\":\"You are leading a group of colonists to a far away planet called Xelifan-3. To survive on Xelifan-3, the colonists need constant supply of the seeds of a plant called xeliherb, which grows sparsely and only on Xelifan-3. You will need to cultivate xeliherb to ensure survival of the colonists. Your science team have explored the planet and found that ... \",\"criticalSentence\":\"... a high yield of xeliherb was obtained whenever another plant called ralocrop was cultivated as well.\",\"furtherContext\":\"However, the cultivation of ralocrop is costly (water, energy resources).\",\"taskQuestion\":\"Based on the evidence reported by your science team, would you decide to cultivate both xeliherb and ralocrop on the fields available to your colony for agriculture, or would you only cultivate xeliherb?\"},{\"itemNr\":1,\"itemName\":\"spaceColony\",\"condition\":\"commonCause\",\"context\":\"You are leading a group of colonists to a far away planet called Xelifan-3. To survive on Xelifan-3, the colonists need constant supply of the seeds of a plant called xeliherb, which grows sparsely and only on Xelifan-3. You will need to cultivate xeliherb to ensure survival of the colonists. Your science team have explored the planet and found that ... \",\"criticalSentence\":\"... a high yield of xeliherb is associated with the presence of another plant called ralocrop. But they also found that ralocrop only grows on particularly fertile grounds.\",\"furtherContext\":\"However, the cultivation of ralocrop is costly (water, energy resources).\",\"taskQuestion\":\"Based on the evidence reported by your science team, would you decide to cultivate both xeliherb and ralocrop on the fields available to your colony for agriculture, or would you only cultivate xeliherb?\"},{\"itemNr\":1,\"itemName\":\"spaceColony\",\"condition\":\"deniedCausation\",\"context\":\"You are leading a group of colonists to a far away planet called Xelifan-3. To survive on Xelifan-3, the colonists need constant supply of the seeds of a plant called xeliherb, which grows sparsely and only on Xelifan-3. You will need to cultivate xeliherb to ensure survival of the colonists. Your science team have explored the planet and found that ... \",\"criticalSentence\":\"... a high yield of xeliherb is associated with the presence of another plant called ralocrop. But there is no evidence that the cultivation of ralocrop causes a better yield of xeliherb.\",\"furtherContext\":\"However, the cultivation of ralocrop is costly (water, energy resources).\",\"taskQuestion\":\"Based on the evidence reported by your science team, would you decide to cultivate both xeliherb and ralocrop on the fields available to your colony for agriculture, or would you only cultivate xeliherb?\"}]","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('Experiment',{attrs:{\"title\":\"Decision-making experiment\"}},[_c('InstructionScreen',{attrs:{\"title\":'Welcome'}},[_vm._v(\" In this short experiment you will first read a description about a fictitious context in which you are supposed to make an decision based on some information you received from others. Please read the context information very carefully and make your decision deliberately. \"),_c('p'),_vm._v(\" After your choice, we will ask you to explain your choice in a few words. \")]),_c('ConnectInteractiveScreen',{attrs:{\"title\":'Connecting...'}}),_c('AwaitIteratedResultScreen',{attrs:{\"title\":'Waiting for previous participant to finish'}}),_c('Wait',{attrs:{\"time\":0},on:{\"done\":function($event){_vm.prepareData();_vm.$magpie.nextScreen()}}}),_vm._l((_vm.items),function(trial,i){return [_c('Screen',{key:i},[_c('Slide',[_c('h2',[_c('strong',[_vm._v(\"Context\")])]),_c('p',[_vm._v(\"You are leading a group of colonists to a far away planet called Xelifan-3. The information you received from Mission Control when you departed months ago is this:\")]),_c('div',{staticStyle:{\"background-color\":\"#FF9999\"}},[_c('strong',[_vm._v(\"Information from Mission Control:\")]),_vm._v(\" \"),_c('br'),_vm._v(\" Two plants grow exclusively on Xelifan-3. They are called xeliherb and ralocrop. To survive on Xelifan-3, you need constant supply of the seeds of xeliherb. The cultivation of ralocrop is costly (water, energy resources).\")]),_c('p',[_vm._v(\"On arrival to Xelifan-3 you find a message left by earlier colonists. Here is what the message says:\")]),_c('div',{staticStyle:{\"background-color\":\"#AAAAFF\"}},[_c('strong',[_vm._v(\"Message from earlier colonists:\")]),_c('br'),_vm._v(\" \"+_vm._s(_vm.getPreviousResponse())+\" \")]),_c('p',[_c('strong',[_vm._v(\"Question:\")]),_vm._v(\" Based on the information provided by Mission Control and the earlier colonists, will you cultivate both xeliherb and ralocrop on the fields available to your colony, or will you only cultivate xeliherb?\")]),_c('ForcedChoiceInput',{attrs:{\"response\":_vm.$magpie.measurements.response,\"options\":['both xeliherb and ralocrop', 'only xeliherb']},on:{\"update:response\":[function($event){return _vm.$set(_vm.$magpie.measurements, \"response\", $event)},function($event){return _vm.$magpie.saveAndNextScreen()}]}}),_c('Record',{attrs:{\"data\":{\n trialNR: i,\n itemNr: trial.itemNr,\n itemName: trial.itemName,\n condition: trial.condition,\n measure: 'choice'\n }}})],1)],1),_c('Screen',{key:i},[_c('Slide',[_c('p',[_vm._v(\" Please give a short explanation for why you chose to cultivate \"+_vm._s(_vm.getChoice())+\"! \")]),_c('TextareaInput',{attrs:{\"response\":_vm.$magpie.measurements.response},on:{\"update:response\":function($event){return _vm.$set(_vm.$magpie.measurements, \"response\", $event)}}}),(\n _vm.$magpie.measurements.response\n )?_c('button',{on:{\"click\":function($event){return _vm.$magpie.saveAndNextScreen()}}},[_vm._v(\" Submit \")]):_vm._e(),_c('Record',{attrs:{\"data\":{\n trialNR: i+1,\n itemNr: trial.itemNr,\n itemName: trial.itemName,\n condition: trial.condition,\n measure: 'justification'\n }}})],1)],1),_c('Screen',{key:i},[_c('Slide',[_c('h2',[_c('strong',[_vm._v(\"Oh, no! Abort mission immediately!\")])]),_c('p',[_vm._v(\" Due to atmospheric conditions and technical problems you are forced to leave Xelifan-3 in a rush. You should make sure that the information you received from the earlier colonists is not lost to whoever may come next. \"),_c('strong',[_vm._v(\"Please write down what you recall from the earlier colonists' message into the text box!\")])]),_c('TextareaInput',{attrs:{\"response\":_vm.$magpie.measurements.response},on:{\"update:response\":function($event){return _vm.$set(_vm.$magpie.measurements, \"response\", $event)}}}),_c('p',[_vm._v(\" For clarity, you do NOT have to repeat the information received from Mission Control, which is repeated below for your convenience. Only reproduce the message you received from the earlier colonists. \")]),_c('div',{staticStyle:{\"background-color\":\"#FF9999\"}},[_c('strong',[_vm._v(\"Information from Mission Control:\")]),_vm._v(\" \"),_c('br'),_vm._v(\" Two plants grow exclusively on Xelifan-3. They are called xeliherb and ralocrop. To survive on Xelifan-3, you need constant supply of the seeds of xeliherb. The cultivation of ralocrop is costly (water, energy resources).\")]),(\n _vm.$magpie.measurements.response\n )?_c('button',{on:{\"click\":function($event){return _vm.$magpie.saveAndNextScreen()}}},[_vm._v(\" Submit \")]):_vm._e(),_c('Record',{attrs:{\"data\":{\n trialNR: i+2,\n itemNr: trial.itemNr,\n itemName: trial.itemName,\n condition: trial.condition,\n measure: 'reproduction'\n }}})],1)],1)]}),_c('PostTestScreen'),_c('SubmitResultsScreen')],2)\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n\n","import mod from \"-!../node_modules/cache-loader/dist/cjs.js??ref--1-0!../node_modules/vue-loader/lib/index.js??vue-loader-options!./App.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../node_modules/cache-loader/dist/cjs.js??ref--1-0!../node_modules/vue-loader/lib/index.js??vue-loader-options!./App.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./App.vue?vue&type=template&id=e17dde6c&\"\nimport script from \"./App.vue?vue&type=script&lang=js&\"\nexport * from \"./App.vue?vue&type=script&lang=js&\"\n\n\n/* normalize component */\nimport normalizer from \"!../node_modules/vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n null,\n null\n \n)\n\nexport default component.exports","export default {\n experimentId: '2',\n serverUrl: 'https://magpie-temp.herokuapp.com/',\n socketUrl: 'wss://magpie-temp.herokuapp.com/socket', // this will be used in prolific mode\n completionUrl: 'https://app.prolific.co/submissions/complete?cc=C13NOKGZ',\n contactEmail: 'mchfranke@gmail.com',\n // Either 'debug', 'directLink' or 'prolific'\n mode: 'prolific',\n language: 'en'\n};\n","import Vue from 'vue';\nimport VueKonva from 'vue-konva';\nimport VueMagpie from 'magpie-base';\nimport App from './App.vue';\nimport magpieConfig from './magpie.config.js';\n\nVue.config.productionTip = false;\n\n// Load Konva components\nVue.use(VueKonva, { prefix: 'Canvas' });\n\n// Load magpie components\nVue.use(VueMagpie, magpieConfig);\n\n// start app\nnew Vue({\n render: (h) => h(App)\n}).$mount('#app');\n"],"sourceRoot":""} \ No newline at end of file diff --git a/experiments/pilot-02b/js/chunk-1335a3e6.3abed9a7.js b/experiments/pilot-02b/js/chunk-1335a3e6.3abed9a7.js new file mode 100644 index 0000000..d35a640 --- /dev/null +++ b/experiments/pilot-02b/js/chunk-1335a3e6.3abed9a7.js @@ -0,0 +1,8 @@ +(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-1335a3e6"],{"04d1":function(t,e,n){(function(t,s){s(e,n("278c"),n("970b"),n("5bc3"))})(0,(function(t,e,n,s){"use strict";function i(t){return t&&"object"===typeof t&&"default"in t?t:{default:t}}var r=i(e),o=i(n),a=i(s),c=function(t,e,n){return{endTime:e,insertTime:n,type:"exponentialRampToValue",value:t}},u=function(t,e,n){return{endTime:e,insertTime:n,type:"linearRampToValue",value:t}},l=function(t,e){return{startTime:e,type:"setValue",value:t}},h=function(t,e,n){return{duration:n,startTime:e,type:"setValueCurve",values:t}},p=function(t,e,n){var s=n.startTime,i=n.target,r=n.timeConstant;return i+(e-i)*Math.exp((s-t)/r)},d=function(t){return"exponentialRampToValue"===t.type},f=function(t){return"linearRampToValue"===t.type},m=function(t){return d(t)||f(t)},_=function(t){return"setValue"===t.type},g=function(t){return"setValueCurve"===t.type},v=function t(e,n,s,i){var r=e[n];return void 0===r?i:m(r)||_(r)?r.value:g(r)?r.values[r.values.length-1]:p(s,t(e,n-1,r.startTime,i),r)},y=function(t,e,n,s,i){return void 0===n?[s.insertTime,i]:m(n)?[n.endTime,n.value]:_(n)?[n.startTime,n.value]:g(n)?[n.startTime+n.duration,n.values[n.values.length-1]]:[n.startTime,v(t,e-1,n.startTime,i)]},w=function(t){return"cancelAndHold"===t.type},x=function(t){return"cancelScheduledValues"===t.type},T=function(t){return w(t)||x(t)?t.cancelTime:d(t)||f(t)?t.endTime:t.startTime},b=function(t,e,n,s){var i=s.endTime,r=s.value;return n===r?r:0=e:T(n)>=e})),s=this._automationEvents[n];if(-1!==n&&(this._automationEvents=this._automationEvents.slice(0,n)),w(t)){var i=this._automationEvents[this._automationEvents.length-1];if(void 0!==s&&m(s)){if(k(i))throw new Error("The internal list is malformed.");var r=g(i)?i.startTime+i.duration:T(i),o=g(i)?i.values[i.values.length-1]:i.value,a=d(s)?b(e,r,o,s):C(e,r,o,s),p=d(s)?c(a,e,this._currenTime):u(a,e,this._currenTime);this._automationEvents.push(p)}void 0!==i&&k(i)&&this._automationEvents.push(l(this.getValue(e),e)),void 0!==i&&g(i)&&i.startTime+i.duration>e&&(this._automationEvents[this._automationEvents.length-1]=h(new Float32Array([6,7]),i.startTime,e-i.startTime))}}else{var _=this._automationEvents.findIndex((function(t){return T(t)>e})),v=-1===_?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[_-1];if(void 0!==v&&g(v)&&T(v)+v.duration>e)return!1;var y=d(t)?c(t.value,t.endTime,this._currenTime):f(t)?u(t.value,e,this._currenTime):t;if(-1===_)this._automationEvents.push(y);else{if(g(t)&&e+t.duration>T(this._automationEvents[_]))return!1;this._automationEvents.splice(_,0,y)}}return!0}},{key:"flush",value:function(t){var e=this._automationEvents.findIndex((function(e){return T(e)>t}));if(e>1){var n=this._automationEvents.slice(e-1),s=n[0];k(s)&&n.unshift(l(v(this._automationEvents,e-2,s.startTime,this._defaultValue),s.startTime)),this._automationEvents=n}}},{key:"getValue",value:function(t){if(0===this._automationEvents.length)return this._defaultValue;var e=this._automationEvents.findIndex((function(e){return T(e)>t})),n=this._automationEvents[e],s=(-1===e?this._automationEvents.length:e)-1,i=this._automationEvents[s];if(void 0!==i&&k(i)&&(void 0===n||!m(n)||n.insertTime>t))return p(t,v(this._automationEvents,s-1,i.startTime,this._defaultValue),i);if(void 0!==i&&_(i)&&(void 0===n||!m(n)))return i.value;if(void 0!==i&&g(i)&&(void 0===n||!m(n)||i.startTime+i.duration>t))return tnew DOMException("","AbortError"),c=t=>(e,n,[s,i,r],o)=>{t(e[i],[n,s,r],t=>t[0]===n&&t[1]===s,o)},u=t=>(e,n,s)=>{const i=[];for(let t=0;t(e,n)=>{t.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:n})},h=new WeakSet,p=new WeakMap,d=new WeakMap,f=new WeakMap,m=new WeakMap,_=new WeakMap,g=new WeakMap,v=new WeakMap,y=new WeakMap,w=new WeakMap,x={construct(){return x}},T=t=>{try{const e=new Proxy(t,x);new e}catch{return!1}return!0},b=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,C=(t,e)=>{const n=[];let s=t.replace(/^[\s]+/,""),i=s.match(b);while(null!==i){const t=i[1].slice(1,-1),r=i[0].replace(/([\s]+)?;?$/,"").replace(t,new URL(t,e).toString());n.push(r),s=s.slice(i[0].length).replace(/^[\s]+/,""),i=s.match(b)}return[n.join(";"),s]},A=t=>{if(void 0!==t&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},S=t=>{if(!T(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(null===t.prototype||"object"!==typeof t.prototype)throw new TypeError("The given value for processorCtor should have a prototype.")},k=(t,e,n,s,i,r,o,a,c,u,l,h,p)=>{let d=0;return(f,m,_={credentials:"omit"})=>{const g=l.get(f);if(void 0!==g&&g.has(m))return Promise.resolve();const v=u.get(f);if(void 0!==v){const t=v.get(m);if(void 0!==t)return t}const w=r(f),x=void 0===w.audioWorklet?i(m).then(([t,e])=>{const[s,i]=C(t,e),r=`${s};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${i}\n})})(window,'_AWGS')`;return n(r)}).then(()=>{const t=p._AWGS.pop();if(void 0===t)throw new SyntaxError;s(w.currentTime,w.sampleRate,()=>t(class{},void 0,(t,n)=>{if(""===t.trim())throw e();const s=y.get(w);if(void 0!==s){if(s.has(t))throw e();S(n),A(n.parameterDescriptors),s.set(t,n)}else S(n),A(n.parameterDescriptors),y.set(w,new Map([[t,n]]))},w.sampleRate,void 0,void 0))}):Promise.all([i(m),Promise.resolve(t(h,h))]).then(([[t,e],n])=>{const s=d+1;d=s;const[i,r]=C(t,e),u=n?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}",l=n?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));",h=n?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));",p=`${i};((AudioWorkletProcessor,registerProcessor)=>{${r}\n})(${u},(n,p)=>registerProcessor(n,class extends p{${l}process(i,o,p){${h}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${s}',class extends AudioWorkletProcessor{process(){return !1}})`,f=new Blob([p],{type:"application/javascript; charset=utf-8"}),m=URL.createObjectURL(f);return w.audioWorklet.addModule(m,_).then(()=>{if(a(w))return w;const t=o(w);return t.audioWorklet.addModule(m,_).then(()=>t)}).then(t=>{if(null===c)throw new SyntaxError;try{new c(t,"__sac"+s)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(m))});return void 0===v?u.set(f,new Map([[m,x]])):v.set(m,x),x.then(()=>{const t=l.get(f);void 0===t?l.set(f,new Set([m])):t.add(m)}).finally(()=>{const t=u.get(f);void 0!==t&&t.delete(m)}),x}},O=(t,e)=>{const n=t.get(e);if(void 0===n)throw new Error("A value with the given key could not be found.");return n},M=(t,e)=>{const n=Array.from(t).filter(e);if(n.length>1)throw Error("More than one element was found.");if(0===n.length)throw Error("No element was found.");const[s]=n;return t.delete(s),s},E=(t,e,n,s)=>{const i=O(t,e),r=M(i,t=>t[0]===n&&t[1]===s);return 0===i.size&&t.delete(e),r},D=t=>O(g,t),I=t=>{if(h.has(t))throw new Error("The AudioNode is already stored.");h.add(t),D(t).forEach(t=>t(!0))},R=t=>"port"in t,N=t=>{if(!h.has(t))throw new Error("The AudioNode is not stored.");h.delete(t),D(t).forEach(t=>t(!1))},V=(t,e)=>{!R(t)&&e.every(t=>0===t.size)&&N(t)},P=(t,e,n,s,i,r,o,a,c,u,l,h,p)=>{const d=new WeakMap;return(f,m,_,g,v)=>{const{activeInputs:y,passiveInputs:w}=r(m),{outputs:x}=r(f),T=a(f),b=r=>{const a=c(m),u=c(f);if(r){const e=E(w,f,_,g);t(y,f,e,!1),v||h(f)||n(u,a,_,g),p(m)&&I(m)}else{const t=s(y,f,_,g);e(w,g,t,!1),v||h(f)||i(u,a,_,g);const n=o(m);if(0===n)l(m)&&V(m,y);else{const t=d.get(m);void 0!==t&&clearTimeout(t),d.set(m,setTimeout(()=>{l(m)&&V(m,y)},1e3*n))}}};return!!u(x,[m,_,g],t=>t[0]===m&&t[1]===_&&t[2]===g,!0)&&(T.add(b),l(f)?t(y,f,[_,g,b],!0):e(w,g,[f,_,b],!0),!0)}},q=t=>(e,n,[s,i,r],o)=>{const a=e.get(s);void 0===a?e.set(s,new Set([[i,n,r]])):t(a,[i,n,r],t=>t[0]===i&&t[1]===n,o)},F=t=>(e,n)=>{const s=t(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});n.connect(s).connect(e.destination);const i=()=>{n.removeEventListener("ended",i),n.disconnect(s),s.disconnect()};n.addEventListener("ended",i)},j=t=>(e,n)=>{t(e).add(n)},L={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},W=(t,e,n,s,i,r)=>class extends t{constructor(t,n){const o=i(t),a={...L,...n},c=s(o,a),u=r(o)?e():null;super(t,!1,c,u),this._nativeAnalyserNode=c}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(t){this._nativeAnalyserNode.fftSize=t}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(t){const e=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=t,!(t>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=e,n()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(t){const e=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=t,!(this._nativeAnalyserNode.maxDecibels>t))throw this._nativeAnalyserNode.minDecibels=e,n()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(t){this._nativeAnalyserNode.smoothingTimeConstant=t}getByteFrequencyData(t){this._nativeAnalyserNode.getByteFrequencyData(t)}getByteTimeDomainData(t){this._nativeAnalyserNode.getByteTimeDomainData(t)}getFloatFrequencyData(t){this._nativeAnalyserNode.getFloatFrequencyData(t)}getFloatTimeDomainData(t){this._nativeAnalyserNode.getFloatTimeDomainData(t)}},B=(t,e)=>t.context===e,U=(t,e,n)=>()=>{const s=new WeakMap,i=async(i,r)=>{let o=e(i);const a=B(o,r);if(!a){const e={channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,fftSize:o.fftSize,maxDecibels:o.maxDecibels,minDecibels:o.minDecibels,smoothingTimeConstant:o.smoothingTimeConstant};o=t(r,e)}return s.set(r,o),await n(i,r,o),o};return{render(t,e){const n=s.get(e);return void 0!==n?Promise.resolve(n):i(t,e)}}},z=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},G=()=>new DOMException("","IndexSizeError"),X=t=>{t.getChannelData=(e=>n=>{try{return e.call(t,n)}catch(s){if(12===s.code)throw G();throw s}})(t.getChannelData)},Y={numberOfChannels:1},Z=(t,e,n,s,i,r,o,a)=>{let c=null;return class u{constructor(u){if(null===i)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:l,numberOfChannels:h,sampleRate:p}={...Y,...u};null===c&&(c=new i(1,1,44100));const d=null!==s&&e(r,r)?new s({length:l,numberOfChannels:h,sampleRate:p}):c.createBuffer(h,l,p);if(0===d.numberOfChannels)throw n();return"function"!==typeof d.copyFromChannel?(o(d),X(d)):e(z,()=>z(d))||a(d),t.add(d),d}static[Symbol.hasInstance](e){return null!==e&&"object"===typeof e&&Object.getPrototypeOf(e)===u.prototype||t.has(e)}}},H=-34028234663852886e22,$=-H,Q=t=>h.has(t),J={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},K=(t,e,n,s,i,r,o,a)=>class extends t{constructor(t,s){const a=r(t),c={...J,...s},u=i(a,c),l=o(a),h=l?e():null;super(t,!1,u,h),this._audioBufferSourceNodeRenderer=h,this._isBufferNullified=!1,this._isBufferSet=null!==c.buffer,this._nativeAudioBufferSourceNode=u,this._onended=null,this._playbackRate=n(this,l,u.playbackRate,$,H)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(t){if(this._nativeAudioBufferSourceNode.buffer=t,null!==t){if(this._isBufferSet)throw s();this._isBufferSet=!0}}get loop(){return this._nativeAudioBufferSourceNode.loop}set loop(t){this._nativeAudioBufferSourceNode.loop=t}get loopEnd(){return this._nativeAudioBufferSourceNode.loopEnd}set loopEnd(t){this._nativeAudioBufferSourceNode.loopEnd=t}get loopStart(){return this._nativeAudioBufferSourceNode.loopStart}set loopStart(t){this._nativeAudioBufferSourceNode.loopStart=t}get onended(){return this._onended}set onended(t){const e="function"===typeof t?a(this,t):null;this._nativeAudioBufferSourceNode.onended=e;const n=this._nativeAudioBufferSourceNode.onended;this._onended=null!==n&&n===e?t:n}get playbackRate(){return this._playbackRate}start(t=0,e=0,n){if(this._nativeAudioBufferSourceNode.start(t,e,n),null!==this._audioBufferSourceNodeRenderer&&(this._audioBufferSourceNodeRenderer.start=void 0===n?[t,e]:[t,e,n]),"closed"!==this.context.state){I(this);const t=()=>{this._nativeAudioBufferSourceNode.removeEventListener("ended",t),Q(this)&&N(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeAudioBufferSourceNode.stop(t),null!==this._audioBufferSourceNodeRenderer&&(this._audioBufferSourceNodeRenderer.stop=t)}},tt=(t,e,n,s,i)=>()=>{const r=new WeakMap;let o=null,a=null;const c=async(c,u)=>{let l=n(c);const h=B(l,u);if(!h){const t={buffer:l.buffer,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,loop:l.loop,loopEnd:l.loopEnd,loopStart:l.loopStart,playbackRate:l.playbackRate.value};l=e(u,t),null!==o&&l.start(...o),null!==a&&l.stop(a)}return r.set(u,l),h?await t(u,c.playbackRate,l.playbackRate):await s(u,c.playbackRate,l.playbackRate),await i(c,u,l),l};return{set start(t){o=t},set stop(t){a=t},render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):c(t,e)}}},et=t=>"playbackRate"in t,nt=t=>"frequency"in t&&"gain"in t,st=t=>"offset"in t,it=t=>!("frequency"in t)&&"gain"in t,rt=t=>"detune"in t&&"frequency"in t,ot=t=>"pan"in t,at=t=>O(p,t),ct=t=>O(f,t),ut=(t,e)=>{const{activeInputs:n}=at(t);n.forEach(n=>n.forEach(([n])=>{e.includes(t)||ut(n,[...e,t])}));const s=et(t)?[t.playbackRate]:R(t)?Array.from(t.parameters.values()):nt(t)?[t.Q,t.detune,t.frequency,t.gain]:st(t)?[t.offset]:it(t)?[t.gain]:rt(t)?[t.detune,t.frequency]:ot(t)?[t.pan]:[];for(const i of s){const t=ct(i);void 0!==t&&t.activeInputs.forEach(([t])=>ut(t,e))}Q(t)&&N(t)},lt=t=>{ut(t.destination,[])},ht=t=>void 0===t||"number"===typeof t||"string"===typeof t&&("balanced"===t||"interactive"===t||"playback"===t),pt=(t,e,n,s,i,r,o,a,c)=>class extends t{constructor(t={}){if(null===c)throw new Error("Missing the native AudioContext constructor.");let e;try{e=new c(t)}catch(o){if(12===o.code&&"sampleRate is not in range"===o.message)throw n();throw o}if(null===e)throw s();if(!ht(t.latencyHint))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&e.sampleRate!==t.sampleRate)throw n();super(e,2);const{latencyHint:i}=t,{sampleRate:r}=e;if(this._baseLatency="number"===typeof e.baseLatency?e.baseLatency:"balanced"===i?512/r:"interactive"===i||void 0===i?256/r:"playback"===i?1024/r:128*Math.max(2,Math.min(128,Math.round(i*r/128)))/r,this._nativeAudioContext=e,"webkitAudioContext"===c.name?(this._nativeGainNode=e.createGain(),this._nativeOscillatorNode=e.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(e.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,"running"===e.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw e()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close().then(()=>{null!==this._nativeGainNode&&null!==this._nativeOscillatorNode&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),lt(this)}))}createMediaElementSource(t){return new i(this,{mediaElement:t})}createMediaStreamDestination(){return new r(this)}createMediaStreamSource(t){return new o(this,{mediaStream:t})}createMediaStreamTrackSource(t){return new a(this,{mediaStreamTrack:t})}resume(){return"suspended"===this._state?new Promise((t,e)=>{const n=()=>{this._nativeAudioContext.removeEventListener("statechange",n),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",n)}):this._nativeAudioContext.resume().catch(t=>{if(void 0===t||15===t.code)throw e();throw t})}suspend(){return this._nativeAudioContext.suspend().catch(t=>{if(void 0===t)throw e();throw t})}},dt=(t,e,n,s,i,r,o,a)=>class extends t{constructor(t,n){const s=r(t),c=o(s),u=i(s,n,c),l=c?e(a):null;super(t,!1,u,l),this._isNodeOfNativeOfflineAudioContext=c,this._nativeAudioDestinationNode=u}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(t){if(this._isNodeOfNativeOfflineAudioContext)throw s();if(t>this._nativeAudioDestinationNode.maxChannelCount)throw n();this._nativeAudioDestinationNode.channelCount=t}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(t){if(this._isNodeOfNativeOfflineAudioContext)throw s();this._nativeAudioDestinationNode.channelCountMode=t}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}},ft=t=>{const e=new WeakMap,n=async(n,s)=>{const i=s.destination;return e.set(s,i),await t(n,s,i),i};return{render(t,s){const i=e.get(s);return void 0!==i?Promise.resolve(i):n(t,s)}}},mt=(t,e,n,s,i,r,o,a)=>(c,u)=>{const l=u.listener,h=()=>{const h=new Float32Array(1),p=e(u,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),d=o(u);let f=!1,m=[0,0,-1,0,1,0],_=[0,0,0];const g=()=>{if(f)return;f=!0;const t=s(u,256,9,0);t.onaudioprocess=({inputBuffer:t})=>{const e=[r(t,h,0),r(t,h,1),r(t,h,2),r(t,h,3),r(t,h,4),r(t,h,5)];e.some((t,e)=>t!==m[e])&&(l.setOrientation(...e),m=e);const n=[r(t,h,6),r(t,h,7),r(t,h,8)];n.some((t,e)=>t!==_[e])&&(l.setPosition(...n),_=n)},p.connect(t)},v=t=>e=>{e!==m[t]&&(m[t]=e,l.setOrientation(...m))},y=t=>e=>{e!==_[t]&&(_[t]=e,l.setPosition(..._))},w=(e,s,r)=>{const o=n(u,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:s});o.connect(p,0,e),o.start(),Object.defineProperty(o.offset,"defaultValue",{get(){return s}});const l=t({context:c},d,o.offset,$,H);return a(l,"value",t=>()=>t.call(l),t=>e=>{try{t.call(l,e)}catch(n){if(9!==n.code)throw n}g(),d&&r(e)}),l.cancelAndHoldAtTime=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.cancelAndHoldAtTime),l.cancelScheduledValues=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.cancelScheduledValues),l.exponentialRampToValueAtTime=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.exponentialRampToValueAtTime),l.linearRampToValueAtTime=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.linearRampToValueAtTime),l.setTargetAtTime=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.setTargetAtTime),l.setValueAtTime=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.setValueAtTime),l.setValueCurveAtTime=(t=>d?()=>{throw i()}:(...e)=>{const n=t.apply(l,e);return g(),n})(l.setValueCurveAtTime),l};return{forwardX:w(0,0,v(0)),forwardY:w(1,0,v(1)),forwardZ:w(2,-1,v(2)),positionX:w(6,0,y(0)),positionY:w(7,0,y(1)),positionZ:w(8,0,y(2)),upX:w(3,0,v(3)),upY:w(4,1,v(4)),upZ:w(5,0,v(5))}},{forwardX:p,forwardY:d,forwardZ:f,positionX:m,positionY:_,positionZ:g,upX:v,upY:y,upZ:w}=void 0===l.forwardX?h():l;return{get forwardX(){return p},get forwardY(){return d},get forwardZ(){return f},get positionX(){return m},get positionY(){return _},get positionZ(){return g},get upX(){return v},get upY(){return y},get upZ(){return w}}},_t=t=>"context"in t,gt=t=>_t(t[0]),vt=(t,e,n,s)=>{for(const i of t)if(n(i)){if(s)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0},yt=(t,e,[n,s],i)=>{vt(t,[e,n,s],t=>t[0]===e&&t[1]===n,i)},wt=(t,[e,n,s],i)=>{const r=t.get(e);void 0===r?t.set(e,new Set([[n,s]])):vt(r,[n,s],t=>t[0]===n,i)},xt=t=>"inputs"in t,Tt=(t,e,n,s)=>{if(xt(e)){const i=e.inputs[s];return t.connect(i,n,0),[i,n,0]}return t.connect(e,n,s),[e,n,s]},bt=(t,e,n)=>{for(const s of t)if(s[0]===e&&s[1]===n)return t.delete(s),s;return null},Ct=(t,e,n)=>M(t,t=>t[0]===e&&t[1]===n),At=(t,e)=>{const n=D(t);if(!n.delete(e))throw new Error("Missing the expected event listener.")},St=(t,e,n)=>{const s=O(t,e),i=M(s,t=>t[0]===n);return 0===s.size&&t.delete(e),i},kt=(t,e,n,s)=>{xt(e)?t.disconnect(e.inputs[s],n,0):t.disconnect(e,n,s)},Ot=t=>O(d,t),Mt=t=>O(m,t),Et=t=>v.has(t),Dt=t=>!h.has(t),It=(t,e)=>new Promise(n=>{if(null!==e)n(!0);else{const e=t.createScriptProcessor(256,1,1),s=t.createGain(),i=t.createBuffer(1,2,44100),r=i.getChannelData(0);r[0]=1,r[1]=1;const o=t.createBufferSource();o.buffer=i,o.loop=!0,o.connect(e).connect(t.destination),o.connect(s),o.disconnect(s),e.onaudioprocess=s=>{const i=s.inputBuffer.getChannelData(0);Array.prototype.some.call(i,t=>1===t)?n(!0):n(!1),o.stop(),e.onaudioprocess=null,o.disconnect(e),e.disconnect(t.destination)},o.start()}}),Rt=(t,e)=>{const n=new Map;for(const s of t)for(const t of s){const e=n.get(t);n.set(t,void 0===e?1:e+1)}n.forEach((t,n)=>e(n,t))},Nt=t=>"context"in t,Vt=t=>{const e=new Map;t.connect=(t=>(n,s=0,i=0)=>{const r=Nt(n)?t(n,s,i):t(n,s),o=e.get(n);return void 0===o?e.set(n,[{input:i,output:s}]):o.every(t=>t.input!==i||t.output!==s)&&o.push({input:i,output:s}),r})(t.connect.bind(t)),t.disconnect=(n=>(s,i,r)=>{if(n.apply(t),void 0===s)e.clear();else if("number"===typeof s)for(const[t,n]of e){const i=n.filter(t=>t.output!==s);0===i.length?e.delete(t):e.set(t,i)}else if(e.has(s))if(void 0===i)e.delete(s);else{const t=e.get(s);if(void 0!==t){const n=t.filter(t=>t.output!==i&&(t.input!==r||void 0===r));0===n.length?e.delete(s):e.set(s,n)}}for(const[n,o]of e)o.forEach(e=>{Nt(n)?t.connect(n,e.output,e.input):t.connect(n,e.output)})})(t.disconnect)},Pt=(t,e,n,s)=>{const{activeInputs:i,passiveInputs:r}=ct(e),{outputs:o}=at(t),a=D(t),c=o=>{const a=Ot(t),c=Mt(e);if(o){const e=St(r,t,n);yt(i,t,e,!1),s||Et(t)||a.connect(c,n)}else{const e=Ct(i,t,n);wt(r,e,!1),s||Et(t)||a.disconnect(c,n)}};return!!vt(o,[e,n],t=>t[0]===e&&t[1]===n,!0)&&(a.add(c),Q(t)?yt(i,t,[n,c],!0):wt(r,[t,n,c],!0),!0)},qt=(t,e,n,s)=>{const{activeInputs:i,passiveInputs:r}=at(e),o=bt(i[s],t,n);if(null===o){const e=E(r,t,n,s);return[e[2],!1]}return[o[2],!0]},Ft=(t,e,n)=>{const{activeInputs:s,passiveInputs:i}=ct(e),r=bt(s,t,n);if(null===r){const e=St(i,t,n);return[e[1],!1]}return[r[2],!0]},jt=(t,e,n,s,i)=>{const[r,o]=qt(t,n,s,i);if(null!==r&&(At(t,r),!o||e||Et(t)||kt(Ot(t),Ot(n),s,i)),Q(n)){const{activeInputs:t}=at(n);V(n,t)}},Lt=(t,e,n,s)=>{const[i,r]=Ft(t,n,s);null!==i&&(At(t,i),!r||e||Et(t)||Ot(t).disconnect(Mt(n),s))},Wt=(t,e)=>{const n=at(t),s=[];for(const i of n.outputs)gt(i)?jt(t,e,...i):Lt(t,e,...i),s.push(i[0]);return n.outputs.clear(),s},Bt=(t,e,n)=>{const s=at(t),i=[];for(const r of s.outputs)r[1]===n&&(gt(r)?jt(t,e,...r):Lt(t,e,...r),i.push(r[0]),s.outputs.delete(r));return i},Ut=(t,e,n,s,i)=>{const r=at(t);return Array.from(r.outputs).filter(t=>t[0]===n&&(void 0===s||t[1]===s)&&(void 0===i||t[2]===i)).map(n=>(gt(n)?jt(t,e,...n):Lt(t,e,...n),r.outputs.delete(n),n[0]))},zt=(t,e,n,s,i,r,o,a,c,u,l,h,p,f,m,_)=>class extends u{constructor(e,s,i,r){super(i),this._context=e,this._nativeAudioNode=i;const o=l(e);h(o)&&!0!==n(It,()=>It(o,_))&&Vt(i),d.set(this,i),g.set(this,new Set),"closed"!==e.state&&s&&I(this),t(this,r,i)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(t){this._nativeAudioNode.channelCount=t}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(t){this._nativeAudioNode.channelCountMode=t}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(t){this._nativeAudioNode.channelInterpretation=t}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(t,n=0,a=0){if(n<0||n>=this._nativeAudioNode.numberOfOutputs)throw i();const u=l(this._context),h=m(u);if(p(t)||f(t))throw r();if(_t(t)){const i=Ot(t);try{const e=Tt(this._nativeAudioNode,i,n,a),s=Dt(this);(h||s)&&this._nativeAudioNode.disconnect(...e),"closed"!==this.context.state&&!s&&Dt(t)&&I(t)}catch(g){if(12===g.code)throw r();throw g}const o=e(this,t,n,a,h);if(o){const e=c([this],t);Rt(e,s(h))}return t}const d=Mt(t);if("playbackRate"===d.name&&1024===d.maxValue)throw o();try{this._nativeAudioNode.connect(d,n),(h||Dt(this))&&this._nativeAudioNode.disconnect(d,n)}catch(g){if(12===g.code)throw r();throw g}const _=Pt(this,t,n,h);if(_){const e=c([this],t);Rt(e,s(h))}}disconnect(t,e,n){let s;const o=l(this._context),u=m(o);if(void 0===t)s=Wt(this,u);else if("number"===typeof t){if(t<0||t>=this.numberOfOutputs)throw i();s=Bt(this,u,t)}else{if(void 0!==e&&(e<0||e>=this.numberOfOutputs))throw i();if(_t(t)&&void 0!==n&&(n<0||n>=t.numberOfInputs))throw i();if(s=Ut(this,u,t,e,n),0===s.length)throw r()}for(const i of s){const t=c([this],i);Rt(t,a)}}},Gt=(t,e,n,s,i,r,a,c,u,l,h,p,d)=>(f,m,_,g=null,v=null)=>{const y=new o["AutomationEventList"](_.defaultValue),w=m?s(y):null,x={get defaultValue(){return _.defaultValue},get maxValue(){return null===g?_.maxValue:g},get minValue(){return null===v?_.minValue:v},get value(){return _.value},set value(t){_.value=t,x.setValueAtTime(t,f.context.currentTime)},cancelAndHoldAtTime(t){if("function"===typeof _.cancelAndHoldAtTime)null===w&&y.flush(f.context.currentTime),y.add(i(t)),_.cancelAndHoldAtTime(t);else{const e=Array.from(y).pop();null===w&&y.flush(f.context.currentTime),y.add(i(t));const n=Array.from(y).pop();_.cancelScheduledValues(t),e!==n&&void 0!==n&&("exponentialRampToValue"===n.type?_.exponentialRampToValueAtTime(n.value,n.endTime):"linearRampToValue"===n.type?_.linearRampToValueAtTime(n.value,n.endTime):"setValue"===n.type?_.setValueAtTime(n.value,n.startTime):"setValueCurve"===n.type&&_.setValueCurveAtTime(n.values,n.startTime,n.duration))}return x},cancelScheduledValues(t){return null===w&&y.flush(f.context.currentTime),y.add(r(t)),_.cancelScheduledValues(t),x},exponentialRampToValueAtTime(t,e){if(0===t)throw new RangeError;if(!Number.isFinite(e)||e<0)throw new RangeError;return null===w&&y.flush(f.context.currentTime),y.add(a(t,e)),_.exponentialRampToValueAtTime(t,e),x},linearRampToValueAtTime(t,e){return null===w&&y.flush(f.context.currentTime),y.add(c(t,e)),_.linearRampToValueAtTime(t,e),x},setTargetAtTime(t,e,n){return null===w&&y.flush(f.context.currentTime),y.add(u(t,e,n)),_.setTargetAtTime(t,e,n),x},setValueAtTime(t,e){return null===w&&y.flush(f.context.currentTime),y.add(l(t,e)),_.setValueAtTime(t,e),x},setValueCurveAtTime(t,e,n){const s=t instanceof Float32Array?t:new Float32Array(t);if(null!==p&&"webkitAudioContext"===p.name){const t=e+n,i=f.context.sampleRate,r=Math.ceil(e*i),o=Math.floor(t*i),a=o-r,c=new Float32Array(a);for(let l=0;l({replay(e){for(const n of t)if("exponentialRampToValue"===n.type){const{endTime:t,value:s}=n;e.exponentialRampToValueAtTime(s,t)}else if("linearRampToValue"===n.type){const{endTime:t,value:s}=n;e.linearRampToValueAtTime(s,t)}else if("setTarget"===n.type){const{startTime:t,target:s,timeConstant:i}=n;e.setTargetAtTime(s,t,i)}else if("setValue"===n.type){const{startTime:t,value:s}=n;e.setValueAtTime(s,t)}else{if("setValueCurve"!==n.type)throw new Error("Can't apply an unknown automation.");{const{duration:t,startTime:s,values:i}=n;e.setValueCurveAtTime(i,s,t)}}}});class Yt{constructor(t){this._map=new Map(t)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(t,e=null){return this._map.forEach((n,s)=>t.call(e,n,s,this))}get(t){return this._map.get(t)}has(t){return this._map.has(t)}keys(){return this._map.keys()}values(){return this._map.values()}}const Zt={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}},Ht=(t,e,n,s,i,r,o,a,c,u,l,h,p,d)=>class extends e{constructor(e,d,f){var m;const _=a(e),g=c(_),v=l({...Zt,...f});p(v);const w=y.get(_),x=null===w||void 0===w?void 0:w.get(d),T=g||"closed"!==_.state?_:null!==(m=o(_))&&void 0!==m?m:_,b=i(T,g?null:e.baseLatency,u,d,x,v),C=g?s(d,v,x):null;super(e,!0,b,C);const A=[];b.parameters.forEach((t,e)=>{const s=n(this,g,t);A.push([e,s])}),this._nativeAudioWorkletNode=b,this._onprocessorerror=null,this._parameters=new Yt(A),g&&t(_,this);const{activeInputs:S}=r(this);h(b,S)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(t){const e="function"===typeof t?d(this,t):null;this._nativeAudioWorkletNode.onprocessorerror=e;const n=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=null!==n&&n===e?t:n}get parameters(){return null===this._parameters?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}};function $t(t,e,n,s,i){if("function"===typeof t.copyFromChannel)0===e[n].byteLength&&(e[n]=new Float32Array(128)),t.copyFromChannel(e[n],s,i);else{const r=t.getChannelData(s);if(0===e[n].byteLength)e[n]=r.slice(i,i+128);else{const t=new Float32Array(r.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[n].set(t)}}}const Qt=(t,e,n,s,i)=>{"function"===typeof t.copyToChannel?0!==e[n].byteLength&&t.copyToChannel(e[n],s,i):0!==e[n].byteLength&&t.getChannelData(s).set(e[n],i)},Jt=(t,e)=>{const n=[];for(let s=0;s{const n=O(w,t),s=Ot(e);return O(n,s)},te=async(t,e,n,s,i,r,o)=>{const a=null===e?128*Math.ceil(t.context.length/128):e.length,c=s.channelCount*s.numberOfInputs,u=i.reduce((t,e)=>t+e,0),l=0===u?null:n.createBuffer(u,a,n.sampleRate);if(void 0===r)throw new Error("Missing the processor constructor.");const h=at(t),p=await Kt(n,t),d=Jt(s.numberOfInputs,s.channelCount),f=Jt(s.numberOfOutputs,i),m=Array.from(t.parameters.keys()).reduce((t,e)=>({...t,[e]:new Float32Array(128)}),{});for(let g=0;g0&&null!==e)for(let t=0;t{$t(e,m,t,c+n,g)});for(let t=0;t0===h.activeInputs[e].size?[]:t),e=o(g/n.sampleRate,n.sampleRate,()=>p.process(t,f,m));if(null!==l)for(let n=0,r=0;n(_,g,v)=>{const y=new WeakMap;let w=null;const x=async(a,x)=>{let T=l(a),b=null;const C=B(T,x),A=Array.isArray(g.outputChannelCount)?g.outputChannelCount:Array.from(g.outputChannelCount);if(null===h){const t=A.reduce((t,e)=>t+e,0),n=i(x,{channelCount:Math.max(1,t),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,t)}),r=[];for(let e=0;e{const c=new p(n,128*Math.ceil(a.context.length/128),x.sampleRate),u=[],l=[];for(let t=0;t{const e=r(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:t.value});return await d(c,t,e.offset),e})),_=s(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,t+e)});for(let t=0;tf(a,c,t))),m(c)};w=te(a,0===n?null:await c(),x,g,A,v,u)}const t=await w,e=n(x,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),[c,l,h]=b;null!==t&&(e.buffer=t,e.start(0)),e.connect(c);for(let n=0,s=0;nclass extends f{constructor(e,n){super(e,n),this._nativeContext=e,this._audioWorklet=void 0===t?void 0:{addModule:(e,n)=>t(this,e,n)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(t,e,s){return new n({length:e,numberOfChannels:t,sampleRate:s})}createBufferSource(){return new s(this)}createChannelMerger(t=6){return new r(this,{numberOfInputs:t})}createChannelSplitter(t=6){return new o(this,{numberOfOutputs:t})}createConstantSource(){return new a(this)}createConvolver(){return new c(this)}createDelay(t=1){return new l(this,{maxDelayTime:t})}createDynamicsCompressor(){return new h(this)}createGain(){return new p(this)}createIIRFilter(t,e){return new d(this,{feedback:e,feedforward:t})}createOscillator(){return new m(this)}createPanner(){return new _(this)}createPeriodicWave(t,e,n={disableNormalization:!1}){return new g(this,{...n,imag:e,real:t})}createStereoPanner(){return new v(this)}createWaveShaper(){return new y(this)}decodeAudioData(t,e,n){return u(this._nativeContext,t).then(t=>("function"===typeof e&&e(t),t),t=>{throw"function"===typeof n&&n(t),t})}},se={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},ie=(t,e,n,s,i,r,o,a)=>class extends t{constructor(t,s){const c=r(t),u={...se,...s},l=i(c,u),h=o(c),p=h?n():null;super(t,!1,l,p),this._Q=e(this,h,l.Q,$,H),this._detune=e(this,h,l.detune,1200*Math.log2($),-1200*Math.log2($)),this._frequency=e(this,h,l.frequency,t.sampleRate/2,0),this._gain=e(this,h,l.gain,40*Math.log10($),H),this._nativeBiquadFilterNode=l,a(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(t){this._nativeBiquadFilterNode.type=t}getFrequencyResponse(t,e,n){try{this._nativeBiquadFilterNode.getFrequencyResponse(t,e,n)}catch(i){if(11===i.code)throw s();throw i}if(t.length!==e.length||e.length!==n.length)throw s()}},re=(t,e,n,s,i)=>()=>{const r=new WeakMap,o=async(o,a)=>{let c=n(o);const u=B(c,a);if(!u){const t={Q:c.Q.value,channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,detune:c.detune.value,frequency:c.frequency.value,gain:c.gain.value,type:c.type};c=e(a,t)}return r.set(a,c),u?(await t(a,o.Q,c.Q),await t(a,o.detune,c.detune),await t(a,o.frequency,c.frequency),await t(a,o.gain,c.gain)):(await s(a,o.Q,c.Q),await s(a,o.detune,c.detune),await s(a,o.frequency,c.frequency),await s(a,o.gain,c.gain)),await i(o,a,c),c};return{render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):o(t,e)}}},oe=(t,e)=>(n,s)=>{const i=e.get(n);if(void 0!==i)return i;const r=t.get(n);if(void 0!==r)return r;try{const i=s();return i instanceof Promise?(t.set(n,i),i.catch(()=>!1).then(s=>(t.delete(n),e.set(n,s),s))):(e.set(n,i),i)}catch{return e.set(n,!1),!1}},ae={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},ce=(t,e,n,s,i)=>class extends t{constructor(t,r){const o=s(t),a={...ae,...r},c=n(o,a),u=i(o)?e():null;super(t,!1,c,u)}},ue=(t,e,n)=>()=>{const s=new WeakMap,i=async(i,r)=>{let o=e(i);const a=B(o,r);if(!a){const e={channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,numberOfInputs:o.numberOfInputs};o=t(r,e)}return s.set(r,o),await n(i,r,o),o};return{render(t,e){const n=s.get(e);return void 0!==n?Promise.resolve(n):i(t,e)}}},le={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},he=(t,e,n,s,i,r)=>class extends t{constructor(t,o){const a=s(t),c=r({...le,...o}),u=n(a,c),l=i(a)?e():null;super(t,!1,u,l)}},pe=(t,e,n)=>()=>{const s=new WeakMap,i=async(i,r)=>{let o=e(i);const a=B(o,r);if(!a){const e={channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,numberOfOutputs:o.numberOfOutputs};o=t(r,e)}return s.set(r,o),await n(i,r,o),o};return{render(t,e){const n=s.get(e);return void 0!==n?Promise.resolve(n):i(t,e)}}},de=t=>(e,n,s)=>t(n,e,s),fe=t=>(e,n,s=0,i=0)=>{const r=e[s];if(void 0===r)throw t();return Nt(n)?r.connect(n,0,i):r.connect(n,0)},me=t=>(e,n)=>{const s=t(e,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),i=e.createBuffer(1,2,44100);return s.buffer=i,s.loop=!0,s.connect(n),s.start(),()=>{s.stop(),s.disconnect(n)}},_e={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},ge=(t,e,n,s,i,r,o)=>class extends t{constructor(t,o){const a=i(t),c={..._e,...o},u=s(a,c),l=r(a),h=l?n():null;super(t,!1,u,h),this._constantSourceNodeRenderer=h,this._nativeConstantSourceNode=u,this._offset=e(this,l,u.offset,$,H),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(t){const e="function"===typeof t?o(this,t):null;this._nativeConstantSourceNode.onended=e;const n=this._nativeConstantSourceNode.onended;this._onended=null!==n&&n===e?t:n}start(t=0){if(this._nativeConstantSourceNode.start(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.start=t),"closed"!==this.context.state){I(this);const t=()=>{this._nativeConstantSourceNode.removeEventListener("ended",t),Q(this)&&N(this)};this._nativeConstantSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeConstantSourceNode.stop(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.stop=t)}},ve=(t,e,n,s,i)=>()=>{const r=new WeakMap;let o=null,a=null;const c=async(c,u)=>{let l=n(c);const h=B(l,u);if(!h){const t={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,offset:l.offset.value};l=e(u,t),null!==o&&l.start(o),null!==a&&l.stop(a)}return r.set(u,l),h?await t(u,c.offset,l.offset):await s(u,c.offset,l.offset),await i(c,u,l),l};return{set start(t){o=t},set stop(t){a=t},render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):c(t,e)}}},ye=t=>e=>(t[0]=e,t[0]),we={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},xe=(t,e,n,s,i,r)=>class extends t{constructor(t,o){const a=s(t),c={...we,...o},u=n(a,c),l=i(a),h=l?e():null;super(t,!1,u,h),this._isBufferNullified=!1,this._nativeConvolverNode=u,null!==c.buffer&&r(this,c.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(t){if(this._nativeConvolverNode.buffer=t,null===t&&null!==this._nativeConvolverNode.buffer){const t=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=t.createBuffer(1,1,44100),this._isBufferNullified=!0,r(this,0)}else this._isBufferNullified=!1,r(this,null===this._nativeConvolverNode.buffer?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(t){this._nativeConvolverNode.normalize=t}},Te=(t,e,n)=>()=>{const s=new WeakMap,i=async(i,r)=>{let o=e(i);const a=B(o,r);if(!a){const e={buffer:o.buffer,channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,disableNormalization:!o.normalize};o=t(r,e)}return s.set(r,o),xt(o)?await n(i,r,o.inputs[0]):await n(i,r,o),o};return{render(t,e){const n=s.get(e);return void 0!==n?Promise.resolve(n):i(t,e)}}},be=(t,e)=>(n,s,i)=>{if(null===e)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(n,s,i)}catch(r){if("SyntaxError"===r.name)throw t();throw r}},Ce=()=>new DOMException("","DataCloneError"),Ae=t=>{const{port1:e,port2:n}=new MessageChannel;return new Promise(s=>{const i=()=>{n.onmessage=null,e.close(),n.close(),s()};n.onmessage=()=>i();try{e.postMessage(t,[t])}finally{i()}})},Se=(t,e,n,s,i,r,o,a,c,u,l)=>(h,p)=>{const d=o(h)?h:r(h);if(i.has(p)){const t=n();return Promise.reject(t)}try{i.add(p)}catch{}return e(c,()=>c(d))?d.decodeAudioData(p).then(n=>(Ae(p).catch(()=>{}),e(a,()=>a(n))||l(n),t.add(n),n)):new Promise((e,n)=>{const i=async()=>{try{await Ae(p)}catch{}},r=t=>{n(t),i()};try{d.decodeAudioData(p,n=>{"function"!==typeof n.copyFromChannel&&(u(n),X(n)),t.add(n),i().then(()=>e(n))},t=>{r(null===t?s():t)})}catch(o){r(o)}})},ke=(t,e,n,s,i,r,o,a)=>(c,u)=>{const l=e.get(c);if(void 0===l)throw new Error("Missing the expected cycle count.");const h=r(c.context),p=a(h);if(l===u){if(e.delete(c),!p&&o(c)){const e=s(c),{outputs:r}=n(c);for(const n of r)if(gt(n)){const i=s(n[0]);t(e,i,n[1],n[2])}else{const t=i(n[0]);e.connect(t,n[1])}}}else e.set(c,l-u)},Oe={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},Me=(t,e,n,s,i,r,o)=>class extends t{constructor(t,a){const c=i(t),u={...Oe,...a},l=s(c,u),h=r(c),p=h?n(u.maxDelayTime):null;super(t,!1,l,p),this._delayTime=e(this,h,l.delayTime),o(this,u.maxDelayTime)}get delayTime(){return this._delayTime}},Ee=(t,e,n,s,i)=>r=>{const o=new WeakMap,a=async(a,c)=>{let u=n(a);const l=B(u,c);if(!l){const t={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,delayTime:u.delayTime.value,maxDelayTime:r};u=e(c,t)}return o.set(c,u),l?await t(c,a.delayTime,u.delayTime):await s(c,a.delayTime,u.delayTime),await i(a,c,u),u};return{render(t,e){const n=o.get(e);return void 0!==n?Promise.resolve(n):a(t,e)}}},De=t=>(e,n,s,i)=>t(e[i],t=>t[0]===n&&t[1]===s),Ie=t=>(e,n)=>{t(e).delete(n)},Re=t=>"delayTime"in t,Ne=(t,e,n)=>function s(i,r){const o=_t(r)?r:n(t,r);if(Re(o))return[];if(i[0]===o)return[i];if(i.includes(o))return[];const{outputs:a}=e(o);return Array.from(a).map(t=>s([...i,o],t[0])).reduce((t,e)=>t.concat(e),[])},Ve=(t,e,n)=>{const s=e[n];if(void 0===s)throw t();return s},Pe=t=>(e,n,s,i=0)=>void 0===n?e.forEach(t=>t.disconnect()):"number"===typeof n?Ve(t,e,n).disconnect():Nt(n)?void 0===s?e.forEach(t=>t.disconnect(n)):void 0===i?Ve(t,e,s).disconnect(n,0):Ve(t,e,s).disconnect(n,0,i):void 0===s?e.forEach(t=>t.disconnect(n)):Ve(t,e,s).disconnect(n,0),qe={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},Fe=(t,e,n,s,i,r,o,a)=>class extends t{constructor(t,i){const c=r(t),u={...qe,...i},l=s(c,u),h=o(c),p=h?n():null;super(t,!1,l,p),this._attack=e(this,h,l.attack),this._knee=e(this,h,l.knee),this._nativeDynamicsCompressorNode=l,this._ratio=e(this,h,l.ratio),this._release=e(this,h,l.release),this._threshold=e(this,h,l.threshold),a(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(t){const e=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=t,t>2)throw this._nativeDynamicsCompressorNode.channelCount=e,i()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(t){const e=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=t,"max"===t)throw this._nativeDynamicsCompressorNode.channelCountMode=e,i()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return"number"===typeof this._nativeDynamicsCompressorNode.reduction.value?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}},je=(t,e,n,s,i)=>()=>{const r=new WeakMap,o=async(o,a)=>{let c=n(o);const u=B(c,a);if(!u){const t={attack:c.attack.value,channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,knee:c.knee.value,ratio:c.ratio.value,release:c.release.value,threshold:c.threshold.value};c=e(a,t)}return r.set(a,c),u?(await t(a,o.attack,c.attack),await t(a,o.knee,c.knee),await t(a,o.ratio,c.ratio),await t(a,o.release,c.release),await t(a,o.threshold,c.threshold)):(await s(a,o.attack,c.attack),await s(a,o.knee,c.knee),await s(a,o.ratio,c.ratio),await s(a,o.release,c.release),await s(a,o.threshold,c.threshold)),await i(o,a,c),c};return{render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):o(t,e)}}},Le=()=>new DOMException("","EncodingError"),We=t=>e=>new Promise((n,s)=>{if(null===t)return void s(new SyntaxError);const i=t.document.head;if(null===i)s(new SyntaxError);else{const r=t.document.createElement("script"),o=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(o),c=t.onerror,u=()=>{t.onerror=c,URL.revokeObjectURL(a)};t.onerror=(e,n,i,r,o)=>n===a||n===t.location.href&&1===i&&1===r?(u(),s(o),!1):null!==c?c(e,n,i,r,o):void 0,r.onerror=()=>{u(),s(new SyntaxError)},r.onload=()=>{u(),n()},r.src=a,r.type="module",i.appendChild(r)}}),Be=t=>class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(e,n,s){if(null!==n){let i=this._listeners.get(n);void 0===i&&(i=t(this,n),"function"===typeof n&&this._listeners.set(n,i)),this._nativeEventTarget.addEventListener(e,i,s)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,e,n){const s=null===e?void 0:this._listeners.get(e);this._nativeEventTarget.removeEventListener(t,void 0===s?null:s,n)}},Ue=t=>(e,n,s)=>{Object.defineProperties(t,{currentFrame:{configurable:!0,get(){return Math.round(e*n)}},currentTime:{configurable:!0,get(){return e}}});try{return s()}finally{null!==t&&(delete t.currentFrame,delete t.currentTime)}},ze=t=>async e=>{try{const t=await fetch(e);if(t.ok)return[await t.text(),t.url]}catch{}throw t()},Ge={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},Xe=(t,e,n,s,i,r)=>class extends t{constructor(t,o){const a=i(t),c={...Ge,...o},u=s(a,c),l=r(a),h=l?n():null;super(t,!1,u,h),this._gain=e(this,l,u.gain,$,H)}get gain(){return this._gain}},Ye=(t,e,n,s,i)=>()=>{const r=new WeakMap,o=async(o,a)=>{let c=n(o);const u=B(c,a);if(!u){const t={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,gain:c.gain.value};c=e(a,t)}return r.set(a,c),u?await t(a,o.gain,c.gain):await s(a,o.gain,c.gain),await i(o,a,c),c};return{render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):o(t,e)}}},Ze=(t,e)=>n=>e(t,n),He=t=>e=>{const n=t(e);if(null===n.renderer)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return n.renderer},$e=t=>e=>{var n;return null!==(n=t.get(e))&&void 0!==n?n:0},Qe=t=>e=>{const n=t(e);if(null===n.renderer)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return n.renderer},Je=t=>e=>t.get(e),Ke=()=>new DOMException("","InvalidStateError"),tn=t=>e=>{const n=t.get(e);if(void 0===n)throw Ke();return n},en=(t,e)=>n=>{let s=t.get(n);if(void 0!==s)return s;if(null===e)throw new Error("Missing the native OfflineAudioContext constructor.");return s=new e(1,1,44100),t.set(n,s),s},nn=t=>e=>{const n=t.get(e);if(void 0===n)throw new Error("The context has no set of AudioWorkletNodes.");return n},sn=()=>new DOMException("","InvalidAccessError"),rn=t=>{t.getFrequencyResponse=(e=>(n,s,i)=>{if(n.length!==s.length||s.length!==i.length)throw sn();return e.call(t,n,s,i)})(t.getFrequencyResponse)},on={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},an=(t,e,n,s,i,r)=>class extends t{constructor(t,o){const a=s(t),c=i(a),u={...on,...o},l=e(a,c?null:t.baseLatency,u),h=c?n(u.feedback,u.feedforward):null;super(t,!1,l,h),rn(l),this._nativeIIRFilterNode=l,r(this,1)}getFrequencyResponse(t,e,n){return this._nativeIIRFilterNode.getFrequencyResponse(t,e,n)}},cn=(t,e,n,s,i,r,o,a,c,u,l)=>{const h=u.length;let p=a;for(let d=0;d{const i=n instanceof Float64Array?n:new Float64Array(n),r=s instanceof Float64Array?s:new Float64Array(s),o=i.length,a=r.length,c=Math.min(o,a);if(1!==i[0]){for(let t=0;t(r,o)=>{const a=new WeakMap;let c=null;const u=async(u,l)=>{let h=null,p=e(u);const d=B(p,l);if(void 0===l.createIIRFilter?h=t(l,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):d||(p=l.createIIRFilter(o,r)),a.set(l,null===h?p:h),null!==h){if(null===c){if(null===n)throw new Error("Missing the native OfflineAudioContext constructor.");const t=new n(u.context.destination.channelCount,u.context.length,l.sampleRate);c=(async()=>{await s(u,t,t.destination);const e=await i(t);return un(e,l,r,o)})()}const t=await c;return h.buffer=t,h.start(0),h}return await s(u,l,p),p};return{render(t,e){const n=a.get(e);return void 0!==n?Promise.resolve(n):u(t,e)}}},hn=(t,e,n,s,i,r)=>o=>(a,c)=>{const u=t.get(a);if(void 0===u){if(!o&&r(a)){const t=s(a),{outputs:r}=n(a);for(const n of r)if(gt(n)){const i=s(n[0]);e(t,i,n[1],n[2])}else{const e=i(n[0]);t.disconnect(e,n[1])}}t.set(a,c)}else t.set(a,u+c)},pn=(t,e)=>n=>{const s=t.get(n);return e(s)||e(n)},dn=(t,e)=>n=>t.has(n)||e(n),fn=(t,e)=>n=>t.has(n)||e(n),mn=(t,e)=>n=>{const s=t.get(n);return e(s)||e(n)},_n=t=>e=>null!==t&&e instanceof t,gn=t=>e=>null!==t&&"function"===typeof t.AudioNode&&e instanceof t.AudioNode,vn=t=>e=>null!==t&&"function"===typeof t.AudioParam&&e instanceof t.AudioParam,yn=(t,e)=>n=>t(n)||e(n),wn=t=>e=>null!==t&&e instanceof t,xn=t=>null!==t&&t.isSecureContext,Tn=(t,e,n,s)=>class extends t{constructor(t,i){const r=n(t),o=e(r,i);if(s(r))throw TypeError();super(t,!0,o,null),this._nativeMediaElementAudioSourceNode=o}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},bn={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},Cn=(t,e,n,s)=>class extends t{constructor(t,i){const r=n(t);if(s(r))throw new TypeError;const o={...bn,...i},a=e(r,o);super(t,!1,a,null),this._nativeMediaStreamAudioDestinationNode=a}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},An=(t,e,n,s)=>class extends t{constructor(t,i){const r=n(t),o=e(r,i);if(s(r))throw new TypeError;super(t,!0,o,null),this._nativeMediaStreamAudioSourceNode=o}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},Sn=(t,e,n)=>class extends t{constructor(t,s){const i=n(t),r=e(i,s);super(t,!0,r,null)}},kn=(t,e,n,s,i)=>class extends s{constructor(t={}){if(null===i)throw new Error("Missing the native AudioContext constructor.");let s;try{s=new i(t)}catch(a){if(12===a.code&&"sampleRate is not in range"===a.message)throw e();throw a}if(null===s)throw n();if(!ht(t.latencyHint))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&s.sampleRate!==t.sampleRate)throw e();super(s,2);const{latencyHint:r}=t,{sampleRate:o}=s;if(this._baseLatency="number"===typeof s.baseLatency?s.baseLatency:"balanced"===r?512/o:"interactive"===r||void 0===r?256/o:"playback"===r?1024/o:128*Math.max(2,Math.min(128,Math.round(r*o/128)))/o,this._nativeAudioContext=s,"webkitAudioContext"===i.name?(this._nativeGainNode=s.createGain(),this._nativeOscillatorNode=s.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(s.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,"running"===s.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),s.removeEventListener("statechange",t)};s.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw t()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close().then(()=>{null!==this._nativeGainNode&&null!==this._nativeOscillatorNode&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),lt(this)}))}resume(){return"suspended"===this._state?new Promise((t,e)=>{const n=()=>{this._nativeAudioContext.removeEventListener("statechange",n),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",n)}):this._nativeAudioContext.resume().catch(e=>{if(void 0===e||15===e.code)throw t();throw e})}suspend(){return this._nativeAudioContext.suspend().catch(e=>{if(void 0===e)throw t();throw e})}},On=(t,e,n,s,i,r)=>class extends n{constructor(n,r){super(n),this._nativeContext=n,_.set(this,n),s(n)&&i.set(n,new Set),this._destination=new t(this,r),this._listener=e(this,n),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(t){const e="function"===typeof t?r(this,t):null;this._nativeContext.onstatechange=e;const n=this._nativeContext.onstatechange;this._onstatechange=null!==n&&n===e?t:n}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}},Mn=t=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const n=t.decodeAudioData(e.buffer,()=>{});return void 0!==n&&(n.catch(()=>{}),!0)}catch{}return!1},En={numberOfChannels:1},Dn=(t,e,n,s,i)=>class extends s{constructor(e){const{length:s,numberOfChannels:i,sampleRate:r}={...En,...e},o=n(i,s,r);t(Mn,()=>Mn(o))||o.addEventListener("statechange",(()=>{let t=0;const e=n=>{"running"===this._state&&(t>0?(o.removeEventListener("statechange",e),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):t+=1)};return e})()),super(o,i),this._length=s,this._nativeOfflineAudioContext=o,this._state=null}get length(){return void 0===this._nativeOfflineAudioContext.length?this._length:this._nativeOfflineAudioContext.length}get state(){return null===this._state?this._nativeOfflineAudioContext.state:this._state}startRendering(){return"running"===this._state?Promise.reject(e()):(this._state="running",i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,lt(this)}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}},In=(t,e)=>(n,s,i)=>{const r=new Set;return n.connect=(i=>(o,a=0,c=0)=>{const u=0===r.size;if(e(o))return i.call(n,o,a,c),t(r,[o,a,c],t=>t[0]===o&&t[1]===a&&t[2]===c,!0),u&&s(),o;i.call(n,o,a),t(r,[o,a],t=>t[0]===o&&t[1]===a,!0),u&&s()})(n.connect),n.disconnect=(t=>(s,o,a)=>{const c=r.size>0;if(void 0===s)t.apply(n),r.clear();else if("number"===typeof s){t.call(n,s);for(const t of r)t[1]===s&&r.delete(t)}else{e(s)?t.call(n,s,o,a):t.call(n,s,o);for(const t of r)t[0]!==s||void 0!==o&&t[1]!==o||void 0!==a&&t[2]!==a||r.delete(t)}const u=0===r.size;c&&u&&i()})(n.disconnect),n},Rn=(t,e,n)=>{const s=e[n];void 0!==s&&s!==t[n]&&(t[n]=s)},Nn=(t,e)=>{Rn(t,e,"channelCount"),Rn(t,e,"channelCountMode"),Rn(t,e,"channelInterpretation")},Vn=t=>"function"===typeof t.getFloatTimeDomainData,Pn=t=>{t.getFloatTimeDomainData=e=>{const n=new Uint8Array(e.length);t.getByteTimeDomainData(n);const s=Math.max(n.length,t.fftSize);for(let t=0;t(n,s)=>{const i=n.createAnalyser();if(Nn(i,s),!(s.maxDecibels>s.minDecibels))throw e();return Rn(i,s,"fftSize"),Rn(i,s,"maxDecibels"),Rn(i,s,"minDecibels"),Rn(i,s,"smoothingTimeConstant"),t(Vn,()=>Vn(i))||Pn(i),i},Fn=t=>null===t?null:t.hasOwnProperty("AudioBuffer")?t.AudioBuffer:null,jn=(t,e,n)=>{const s=e[n];void 0!==s&&s!==t[n].value&&(t[n].value=s)},Ln=t=>{t.start=(e=>{let n=!1;return(s=0,i=0,r)=>{if(n)throw Ke();e.call(t,s,i,r),n=!0}})(t.start)},Wn=t=>{t.start=(e=>(n=0,s=0,i)=>{if("number"===typeof i&&i<0||s<0||n<0)throw new RangeError("The parameters can't be negative.");e.call(t,n,s,i)})(t.start)},Bn=t=>{t.stop=(e=>(n=0)=>{if(n<0)throw new RangeError("The parameter can't be negative.");e.call(t,n)})(t.stop)},Un=(t,e,n,s,i,r,o,a,c,u,l)=>(h,p)=>{const d=h.createBufferSource();return Nn(d,p),jn(d,p,"playbackRate"),Rn(d,p,"buffer"),Rn(d,p,"loop"),Rn(d,p,"loopEnd"),Rn(d,p,"loopStart"),e(n,()=>n(h))||Ln(d),e(s,()=>s(h))||c(d),e(i,()=>i(h))||u(d,h),e(r,()=>r(h))||Wn(d),e(o,()=>o(h))||l(d,h),e(a,()=>a(h))||Bn(d),t(h,d),d},zn=t=>null===t?null:t.hasOwnProperty("AudioContext")?t.AudioContext:t.hasOwnProperty("webkitAudioContext")?t.webkitAudioContext:null,Gn=(t,e)=>(n,s,i)=>{const r=n.destination;if(r.channelCount!==s)try{r.channelCount=s}catch{}i&&"explicit"!==r.channelCountMode&&(r.channelCountMode="explicit"),0===r.maxChannelCount&&Object.defineProperty(r,"maxChannelCount",{value:s});const o=t(n,{channelCount:s,channelCountMode:r.channelCountMode,channelInterpretation:r.channelInterpretation,gain:1});return e(o,"channelCount",t=>()=>t.call(o),t=>e=>{t.call(o,e);try{r.channelCount=e}catch(n){if(e>r.maxChannelCount)throw n}}),e(o,"channelCountMode",t=>()=>t.call(o),t=>e=>{t.call(o,e),r.channelCountMode=e}),e(o,"channelInterpretation",t=>()=>t.call(o),t=>e=>{t.call(o,e),r.channelInterpretation=e}),Object.defineProperty(o,"maxChannelCount",{get:()=>r.maxChannelCount}),o.connect(r),o},Xn=t=>null===t?null:t.hasOwnProperty("AudioWorkletNode")?t.AudioWorkletNode:null,Yn=t=>{const{port1:e}=new MessageChannel;try{e.postMessage(t)}finally{e.close()}},Zn=(t,e,n,s,i)=>(r,o,a,c,u,l)=>{if(null!==a)try{const e=new a(r,c,l),s=new Map;let o=null;if(Object.defineProperties(e,{channelCount:{get:()=>l.channelCount,set:()=>{throw t()}},channelCountMode:{get:()=>"explicit",set:()=>{throw t()}},onprocessorerror:{get:()=>o,set:t=>{"function"===typeof o&&e.removeEventListener("processorerror",o),o="function"===typeof t?t:null,"function"===typeof o&&e.addEventListener("processorerror",o)}}}),e.addEventListener=(t=>(...n)=>{if("processorerror"===n[0]){const t="function"===typeof n[1]?n[1]:"object"===typeof n[1]&&null!==n[1]&&"function"===typeof n[1].handleEvent?n[1].handleEvent:null;if(null!==t){const e=s.get(n[1]);void 0!==e?n[1]=e:(n[1]=e=>{"error"===e.type?(Object.defineProperties(e,{type:{value:"processorerror"}}),t(e)):t(new ErrorEvent(n[0],{...e}))},s.set(t,n[1]))}}return t.call(e,"error",n[1],n[2]),t.call(e,...n)})(e.addEventListener),e.removeEventListener=(t=>(...n)=>{if("processorerror"===n[0]){const t=s.get(n[1]);void 0!==t&&(s.delete(n[1]),n[1]=t)}return t.call(e,"error",n[1],n[2]),t.call(e,n[0],n[1],n[2])})(e.removeEventListener),0!==l.numberOfOutputs){const t=n(r,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});e.connect(t).connect(r.destination);const s=()=>t.disconnect(),o=()=>t.connect(r.destination);return i(e,s,o)}return e}catch(h){if(11===h.code)throw s();throw h}if(void 0===u)throw s();return Yn(l),e(r,o,u,l)},Hn=(t,e)=>null===t?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e))))),$n=t=>new Promise((e,n)=>{const{port1:s,port2:i}=new MessageChannel;s.onmessage=({data:t})=>{s.close(),i.close(),e(t)},s.onmessageerror=({data:t})=>{s.close(),i.close(),n(t)},i.postMessage(t)}),Qn=async(t,e)=>{const n=await $n(e);return new t(n)},Jn=(t,e,n,s)=>{let i=w.get(t);void 0===i&&(i=new WeakMap,w.set(t,i));const r=Qn(n,s);return i.set(e,r),r},Kn=(t,e,n,s,i,r,o,a,c,u,l,h,p)=>(d,f,m,_)=>{if(0===_.numberOfInputs&&0===_.numberOfOutputs)throw c();const g=Array.isArray(_.outputChannelCount)?_.outputChannelCount:Array.from(_.outputChannelCount);if(g.some(t=>t<1))throw c();if(g.length!==_.numberOfOutputs)throw e();if("explicit"!==_.channelCountMode)throw c();const v=_.channelCount*_.numberOfInputs,y=g.reduce((t,e)=>t+e,0),w=void 0===m.parameterDescriptors?0:m.parameterDescriptors.length;if(v+w>6||y>6)throw c();const x=new MessageChannel,T=[],b=[];for(let t=0;t<_.numberOfInputs;t+=1)T.push(o(d,{channelCount:_.channelCount,channelCountMode:_.channelCountMode,channelInterpretation:_.channelInterpretation,gain:1})),b.push(i(d,{channelCount:_.channelCount,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:_.channelCount}));const C=[];if(void 0!==m.parameterDescriptors)for(const{defaultValue:t,maxValue:e,minValue:n,name:s}of m.parameterDescriptors){const i=r(d,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:void 0!==_.parameterData[s]?_.parameterData[s]:void 0===t?0:t});Object.defineProperties(i.offset,{defaultValue:{get:()=>void 0===t?0:t},maxValue:{get:()=>void 0===e?$:e},minValue:{get:()=>void 0===n?H:n}}),C.push(i)}const A=s(d,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,v+w)}),S=Hn(f,d.sampleRate),k=a(d,S,v+w,Math.max(1,y)),O=i(d,{channelCount:Math.max(1,y),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,y)}),M=[];for(let t=0;t<_.numberOfOutputs;t+=1)M.push(s(d,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:g[t]}));for(let t=0;t<_.numberOfInputs;t+=1){T[t].connect(b[t]);for(let e=0;e<_.channelCount;e+=1)b[t].connect(A,e,t*_.channelCount+e)}const E=new Yt(void 0===m.parameterDescriptors?[]:m.parameterDescriptors.map(({name:t},e)=>{const n=C[e];return n.connect(A,0,v+e),n.start(0),[t,n.offset]}));A.connect(k);let D=_.channelInterpretation,I=null;const R=0===_.numberOfOutputs?[k]:M,N={get bufferSize(){return S},get channelCount(){return _.channelCount},set channelCount(t){throw n()},get channelCountMode(){return _.channelCountMode},set channelCountMode(t){throw n()},get channelInterpretation(){return D},set channelInterpretation(t){for(const e of T)e.channelInterpretation=t;D=t},get context(){return k.context},get inputs(){return T},get numberOfInputs(){return _.numberOfInputs},get numberOfOutputs(){return _.numberOfOutputs},get onprocessorerror(){return I},set onprocessorerror(t){"function"===typeof I&&N.removeEventListener("processorerror",I),I="function"===typeof t?t:null,"function"===typeof I&&N.addEventListener("processorerror",I)},get parameters(){return E},get port(){return x.port2},addEventListener(...t){return k.addEventListener(t[0],t[1],t[2])},connect:t.bind(null,R),disconnect:u.bind(null,R),dispatchEvent(...t){return k.dispatchEvent(t[0])},removeEventListener(...t){return k.removeEventListener(t[0],t[1],t[2])}},V=new Map;x.port1.addEventListener=(t=>(...e)=>{if("message"===e[0]){const t="function"===typeof e[1]?e[1]:"object"===typeof e[1]&&null!==e[1]&&"function"===typeof e[1].handleEvent?e[1].handleEvent:null;if(null!==t){const n=V.get(e[1]);void 0!==n?e[1]=n:(e[1]=e=>{l(d.currentTime,d.sampleRate,()=>t(e))},V.set(t,e[1]))}}return t.call(x.port1,e[0],e[1],e[2])})(x.port1.addEventListener),x.port1.removeEventListener=(t=>(...e)=>{if("message"===e[0]){const t=V.get(e[1]);void 0!==t&&(V.delete(e[1]),e[1]=t)}return t.call(x.port1,e[0],e[1],e[2])})(x.port1.removeEventListener);let P=null;Object.defineProperty(x.port1,"onmessage",{get:()=>P,set:t=>{"function"===typeof P&&x.port1.removeEventListener("message",P),P="function"===typeof t?t:null,"function"===typeof P&&(x.port1.addEventListener("message",P),x.port1.start())}}),m.prototype.port=x.port1;let q=null;const F=Jn(d,N,m,_);F.then(t=>q=t);const j=Jt(_.numberOfInputs,_.channelCount),L=Jt(_.numberOfOutputs,g),W=void 0===m.parameterDescriptors?[]:m.parameterDescriptors.reduce((t,{name:e})=>({...t,[e]:new Float32Array(128)}),{});let B=!0;const U=()=>{_.numberOfOutputs>0&&k.disconnect(O);for(let t=0,e=0;t<_.numberOfOutputs;t+=1){const n=M[t];for(let s=0;s{if(null!==q){const s=h(N);for(let i=0;i{$t(t,W,e,v+n,i)});for(let t=0;t<_.numberOfInputs;t+=1)for(let e=0;e{const n=s[e];if(n.size>0)return z.set(e,S/128),t;const i=z.get(e);return void 0===i?[]:(t.every(t=>t.every(t=>0===t))&&(1===i?z.delete(e):z.set(e,i-1)),t)}),n=l(d.currentTime+i/d.sampleRate,d.sampleRate,()=>q.process(t,L,W));B=n;for(let s=0,r=0;s<_.numberOfOutputs;s+=1){for(let t=0;tk.connect(X).connect(d.destination),Z=()=>{k.disconnect(X),X.disconnect()},Q=()=>{if(B){Z(),_.numberOfOutputs>0&&k.connect(O);for(let t=0,e=0;t<_.numberOfOutputs;t+=1){const n=M[t];for(let s=0;s{B&&(Y(),U()),G=!1};return Y(),p(N,Q,J)},ts=(t,e)=>{const n=t.createBiquadFilter();return Nn(n,e),jn(n,e,"Q"),jn(n,e,"detune"),jn(n,e,"frequency"),jn(n,e,"gain"),Rn(n,e,"type"),n},es=(t,e)=>(n,s)=>{const i=n.createChannelMerger(s.numberOfInputs);return null!==t&&"webkitAudioContext"===t.name&&e(n,i),Nn(i,s),i},ns=t=>{const e=t.numberOfOutputs;Object.defineProperty(t,"channelCount",{get:()=>e,set:t=>{if(t!==e)throw Ke()}}),Object.defineProperty(t,"channelCountMode",{get:()=>"explicit",set:t=>{if("explicit"!==t)throw Ke()}}),Object.defineProperty(t,"channelInterpretation",{get:()=>"discrete",set:t=>{if("discrete"!==t)throw Ke()}})},ss=(t,e)=>{const n=t.createChannelSplitter(e.numberOfOutputs);return Nn(n,e),ns(n),n},is=(t,e,n,s,i)=>(r,o)=>{if(void 0===r.createConstantSource)return n(r,o);const a=r.createConstantSource();return Nn(a,o),jn(a,o,"offset"),e(s,()=>s(r))||Wn(a),e(i,()=>i(r))||Bn(a),t(r,a),a},rs=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t),os=(t,e,n,s)=>(i,{offset:r,...o})=>{const a=i.createBuffer(1,2,44100),c=e(i,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),u=n(i,{...o,gain:r}),l=a.getChannelData(0);l[0]=1,l[1]=1,c.buffer=a,c.loop=!0;const h={get bufferSize(){},get channelCount(){return u.channelCount},set channelCount(t){u.channelCount=t},get channelCountMode(){return u.channelCountMode},set channelCountMode(t){u.channelCountMode=t},get channelInterpretation(){return u.channelInterpretation},set channelInterpretation(t){u.channelInterpretation=t},get context(){return u.context},get inputs(){return[]},get numberOfInputs(){return c.numberOfInputs},get numberOfOutputs(){return u.numberOfOutputs},get offset(){return u.gain},get onended(){return c.onended},set onended(t){c.onended=t},addEventListener(...t){return c.addEventListener(t[0],t[1],t[2])},dispatchEvent(...t){return c.dispatchEvent(t[0])},removeEventListener(...t){return c.removeEventListener(t[0],t[1],t[2])},start(t=0){c.start.call(c,t)},stop(t=0){c.stop.call(c,t)}},p=()=>c.connect(u),d=()=>c.disconnect(u);return t(i,c),s(rs(h,u),p,d)},as=(t,e)=>(n,s)=>{const i=n.createConvolver();if(Nn(i,s),s.disableNormalization===i.normalize&&(i.normalize=!s.disableNormalization),Rn(i,s,"buffer"),s.channelCount>2)throw t();if(e(i,"channelCount",t=>()=>t.call(i),e=>n=>{if(n>2)throw t();return e.call(i,n)}),"max"===s.channelCountMode)throw t();return e(i,"channelCountMode",t=>()=>t.call(i),e=>n=>{if("max"===n)throw t();return e.call(i,n)}),i},cs=(t,e)=>{const n=t.createDelay(e.maxDelayTime);return Nn(n,e),jn(n,e,"delayTime"),n},us=t=>(e,n)=>{const s=e.createDynamicsCompressor();if(Nn(s,n),n.channelCount>2)throw t();if("max"===n.channelCountMode)throw t();return jn(s,n,"attack"),jn(s,n,"knee"),jn(s,n,"ratio"),jn(s,n,"release"),jn(s,n,"threshold"),s},ls=(t,e)=>{const n=t.createGain();return Nn(n,e),jn(n,e,"gain"),n},hs=t=>(e,n,s)=>{if(void 0===e.createIIRFilter)return t(e,n,s);const i=e.createIIRFilter(s.feedforward,s.feedback);return Nn(i,s),i};function ps(t,e){const n=e[0]*e[0]+e[1]*e[1];return[(t[0]*e[0]+t[1]*e[1])/n,(t[1]*e[0]-t[0]*e[1])/n]}function ds(t,e){return[t[0]*e[0]-t[1]*e[1],t[0]*e[1]+t[1]*e[0]]}function fs(t,e){let n=[0,0];for(let s=t.length-1;s>=0;s-=1)n=ds(n,e),n[0]+=t[s];return n}const ms=(t,e,n,s)=>(i,r,{channelCount:o,channelCountMode:a,channelInterpretation:c,feedback:u,feedforward:l})=>{const h=Hn(r,i.sampleRate),p=u instanceof Float64Array?u:new Float64Array(u),d=l instanceof Float64Array?l:new Float64Array(l),f=p.length,m=d.length,_=Math.min(f,m);if(0===f||f>20)throw s();if(0===p[0])throw e();if(0===m||m>20)throw s();if(0===d[0])throw e();if(1!==p[0]){for(let t=0;t{const e=t.inputBuffer,n=t.outputBuffer,s=e.numberOfChannels;for(let i=0;it.createMediaElementSource(e.mediaElement),gs=(t,e)=>{const n=t.createMediaStreamDestination();return Nn(n,e),1===n.numberOfOutputs&&Object.defineProperty(n,"numberOfOutputs",{get:()=>0}),n},vs=(t,{mediaStream:e})=>{const n=e.getAudioTracks();n.sort((t,e)=>t.ide.id?1:0);const s=n.slice(0,1),i=t.createMediaStreamSource(new MediaStream(s));return Object.defineProperty(i,"mediaStream",{value:e}),i},ys=(t,e)=>(n,{mediaStreamTrack:s})=>{if("function"===typeof n.createMediaStreamTrackSource)return n.createMediaStreamTrackSource(s);const i=new MediaStream([s]),r=n.createMediaStreamSource(i);if("audio"!==s.kind)throw t();if(e(n))throw new TypeError;return r},ws=t=>null===t?null:t.hasOwnProperty("OfflineAudioContext")?t.OfflineAudioContext:t.hasOwnProperty("webkitOfflineAudioContext")?t.webkitOfflineAudioContext:null,xs=(t,e,n,s,i,r)=>(o,a)=>{const c=o.createOscillator();return Nn(c,a),jn(c,a,"detune"),jn(c,a,"frequency"),void 0!==a.periodicWave?c.setPeriodicWave(a.periodicWave):Rn(c,a,"type"),e(n,()=>n(o))||Wn(c),e(s,()=>s(o))||r(c,o),e(i,()=>i(o))||Bn(c),t(o,c),c},Ts=t=>(e,n)=>{const s=e.createPanner();return void 0===s.orientationX?t(e,n):(Nn(s,n),jn(s,n,"orientationX"),jn(s,n,"orientationY"),jn(s,n,"orientationZ"),jn(s,n,"positionX"),jn(s,n,"positionY"),jn(s,n,"positionZ"),Rn(s,n,"coneInnerAngle"),Rn(s,n,"coneOuterAngle"),Rn(s,n,"coneOuterGain"),Rn(s,n,"distanceModel"),Rn(s,n,"maxDistance"),Rn(s,n,"panningModel"),Rn(s,n,"refDistance"),Rn(s,n,"rolloffFactor"),s)},bs=(t,e,n,s,i,r,o,a,c,u)=>(l,{coneInnerAngle:h,coneOuterAngle:p,coneOuterGain:d,distanceModel:f,maxDistance:m,orientationX:_,orientationY:g,orientationZ:v,panningModel:y,positionX:w,positionY:x,positionZ:T,refDistance:b,rolloffFactor:C,...A})=>{const S=l.createPanner();if(A.channelCount>2)throw o();if("max"===A.channelCountMode)throw o();Nn(S,A);const k={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},O=n(l,{...k,channelInterpretation:"speakers",numberOfInputs:6}),M=s(l,{...A,gain:1}),E=s(l,{...k,gain:1}),D=s(l,{...k,gain:0}),I=s(l,{...k,gain:0}),R=s(l,{...k,gain:0}),N=s(l,{...k,gain:0}),V=s(l,{...k,gain:0}),P=i(l,256,6,1),q=r(l,{...k,curve:new Float32Array([1,1]),oversample:"none"});let F=[_,g,v],j=[w,x,T];const L=new Float32Array(1);P.onaudioprocess=({inputBuffer:t})=>{const e=[c(t,L,0),c(t,L,1),c(t,L,2)];e.some((t,e)=>t!==F[e])&&(S.setOrientation(...e),F=e);const n=[c(t,L,3),c(t,L,4),c(t,L,5)];n.some((t,e)=>t!==j[e])&&(S.setPosition(...n),j=n)},Object.defineProperty(D.gain,"defaultValue",{get:()=>0}),Object.defineProperty(I.gain,"defaultValue",{get:()=>0}),Object.defineProperty(R.gain,"defaultValue",{get:()=>0}),Object.defineProperty(N.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0});const W={get bufferSize(){},get channelCount(){return S.channelCount},set channelCount(t){if(t>2)throw o();M.channelCount=t,S.channelCount=t},get channelCountMode(){return S.channelCountMode},set channelCountMode(t){if("max"===t)throw o();M.channelCountMode=t,S.channelCountMode=t},get channelInterpretation(){return S.channelInterpretation},set channelInterpretation(t){M.channelInterpretation=t,S.channelInterpretation=t},get coneInnerAngle(){return S.coneInnerAngle},set coneInnerAngle(t){S.coneInnerAngle=t},get coneOuterAngle(){return S.coneOuterAngle},set coneOuterAngle(t){S.coneOuterAngle=t},get coneOuterGain(){return S.coneOuterGain},set coneOuterGain(t){if(t<0||t>1)throw e();S.coneOuterGain=t},get context(){return S.context},get distanceModel(){return S.distanceModel},set distanceModel(t){S.distanceModel=t},get inputs(){return[M]},get maxDistance(){return S.maxDistance},set maxDistance(t){if(t<0)throw new RangeError;S.maxDistance=t},get numberOfInputs(){return S.numberOfInputs},get numberOfOutputs(){return S.numberOfOutputs},get orientationX(){return E.gain},get orientationY(){return D.gain},get orientationZ(){return I.gain},get panningModel(){return S.panningModel},set panningModel(t){S.panningModel=t},get positionX(){return R.gain},get positionY(){return N.gain},get positionZ(){return V.gain},get refDistance(){return S.refDistance},set refDistance(t){if(t<0)throw new RangeError;S.refDistance=t},get rolloffFactor(){return S.rolloffFactor},set rolloffFactor(t){if(t<0)throw new RangeError;S.rolloffFactor=t},addEventListener(...t){return M.addEventListener(t[0],t[1],t[2])},dispatchEvent(...t){return M.dispatchEvent(t[0])},removeEventListener(...t){return M.removeEventListener(t[0],t[1],t[2])}};h!==W.coneInnerAngle&&(W.coneInnerAngle=h),p!==W.coneOuterAngle&&(W.coneOuterAngle=p),d!==W.coneOuterGain&&(W.coneOuterGain=d),f!==W.distanceModel&&(W.distanceModel=f),m!==W.maxDistance&&(W.maxDistance=m),_!==W.orientationX.value&&(W.orientationX.value=_),g!==W.orientationY.value&&(W.orientationY.value=g),v!==W.orientationZ.value&&(W.orientationZ.value=v),y!==W.panningModel&&(W.panningModel=y),w!==W.positionX.value&&(W.positionX.value=w),x!==W.positionY.value&&(W.positionY.value=x),T!==W.positionZ.value&&(W.positionZ.value=T),b!==W.refDistance&&(W.refDistance=b),C!==W.rolloffFactor&&(W.rolloffFactor=C),1===F[0]&&0===F[1]&&0===F[2]||S.setOrientation(...F),0===j[0]&&0===j[1]&&0===j[2]||S.setPosition(...j);const B=()=>{M.connect(S),t(M,q,0,0),q.connect(E).connect(O,0,0),q.connect(D).connect(O,0,1),q.connect(I).connect(O,0,2),q.connect(R).connect(O,0,3),q.connect(N).connect(O,0,4),q.connect(V).connect(O,0,5),O.connect(P).connect(l.destination)},U=()=>{M.disconnect(S),a(M,q,0,0),q.disconnect(E),E.disconnect(O),q.disconnect(D),D.disconnect(O),q.disconnect(I),I.disconnect(O),q.disconnect(R),R.disconnect(O),q.disconnect(N),N.disconnect(O),q.disconnect(V),V.disconnect(O),O.disconnect(P),P.disconnect(l.destination)};return u(rs(W,S),B,U)},Cs=t=>(e,{disableNormalization:n,imag:s,real:i})=>{const r=s instanceof Float32Array?s:new Float32Array(s),o=i instanceof Float32Array?i:new Float32Array(i),a=e.createPeriodicWave(o,r,{disableNormalization:n});if(Array.from(s).length<2)throw t();return a},As=(t,e,n,s)=>t.createScriptProcessor(e,n,s),Ss=(t,e)=>(n,s)=>{const i=s.channelCountMode;if("clamped-max"===i)throw e();if(void 0===n.createStereoPanner)return t(n,s);const r=n.createStereoPanner();return Nn(r,s),jn(r,s,"pan"),Object.defineProperty(r,"channelCountMode",{get:()=>i,set:t=>{if(t!==i)throw e()}}),r},ks=(t,e,n,s,i,r)=>{const o=16385,a=new Float32Array([1,1]),c=Math.PI/2,u={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},l={...u,oversample:"none"},h=(t,e,i,r)=>{const h=new Float32Array(o),p=new Float32Array(o);for(let n=0;n{const p=new Float32Array(o),d=new Float32Array(o),f=new Float32Array(o),m=new Float32Array(o),_=Math.floor(o/2);for(let e=0;e_){const t=(e-_)/(o-1-_)*c;p[e]=Math.cos(t),d[e]=Math.sin(t),f[e]=0,m[e]=1}else{const t=e/(o-1-_)*c;p[e]=1,d[e]=0,f[e]=Math.cos(t),m[e]=Math.sin(t)}const g=e(t,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),v=n(t,{...u,gain:0}),y=s(t,{...l,curve:p}),w=n(t,{...u,gain:0}),x=s(t,{...l,curve:d}),T=s(t,{...l,curve:a}),b=n(t,{...u,gain:0}),C=s(t,{...l,curve:f}),A=n(t,{...u,gain:0}),S=s(t,{...l,curve:m});return{connectGraph(){i.connect(g),i.connect(void 0===T.inputs?T:T.inputs[0]),g.connect(v,0),g.connect(w,0),g.connect(b,1),g.connect(A,1),T.connect(r),r.connect(void 0===y.inputs?y:y.inputs[0]),r.connect(void 0===x.inputs?x:x.inputs[0]),r.connect(void 0===C.inputs?C:C.inputs[0]),r.connect(void 0===S.inputs?S:S.inputs[0]),y.connect(v.gain),x.connect(w.gain),C.connect(b.gain),S.connect(A.gain),v.connect(h,0,0),b.connect(h,0,0),w.connect(h,0,1),A.connect(h,0,1)},disconnectGraph(){i.disconnect(g),i.disconnect(void 0===T.inputs?T:T.inputs[0]),g.disconnect(v,0),g.disconnect(w,0),g.disconnect(b,1),g.disconnect(A,1),T.disconnect(r),r.disconnect(void 0===y.inputs?y:y.inputs[0]),r.disconnect(void 0===x.inputs?x:x.inputs[0]),r.disconnect(void 0===C.inputs?C:C.inputs[0]),r.disconnect(void 0===S.inputs?S:S.inputs[0]),y.disconnect(v.gain),x.disconnect(w.gain),C.disconnect(b.gain),S.disconnect(A.gain),v.disconnect(h,0,0),b.disconnect(h,0,0),w.disconnect(h,0,1),A.disconnect(h,0,1)}}},d=(t,e,n,s,r)=>{if(1===e)return h(t,n,s,r);if(2===e)return p(t,n,s,r);throw i()};return(e,{channelCount:s,channelCountMode:o,pan:a,...c})=>{if("max"===o)throw i();const u=t(e,{...c,channelCount:1,channelCountMode:o,numberOfInputs:2}),l=n(e,{...c,channelCount:s,channelCountMode:o,gain:1}),h=n(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:a});let{connectGraph:p,disconnectGraph:f}=d(e,s,l,h,u);Object.defineProperty(h.gain,"defaultValue",{get:()=>0}),Object.defineProperty(h.gain,"maxValue",{get:()=>1}),Object.defineProperty(h.gain,"minValue",{get:()=>-1});const m={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(t){l.channelCount!==t&&(_&&f(),({connectGraph:p,disconnectGraph:f}=d(e,t,l,h,u)),_&&p()),l.channelCount=t},get channelCountMode(){return l.channelCountMode},set channelCountMode(t){if("clamped-max"===t||"max"===t)throw i();l.channelCountMode=t},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(t){l.channelInterpretation=t},get context(){return l.context},get inputs(){return[l]},get numberOfInputs(){return l.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get pan(){return h.gain},addEventListener(...t){return l.addEventListener(t[0],t[1],t[2])},dispatchEvent(...t){return l.dispatchEvent(t[0])},removeEventListener(...t){return l.removeEventListener(t[0],t[1],t[2])}};let _=!1;const g=()=>{p(),_=!0},v=()=>{f(),_=!1};return r(rs(m,u),g,v)}},Os=(t,e,n,s,i,r,o)=>(a,c)=>{const u=a.createWaveShaper();if(null!==r&&"webkitAudioContext"===r.name&&void 0===a.createGain().gain.automationRate)return n(a,c);Nn(u,c);const l=null===c.curve||c.curve instanceof Float32Array?c.curve:new Float32Array(c.curve);if(null!==l&&l.length<2)throw e();Rn(u,{curve:l},"curve"),Rn(u,c,"oversample");let h=null,p=!1;o(u,"curve",t=>()=>t.call(u),e=>n=>(e.call(u,n),p&&(s(n)&&null===h?h=t(a,u):s(n)||null===h||(h(),h=null)),n));const d=()=>{p=!0,s(u.curve)&&(h=t(a,u))},f=()=>{p=!1,null!==h&&(h(),h=null)};return i(u,d,f)},Ms=(t,e,n,s,i)=>(r,{curve:o,oversample:a,...c})=>{const u=r.createWaveShaper(),l=r.createWaveShaper();Nn(u,c),Nn(l,c);const h=n(r,{...c,gain:1}),p=n(r,{...c,gain:-1}),d=n(r,{...c,gain:1}),f=n(r,{...c,gain:-1});let m=null,_=!1,g=null;const v={get bufferSize(){},get channelCount(){return u.channelCount},set channelCount(t){h.channelCount=t,p.channelCount=t,u.channelCount=t,d.channelCount=t,l.channelCount=t,f.channelCount=t},get channelCountMode(){return u.channelCountMode},set channelCountMode(t){h.channelCountMode=t,p.channelCountMode=t,u.channelCountMode=t,d.channelCountMode=t,l.channelCountMode=t,f.channelCountMode=t},get channelInterpretation(){return u.channelInterpretation},set channelInterpretation(t){h.channelInterpretation=t,p.channelInterpretation=t,u.channelInterpretation=t,d.channelInterpretation=t,l.channelInterpretation=t,f.channelInterpretation=t},get context(){return u.context},get curve(){return g},set curve(n){if(null!==n&&n.length<2)throw e();if(null===n)u.curve=n,l.curve=n;else{const t=n.length,e=new Float32Array(t+2-t%2),s=new Float32Array(t+2-t%2);e[0]=n[0],s[0]=-n[t-1];const i=Math.ceil((t+1)/2),r=(t+1)/2-1;for(let o=1;o{h.connect(u).connect(d),h.connect(p).connect(l).connect(f).connect(d),_=!0,s(g)&&(m=t(r,h))},w=()=>{h.disconnect(u),u.disconnect(d),h.disconnect(p),p.disconnect(l),l.disconnect(f),f.disconnect(d),_=!1,null!==m&&(m(),m=null)};return i(rs(v,d),y,w)},Es=()=>new DOMException("","NotSupportedError"),Ds={numberOfChannels:1},Is=(t,e,n,s,i)=>class extends t{constructor(t,n,i){let r;if("number"===typeof t&&void 0!==n&&void 0!==i)r={length:n,numberOfChannels:t,sampleRate:i};else{if("object"!==typeof t)throw new Error("The given parameters are not valid.");r=t}const{length:o,numberOfChannels:a,sampleRate:c}={...Ds,...r},u=s(a,o,c);e(Mn,()=>Mn(u))||u.addEventListener("statechange",(()=>{let t=0;const e=n=>{"running"===this._state&&(t>0?(u.removeEventListener("statechange",e),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):t+=1)};return e})()),super(u,a),this._length=o,this._nativeOfflineAudioContext=u,this._state=null}get length(){return void 0===this._nativeOfflineAudioContext.length?this._length:this._nativeOfflineAudioContext.length}get state(){return null===this._state?this._nativeOfflineAudioContext.state:this._state}startRendering(){return"running"===this._state?Promise.reject(n()):(this._state="running",i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,lt(this)}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}},Rs={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},Ns=(t,e,n,s,i,r,o)=>class extends t{constructor(t,o){const a=i(t),c={...Rs,...o},u=n(a,c),l=r(a),h=l?s():null,p=t.sampleRate/2;super(t,!1,u,h),this._detune=e(this,l,u.detune,153600,-153600),this._frequency=e(this,l,u.frequency,p,-p),this._nativeOscillatorNode=u,this._onended=null,this._oscillatorNodeRenderer=h,null!==this._oscillatorNodeRenderer&&void 0!==c.periodicWave&&(this._oscillatorNodeRenderer.periodicWave=c.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(t){const e="function"===typeof t?o(this,t):null;this._nativeOscillatorNode.onended=e;const n=this._nativeOscillatorNode.onended;this._onended=null!==n&&n===e?t:n}get type(){return this._nativeOscillatorNode.type}set type(t){this._nativeOscillatorNode.type=t,null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(t){this._nativeOscillatorNode.setPeriodicWave(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=t)}start(t=0){if(this._nativeOscillatorNode.start(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.start=t),"closed"!==this.context.state){I(this);const t=()=>{this._nativeOscillatorNode.removeEventListener("ended",t),Q(this)&&N(this)};this._nativeOscillatorNode.addEventListener("ended",t)}}stop(t=0){this._nativeOscillatorNode.stop(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.stop=t)}},Vs=(t,e,n,s,i)=>()=>{const r=new WeakMap;let o=null,a=null,c=null;const u=async(u,l)=>{let h=n(u);const p=B(h,l);if(!p){const t={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,detune:h.detune.value,frequency:h.frequency.value,periodicWave:null===o?void 0:o,type:h.type};h=e(l,t),null!==a&&h.start(a),null!==c&&h.stop(c)}return r.set(l,h),p?(await t(l,u.detune,h.detune),await t(l,u.frequency,h.frequency)):(await s(l,u.detune,h.detune),await s(l,u.frequency,h.frequency)),await i(u,l,h),h};return{set periodicWave(t){o=t},set start(t){a=t},set stop(t){c=t},render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):u(t,e)}}},Ps={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},qs=(t,e,n,s,i,r,o)=>class extends t{constructor(t,a){const c=i(t),u={...Ps,...a},l=n(c,u),h=r(c),p=h?s():null;super(t,!1,l,p),this._nativePannerNode=l,this._orientationX=e(this,h,l.orientationX,$,H),this._orientationY=e(this,h,l.orientationY,$,H),this._orientationZ=e(this,h,l.orientationZ,$,H),this._positionX=e(this,h,l.positionX,$,H),this._positionY=e(this,h,l.positionY,$,H),this._positionZ=e(this,h,l.positionZ,$,H),o(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(t){this._nativePannerNode.coneInnerAngle=t}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(t){this._nativePannerNode.coneOuterAngle=t}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(t){this._nativePannerNode.coneOuterGain=t}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(t){this._nativePannerNode.distanceModel=t}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(t){this._nativePannerNode.maxDistance=t}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(t){this._nativePannerNode.panningModel=t}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(t){this._nativePannerNode.refDistance=t}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(t){this._nativePannerNode.rolloffFactor=t}},Fs=(t,e,n,s,i,r,o,a,c,u)=>()=>{const l=new WeakMap;let h=null;const p=async(p,d)=>{let f=null,m=r(p);const _={channelCount:m.channelCount,channelCountMode:m.channelCountMode,channelInterpretation:m.channelInterpretation},g={..._,coneInnerAngle:m.coneInnerAngle,coneOuterAngle:m.coneOuterAngle,coneOuterGain:m.coneOuterGain,distanceModel:m.distanceModel,maxDistance:m.maxDistance,panningModel:m.panningModel,refDistance:m.refDistance,rolloffFactor:m.rolloffFactor},v=B(m,d);if("bufferSize"in m)f=s(d,{..._,gain:1});else if(!v){const t={...g,orientationX:m.orientationX.value,orientationY:m.orientationY.value,orientationZ:m.orientationZ.value,positionX:m.positionX.value,positionY:m.positionY.value,positionZ:m.positionZ.value};m=i(d,t)}if(l.set(d,null===f?m:f),null!==f){if(null===h){if(null===o)throw new Error("Missing the native OfflineAudioContext constructor.");const t=new o(6,p.context.length,d.sampleRate),s=e(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});s.connect(t.destination),h=(async()=>{const e=await Promise.all([p.orientationX,p.orientationY,p.orientationZ,p.positionX,p.positionY,p.positionZ].map(async(e,s)=>{const i=n(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:0===s?1:0});return await a(t,e,i.offset),i}));for(let t=0;t<6;t+=1)e[t].connect(s,0,t),e[t].start(0);return u(t)})()}const t=await h,r=s(d,{..._,gain:1});await c(p,d,r);const l=[];for(let e=0;et!==m[e])||n.some((t,e)=>t!==v[e])){m=t,v=n;const o=e/d.sampleRate;y.gain.setValueAtTime(0,o),y=s(d,{..._,gain:0}),w=i(d,{...g,orientationX:m[0],orientationY:m[1],orientationZ:m[2],positionX:v[0],positionY:v[1],positionZ:v[2]}),y.gain.setValueAtTime(1,o),r.connect(y).connect(w.inputs[0]),w.connect(f)}}return f}return v?(await t(d,p.orientationX,m.orientationX),await t(d,p.orientationY,m.orientationY),await t(d,p.orientationZ,m.orientationZ),await t(d,p.positionX,m.positionX),await t(d,p.positionY,m.positionY),await t(d,p.positionZ,m.positionZ)):(await a(d,p.orientationX,m.orientationX),await a(d,p.orientationY,m.orientationY),await a(d,p.orientationZ,m.orientationZ),await a(d,p.positionX,m.positionX),await a(d,p.positionY,m.positionY),await a(d,p.positionZ,m.positionZ)),xt(m)?await c(p,d,m.inputs[0]):await c(p,d,m),m};return{render(t,e){const n=l.get(e);return void 0!==n?Promise.resolve(n):p(t,e)}}},js={disableNormalization:!1},Ls=(t,e,n,s)=>class i{constructor(i,r){const o=e(i),a=s({...js,...r}),c=t(o,a);return n.add(c),c}static[Symbol.hasInstance](t){return null!==t&&"object"===typeof t&&Object.getPrototypeOf(t)===i.prototype||n.has(t)}},Ws=(t,e)=>(n,s,i)=>{const r=t(s);return r.replay(i),e(s,n,i)},Bs=(t,e,n)=>async(s,i,r)=>{const o=t(s);await Promise.all(o.activeInputs.map((t,o)=>Array.from(t).map(async([t,a])=>{const c=e(t),u=await c.render(t,i),l=s.context.destination;n(t)||s===l&&n(s)||u.connect(r,a,o)})).reduce((t,e)=>[...t,...e],[]))},Us=(t,e,n)=>async(s,i,r)=>{const o=e(s);await Promise.all(Array.from(o.activeInputs).map(async([e,s])=>{const o=t(e),a=await o.render(e,i);n(e)||a.connect(r,s)}))},zs=(t,e,n,s)=>i=>t(Mn,()=>Mn(i))?Promise.resolve(t(s,s)).then(t=>{if(!t){const t=n(i,512,0,1);i.oncomplete=()=>{t.onaudioprocess=null,t.disconnect()},t.onaudioprocess=()=>i.currentTime,t.connect(i.destination)}return i.startRendering()}):new Promise(t=>{const n=e(i,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});i.oncomplete=e=>{n.disconnect(),t(e.renderedBuffer)},n.connect(i.destination),i.startRendering()}),Gs=t=>(e,n)=>{t.set(e,n)},Xs=t=>(e,n)=>t.set(e,n),Ys=(t,e,n,s,i,r,o,a)=>(c,u)=>n(c).render(c,u).then(()=>Promise.all(Array.from(s(u)).map(t=>n(t).render(t,u)))).then(()=>i(u)).then(n=>("function"!==typeof n.copyFromChannel?(o(n),X(n)):e(r,()=>r(n))||a(n),t.add(n),n)),Zs={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},Hs=(t,e,n,s,i,r)=>class extends t{constructor(t,o){const a=i(t),c={...Zs,...o},u=n(a,c),l=r(a),h=l?s():null;super(t,!1,u,h),this._pan=e(this,l,u.pan)}get pan(){return this._pan}},$s=(t,e,n,s,i)=>()=>{const r=new WeakMap,o=async(o,a)=>{let c=n(o);const u=B(c,a);if(!u){const t={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,pan:c.pan.value};c=e(a,t)}return r.set(a,c),u?await t(a,o.pan,c.pan):await s(a,o.pan,c.pan),xt(c)?await i(o,a,c.inputs[0]):await i(o,a,c),c};return{render(t,e){const n=r.get(e);return void 0!==n?Promise.resolve(n):o(t,e)}}},Qs=t=>()=>{if(null===t)return!1;try{new t({length:1,sampleRate:44100})}catch{return!1}return!0},Js=(t,e)=>async()=>{if(null===t)return!0;if(null===e)return!1;const n=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),s=new e(1,128,44100),i=URL.createObjectURL(n);let r=!1,o=!1;try{await s.audioWorklet.addModule(i);const e=new t(s,"a",{numberOfOutputs:0}),n=s.createOscillator();e.port.onmessage=()=>r=!0,e.onprocessorerror=()=>o=!0,n.connect(e),n.start(0),await s.startRendering()}catch{}finally{URL.revokeObjectURL(i)}return r&&!o},Ks=(t,e)=>()=>{if(null===e)return Promise.resolve(!1);const n=new e(1,1,44100),s=t(n,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(t=>{n.oncomplete=()=>{s.disconnect(),t(0!==n.currentTime)},n.startRendering()})},ti=()=>new DOMException("","UnknownError"),ei={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},ni=(t,e,n,s,i,r,o)=>class extends t{constructor(t,e){const a=i(t),c={...ei,...e},u=n(a,c),l=r(a),h=l?s():null;super(t,!0,u,h),this._isCurveNullified=!1,this._nativeWaveShaperNode=u,o(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(t){if(null===t)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(t.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=t}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(t){this._nativeWaveShaperNode.oversample=t}},si=(t,e,n)=>()=>{const s=new WeakMap,i=async(i,r)=>{let o=e(i);const a=B(o,r);if(!a){const e={channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,curve:o.curve,oversample:o.oversample};o=t(r,e)}return s.set(r,o),xt(o)?await n(i,r,o.inputs[0]):await n(i,r,o),o};return{render(t,e){const n=s.get(e);return void 0!==n?Promise.resolve(n):i(t,e)}}},ii=()=>"undefined"===typeof window?null:window,ri=(t,e)=>n=>{n.copyFromChannel=(s,i,r=0)=>{const o=t(r),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,u=n.getChannelData(a),l=s.length;for(let t=o<0?-o:0;t+o{const o=t(r),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,u=n.getChannelData(a),l=s.length;for(let t=o<0?-o:0;t+oe=>{e.copyFromChannel=(n=>(s,i,r=0)=>{const o=t(r),a=t(i);if(o(s,i,r=0)=>{const o=t(r),a=t(i);if(o(e,n)=>{const s=n.createBuffer(1,1,44100);null===e.buffer&&(e.buffer=s),t(e,"buffer",t=>()=>{const n=t.call(e);return n===s?null:n},t=>n=>t.call(e,null===n?s:n))},ci=(t,e)=>(n,s)=>{s.channelCount=1,s.channelCountMode="explicit",Object.defineProperty(s,"channelCount",{get:()=>1,set:()=>{throw t()}}),Object.defineProperty(s,"channelCountMode",{get:()=>"explicit",set:()=>{throw t()}});const i=n.createBufferSource(),r=()=>{const t=s.numberOfInputs;for(let e=0;ei.disconnect(s);e(s,r,o)},ui=(t,e,n)=>void 0===t.copyFromChannel?t.getChannelData(n)[0]:(t.copyFromChannel(e,n),e[0]),li=t=>{if(null===t)return!1;const e=t.length;return e%2!==0?0!==t[Math.floor(e/2)]:t[e/2-1]+t[e/2]!==0},hi=(t,e,n,s)=>{let i=t;while(!i.hasOwnProperty(e))i=Object.getPrototypeOf(i);const{get:r,set:o}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,{get:n(r),set:s(o)})},pi=t=>({...t,outputChannelCount:void 0!==t.outputChannelCount?t.outputChannelCount:1===t.numberOfInputs&&1===t.numberOfOutputs?[t.channelCount]:Array.from({length:t.numberOfOutputs},()=>1)}),di=t=>({...t,channelCount:t.numberOfOutputs}),fi=t=>{const{imag:e,real:n}=t;return void 0===e?void 0===n?{...t,imag:[0,0],real:[0,0]}:{...t,imag:Array.from(n,()=>0),real:n}:void 0===n?{...t,imag:e,real:Array.from(e,()=>0)}:{...t,imag:e,real:n}},mi=(t,e,n)=>{try{t.setValueAtTime(e,n)}catch(s){if(9!==s.code)throw s;mi(t,e,n+1e-7)}},_i=t=>{const e=t.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},gi=t=>{const e=t.createBufferSource(),n=t.createBuffer(1,1,44100);e.buffer=n;try{e.start(0,1)}catch{return!1}return!0},vi=t=>{const e=t.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},yi=t=>{const e=t.createOscillator();try{e.start(-1)}catch(n){return n instanceof RangeError}return!1},wi=t=>{const e=t.createBuffer(1,1,44100),n=t.createBufferSource();n.buffer=e,n.start(),n.stop();try{return n.stop(),!0}catch{return!1}},xi=t=>{const e=t.createOscillator();try{e.stop(-1)}catch(n){return n instanceof RangeError}return!1},Ti=t=>{const{port1:e,port2:n}=new MessageChannel;try{e.postMessage(t)}finally{e.close(),n.close()}},bi=t=>{t.start=(e=>(n=0,s=0,i)=>{const r=t.buffer,o=null===r?s:Math.min(r.duration,s);null!==r&&o>r.duration-.5/t.context.sampleRate?e.call(t,n,0,0):e.call(t,n,o,i)})(t.start)},Ci=(t,e)=>{const n=e.createGain();t.connect(n);const s=(e=>()=>{e.call(t,n),t.removeEventListener("ended",s)})(t.disconnect);t.addEventListener("ended",s),rs(t,n),t.stop=(e=>{let s=!1;return(i=0)=>{if(s)try{e.call(t,i)}catch{n.gain.setValueAtTime(0,i)}else e.call(t,i),s=!0}})(t.stop)},Ai=(t,e)=>n=>{const s={value:t};return Object.defineProperties(n,{currentTarget:s,target:s}),"function"===typeof e?e.call(t,n):e.handleEvent.call(t,n)},Si=c(vt),ki=q(vt),Oi=De(M),Mi=new WeakMap,Ei=$e(Mi),Di=oe(new Map,new WeakMap),Ii=ii(),Ri=qn(Di,G),Ni=He(at),Vi=Bs(at,Ni,Et),Pi=U(Ri,Ot,Vi),qi=tn(_),Fi=ws(Ii),ji=wn(Fi),Li=new WeakMap,Wi=Be(Ai),Bi=zn(Ii),Ui=_n(Bi),zi=gn(Ii),Gi=vn(Ii),Xi=Xn(Ii),Yi=zt(u(p),P(Si,ki,Tt,Oi,kt,at,Ei,D,Ot,vt,Q,Et,Dt),Di,hn(v,kt,at,Ot,Mt,Q),G,sn,Es,ke(Tt,v,at,Ot,Mt,qi,Q,ji),Ne(Li,at,O),Wi,qi,Ui,zi,Gi,ji,Xi),Zi=W(Yi,Pi,G,Ri,qi,ji),Hi=new WeakSet,$i=Fn(Ii),Qi=ye(new Uint32Array(1)),Ji=ri(Qi,G),Ki=oi(Qi),tr=Z(Hi,Di,Es,$i,Fi,Qs($i),Ji,Ki),er=F(ls),nr=Us(Ni,ct,Et),sr=de(nr),ir=Un(er,Di,_i,gi,vi,yi,wi,xi,bi,ai(hi),Ci),rr=Ws(Qe(ct),nr),or=tt(sr,ir,Ot,rr,Vi),ar=Gt(l(f),Li,m,Xt,o["createCancelAndHoldAutomationEvent"],o["createCancelScheduledValuesAutomationEvent"],o["createExponentialRampToValueAutomationEvent"],o["createLinearRampToValueAutomationEvent"],o["createSetTargetAutomationEvent"],o["createSetValueAutomationEvent"],o["createSetValueCurveAutomationEvent"],Bi,mi),cr=K(Yi,or,ar,Ke,ir,qi,ji,Ai),ur=dt(Yi,ft,G,Ke,Gn(ls,hi),qi,ji,Vi),lr=re(sr,ts,Ot,rr,Vi),hr=Xs(Mi),pr=ie(Yi,ar,lr,sn,ts,qi,ji,hr),dr=In(vt,zi),fr=ci(Ke,dr),mr=es(Bi,fr),_r=ue(mr,Ot,Vi),gr=ce(Yi,_r,mr,qi,ji),vr=pe(ss,Ot,Vi),yr=he(Yi,vr,ss,qi,ji,di),wr=os(er,ir,ls,dr),xr=is(er,Di,wr,yi,xi),Tr=ve(sr,xr,Ot,rr,Vi),br=ge(Yi,ar,Tr,xr,qi,ji,Ai),Cr=as(Es,hi),Ar=Te(Cr,Ot,Vi),Sr=xe(Yi,Ar,Cr,qi,ji,hr),kr=Ee(sr,cs,Ot,rr,Vi),Or=Me(Yi,ar,kr,cs,qi,ji,hr),Mr=us(Es),Er=je(sr,Mr,Ot,rr,Vi),Dr=Fe(Yi,ar,Er,Mr,Es,qi,ji,hr),Ir=Ye(sr,ls,Ot,rr,Vi),Rr=Xe(Yi,ar,Ir,ls,qi,ji),Nr=ms(sn,Ke,As,Es),Vr=zs(Di,ls,As,Ks(ls,Fi)),Pr=ln(ir,Ot,Fi,Vi,Vr),qr=hs(Nr),Fr=an(Yi,qr,Pr,qi,ji,hr),jr=mt(ar,mr,xr,As,Es,ui,ji,hi),Lr=new WeakMap,Wr=On(ur,jr,Wi,ji,Lr,Ai),Br=xs(er,Di,yi,wi,xi,Ci),Ur=Vs(sr,Br,Ot,rr,Vi),zr=Ns(Yi,ar,Br,Ur,qi,ji,Ai),Gr=me(ir),Xr=Ms(Gr,Ke,ls,li,dr),Yr=Os(Gr,Ke,Xr,li,dr,Bi,hi),Zr=bs(Tt,Ke,mr,ls,As,Yr,Es,kt,ui,dr),Hr=Ts(Zr),$r=Fs(sr,mr,xr,ls,Hr,Ot,Fi,rr,Vi,Vr),Qr=qs(Yi,ar,Hr,$r,qi,ji,hr),Jr=Cs(G),Kr=Ls(Jr,qi,new WeakSet,fi),to=ks(mr,ss,ls,Yr,Es,dr),eo=Ss(to,Es),no=$s(sr,eo,Ot,rr,Vi),so=Hs(Yi,ar,eo,no,qi,ji),io=si(Yr,Ot,Vi),ro=ni(Yi,Ke,Yr,io,qi,ji,hr),oo=xn(Ii),ao=Ue(Ii),co=new WeakMap,uo=en(co,Fi),lo=oo?k(Di,Es,We(Ii),ao,ze(a),qi,uo,ji,Xi,new WeakMap,new WeakMap,Js(Xi,Fi),Ii):void 0,ho=yn(Ui,ji),po=Se(Hi,Di,Ce,Le,new WeakSet,qi,ho,z,Mn,Ji,Ki),fo=ne(lo,Zi,tr,cr,pr,gr,yr,br,Sr,po,Or,Dr,Rr,Fr,Wr,zr,Qr,Kr,so,ro),mo=Tn(Yi,_s,qi,ji),_o=Cn(Yi,gs,qi,ji),go=An(Yi,vs,qi,ji),vo=ys(Ke,ji),yo=Sn(Yi,vo,qi),wo=pt(fo,Ke,Es,ti,mo,_o,go,yo,Bi),xo=nn(Lr),To=j(xo),bo=fe(G),Co=Ie(xo),Ao=Pe(G),So=new WeakMap,ko=Ze(So,O),Oo=Kn(bo,G,Ke,mr,ss,xr,ls,As,Es,Ao,ao,ko,dr),Mo=Zn(Ke,Oo,ls,Es,dr),Eo=ee(sr,bo,ir,mr,ss,xr,ls,Co,Ao,ao,Ot,Xi,Fi,rr,Vi,Vr),Do=Je(co),Io=Gs(So),Ro=oo?Ht(To,Yi,ar,Eo,Mo,at,Do,qi,ji,Xi,pi,Io,Ti,Ai):void 0,No=(kn(Ke,Es,ti,Wr,Bi),be(Es,Fi)),Vo=Ys(Hi,Di,Ni,xo,Vr,z,Ji,Ki),Po=(Dn(Di,Ke,No,Wr,Vo),Is(fo,Di,Ke,No,Vo)),qo=pn(_,Ui),Fo=dn(d,zi),jo=fn(m,Gi),Lo=mn(_,ji);function Wo(t,e){if(!t)throw new Error(e)}function Bo(t,e,n=1/0){if(!(e<=t&&t<=n))throw new RangeError(`Value must be within [${e}, ${n}], got: ${t}`)}function Uo(t){t.isOffline||"running"===t.state||Xo('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let zo=console;function Go(...t){zo.log(...t)}function Xo(...t){zo.warn(...t)}function Yo(t){return"undefined"===typeof t}function Zo(t){return!Yo(t)}function Ho(t){return"function"===typeof t}function $o(t){return"number"===typeof t}function Qo(t){return"[object Object]"===Object.prototype.toString.call(t)&&t.constructor===Object}function Jo(t){return"boolean"===typeof t}function Ko(t){return Array.isArray(t)}function ta(t){return"string"===typeof t}function ea(t){return ta(t)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(t)}function na(t){return new wo(t)}function sa(t,e,n){return new Po(t,e,n)}const ia="object"===typeof self?self:null,ra=ia&&(ia.hasOwnProperty("AudioContext")||ia.hasOwnProperty("webkitAudioContext"));function oa(t,e,n){return Wo(Zo(Ro),"This node only works in a secure context (https or localhost)"),new Ro(t,e,n)}function aa(t,e,n,s){var i,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,n):s;if("object"===typeof Reflect&&"function"===typeof Reflect.decorate)o=Reflect.decorate(t,e,n,s);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(r<3?i(o):r>3?i(e,n,o):i(e,n))||o);return r>3&&o&&Object.defineProperty(e,n,o),o}function ca(t,e,n,s){function i(t){return t instanceof n?t:new n((function(e){e(t)}))}return new(n||(n=Promise))((function(n,r){function o(t){try{c(s.next(t))}catch(e){r(e)}}function a(t){try{c(s["throw"](t))}catch(e){r(e)}}function c(t){t.done?n(t.value):i(t.value).then(o,a)}c((s=s.apply(t,e||[])).next())}))}Object.create;Object.create;class ua{constructor(t,e,n){this._callback=t,this._type=e,this._updateInterval=n,this._createClock()}_createWorker(){const t=new Blob([`\n\t\t\t// the initial timeout time\n\t\t\tlet timeoutTime = ${(1e3*this._updateInterval).toFixed(1)};\n\t\t\t// onmessage callback\n\t\t\tself.onmessage = function(msg){\n\t\t\t\ttimeoutTime = parseInt(msg.data);\n\t\t\t};\n\t\t\t// the tick function which posts a message\n\t\t\t// and schedules a new tick\n\t\t\tfunction tick(){\n\t\t\t\tsetTimeout(tick, timeoutTime);\n\t\t\t\tself.postMessage('tick');\n\t\t\t}\n\t\t\t// call tick initially\n\t\t\ttick();\n\t\t\t`],{type:"text/javascript"}),e=URL.createObjectURL(t),n=new Worker(e);n.onmessage=this._callback.bind(this),this._worker=n}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},1e3*this._updateInterval)}_createClock(){if("worker"===this._type)try{this._createWorker()}catch(t){this._type="timeout",this._createClock()}else"timeout"===this._type&&this._createTimeout()}_disposeClock(){this._timeout&&(clearTimeout(this._timeout),this._timeout=0),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(t){this._updateInterval=Math.max(t,128/44100),"worker"===this._type&&this._worker.postMessage(Math.max(1e3*t,1))}get type(){return this._type}set type(t){this._disposeClock(),this._type=t,this._createClock()}dispose(){this._disposeClock()}}function la(t){return jo(t)}function ha(t){return Fo(t)}function pa(t){return Lo(t)}function da(t){return qo(t)}function fa(t){return t instanceof AudioBuffer}function ma(t,e){return"value"===t||la(e)||ha(e)||fa(e)}function _a(t,...e){if(!e.length)return t;const n=e.shift();if(Qo(t)&&Qo(n))for(const s in n)ma(s,n[s])?t[s]=n[s]:Qo(n[s])?(t[s]||Object.assign(t,{[s]:{}}),_a(t[s],n[s])):Object.assign(t,{[s]:n[s]});return _a(t,...e)}function ga(t,e){return t.length===e.length&&t.every((t,n)=>e[n]===t)}function va(t,e,n=[],s){const i={},r=Array.from(e);if(Qo(r[0])&&s&&!Reflect.has(r[0],s)){const e=Object.keys(r[0]).some(e=>Reflect.has(t,e));e||(_a(i,{[s]:r[0]}),n.splice(n.indexOf(s),1),r.shift())}if(1===r.length&&Qo(r[0]))_a(i,r[0]);else for(let o=0;o{Reflect.has(t,e)&&delete t[e]}),t} +/** + * Tone.js + * @author Yotam Mann + * @license http://opensource.org/licenses/MIT MIT License + * @copyright 2014-2019 Yotam Mann + */class Ta{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...t){(this.debug||ia&&this.toString()===ia.TONE_DEBUG_CLASS)&&Go(this,...t)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}Ta.version=r;const ba=1e-6;function Ca(t,e){return t>e+ba}function Aa(t,e){return Ca(t,e)||ka(t,e)}function Sa(t,e){return t+bathis.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(t){const e=this._timeline.indexOf(t);return-1!==e&&this._timeline.splice(e,1),this}get(t,e="time"){const n=this._search(t,e);return-1!==n?this._timeline[n]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(t,e="time"){const n=this._search(t,e);return n+10&&this._timeline[e-1].time=0?this._timeline[n-1]:null}cancel(t){if(this._timeline.length>1){let e=this._search(t);if(e>=0)if(ka(this._timeline[e].time,t)){for(let n=e;n>=0;n--){if(!ka(this._timeline[n].time,t))break;e=n}this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&Aa(this._timeline[0].time,t)&&(this._timeline=[]);return this}cancelBefore(t){const e=this._search(t);return e>=0&&(this._timeline=this._timeline.slice(e+1)),this}previousEvent(t){const e=this._timeline.indexOf(t);return e>0?this._timeline[e-1]:null}_search(t,e="time"){if(0===this._timeline.length)return-1;let n=0;const s=this._timeline.length;let i=s;if(s>0&&this._timeline[s-1][e]<=t)return s-1;while(n=0&&this._timeline[n].time>=t)n--;return this._iterate(e,n+1),this}forEachAtTime(t,e){const n=this._search(t);if(-1!==n&&ka(this._timeline[n].time,t)){let s=n;for(let e=n;e>=0;e--){if(!ka(this._timeline[e].time,t))break;s=e}this._iterate(t=>{e(t)},s,n)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const Ea=[];function Da(t){Ea.push(t)}function Ia(t){Ea.forEach(e=>e(t))}const Ra=[];function Na(t){Ra.push(t)}function Va(t){Ra.forEach(e=>e(t))}class Pa extends Ta{constructor(){super(...arguments),this.name="Emitter"}on(t,e){const n=t.split(/\W+/);return n.forEach(t=>{Yo(this._events)&&(this._events={}),this._events.hasOwnProperty(t)||(this._events[t]=[]),this._events[t].push(e)}),this}once(t,e){const n=(...s)=>{e(...s),this.off(t,n)};return this.on(t,n),this}off(t,e){const n=t.split(/\W+/);return n.forEach(n=>{if(Yo(this._events)&&(this._events={}),this._events.hasOwnProperty(t))if(Yo(e))this._events[t]=[];else{const n=this._events[t];for(let t=n.length-1;t>=0;t--)n[t]===e&&n.splice(t,1)}}),this}emit(t,...e){if(this._events&&this._events.hasOwnProperty(t)){const n=this._events[t].slice(0);for(let t=0,s=n.length;t{const n=Object.getOwnPropertyDescriptor(Pa.prototype,e);Object.defineProperty(t.prototype,e,n)})}dispose(){return super.dispose(),this._events=void 0,this}}class qa extends Pa{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class Fa extends qa{constructor(){super(),this.name="Context",this._constants=new Map,this._timeouts=new Ma,this._timeoutIds=0,this._initialized=!1,this.isOffline=!1,this._workletModules=new Map;const t=va(Fa.getDefaults(),arguments,["context"]);t.context?this._context=t.context:this._context=na({latencyHint:t.latencyHint}),this._ticker=new ua(this.emit.bind(this,"tick"),t.clockSource,t.updateInterval),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this._setLatencyHint(t.latencyHint),this.lookAhead=t.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){return this._initialized||(Ia(this),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(t,e,n){return this._context.createBuffer(t,e,n)}createChannelMerger(t){return this._context.createChannelMerger(t)}createChannelSplitter(t){return this._context.createChannelSplitter(t)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(t){return this._context.createDelay(t)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(t,e){return this._context.createIIRFilter(t,e)}createPanner(){return this._context.createPanner()}createPeriodicWave(t,e,n){return this._context.createPeriodicWave(t,e,n)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(t){Wo(da(this._context),"Not available if OfflineAudioContext");const e=this._context;return e.createMediaStreamSource(t)}createMediaElementSource(t){Wo(da(this._context),"Not available if OfflineAudioContext");const e=this._context;return e.createMediaElementSource(t)}createMediaStreamDestination(){Wo(da(this._context),"Not available if OfflineAudioContext");const t=this._context;return t.createMediaStreamDestination()}decodeAudioData(t){return this._context.decodeAudioData(t)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(t){Wo(!this._initialized,"The listener cannot be set after initialization."),this._listener=t}get transport(){return this.initialize(),this._transport}set transport(t){Wo(!this._initialized,"The transport cannot be set after initialization."),this._transport=t}get draw(){return this.initialize(),this._draw}set draw(t){Wo(!this._initialized,"Draw cannot be set after initialization."),this._draw=t}get destination(){return this.initialize(),this._destination}set destination(t){Wo(!this._initialized,"The destination cannot be set after initialization."),this._destination=t}createAudioWorkletNode(t,e){return oa(this.rawContext,t,e)}addAudioWorkletModule(t,e){return ca(this,void 0,void 0,(function*(){Wo(Zo(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletModules.has(e)||this._workletModules.set(e,this.rawContext.audioWorklet.addModule(t)),yield this._workletModules.get(e)}))}workletsAreReady(){return ca(this,void 0,void 0,(function*(){const t=[];this._workletModules.forEach(e=>t.push(e)),yield Promise.all(t)}))}get updateInterval(){return this._ticker.updateInterval}set updateInterval(t){this._ticker.updateInterval=t}get clockSource(){return this._ticker.type}set clockSource(t){this._ticker.type=t}get latencyHint(){return this._latencyHint}_setLatencyHint(t){let e=0;if(this._latencyHint=t,ta(t))switch(t){case"interactive":e=.1;break;case"playback":e=.5;break;case"balanced":e=.25;break}this.lookAhead=e,this.updateInterval=e/2}get rawContext(){return this._context}now(){return this._context.currentTime+this.lookAhead}immediate(){return this._context.currentTime}resume(){return da(this._context)?this._context.resume():Promise.resolve()}close(){return ca(this,void 0,void 0,(function*(){da(this._context)&&(yield this._context.close()),this._initialized&&Va(this)}))}getConstant(t){if(this._constants.has(t))return this._constants.get(t);{const e=this._context.createBuffer(1,128,this._context.sampleRate),n=e.getChannelData(0);for(let i=0;ithis._constants[t].disconnect()),this}_timeoutLoop(){const t=this.now();let e=this._timeouts.peek();while(this._timeouts.length&&e&&e.time<=t)e.callback(),this._timeouts.shift(),e=this._timeouts.peek()}setTimeout(t,e){this._timeoutIds++;const n=this.now();return this._timeouts.add({callback:t,id:this._timeoutIds,time:n+e}),this._timeoutIds}clearTimeout(t){return this._timeouts.forEach(e=>{e.id===t&&this._timeouts.remove(e)}),this}clearInterval(t){return this.clearTimeout(t)}setInterval(t,e){const n=++this._timeoutIds,s=()=>{const i=this.now();this._timeouts.add({callback:()=>{t(),s()},id:n,time:i+e})};return s(),n}}class ja extends qa{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(t,e,n){return{}}createChannelMerger(t){return{}}createChannelSplitter(t){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(t){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(t,e){return{}}createPanner(){return{}}createPeriodicWave(t,e,n){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(t){return{}}createMediaElementSource(t){return{}}createMediaStreamDestination(){return{}}decodeAudioData(t){return Promise.resolve({})}createAudioWorkletNode(t,e){return{}}get rawContext(){return{}}addAudioWorkletModule(t,e){return ca(this,void 0,void 0,(function*(){return Promise.resolve()}))}resume(){return Promise.resolve()}setTimeout(t,e){return 0}clearTimeout(t){return this}setInterval(t,e){return 0}clearInterval(t){return this}getConstant(t){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(t){}get destination(){return{}}set destination(t){}now(){return 0}immediate(){return 0}}function La(t,e){Ko(e)?e.forEach(e=>La(t,e)):Object.defineProperty(t,e,{enumerable:!0,writable:!1})}function Wa(t,e){Ko(e)?e.forEach(e=>Wa(t,e)):Object.defineProperty(t,e,{writable:!0})}const Ba=()=>{};class Ua extends Ta{constructor(){super(),this.name="ToneAudioBuffer",this.onload=Ba;const t=va(Ua.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=t.reverse,this.onload=t.onload,t.url&&fa(t.url)||t.url instanceof Ua?this.set(t.url):ta(t.url)&&this.load(t.url).catch(t.onerror)}static getDefaults(){return{onerror:Ba,onload:Ba,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:Ya().sampleRate}set(t){return t instanceof Ua?t.loaded?this._buffer=t.get():t.onload=()=>{this.set(t),this.onload(this)}:this._buffer=t,this._reversed&&this._reverse(),this}get(){return this._buffer}load(t){return ca(this,void 0,void 0,(function*(){const e=Ua.load(t).then(t=>{this.set(t),this.onload(this)});Ua.downloads.push(e);try{yield e}finally{const t=Ua.downloads.indexOf(e);Ua.downloads.splice(t,1)}return this}))}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(t){const e=Ko(t)&&t[0].length>0,n=e?t.length:1,s=e?t[0].length:t.length,i=Ya(),r=i.createBuffer(n,s,i.sampleRate),o=e||1!==n?t:[t];for(let a=0;at/e),this.fromArray(t)}return this}toArray(t){if($o(t))return this.getChannelData(t);if(1===this.numberOfChannels)return this.toArray(0);{const t=[];for(let e=0;e0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(t){this._reversed!==t&&(this._reversed=t,this._reverse())}static fromArray(t){return(new Ua).fromArray(t)}static fromUrl(t){return ca(this,void 0,void 0,(function*(){const e=new Ua;return yield e.load(t)}))}static load(t){return ca(this,void 0,void 0,(function*(){const e=t.match(/\[([^\]\[]+\|.+)\]$/);if(e){const n=e[1].split("|");let s=n[0];for(const t of n)if(Ua.supportsType(t)){s=t;break}t=t.replace(e[0],s)}const n=""===Ua.baseUrl||Ua.baseUrl.endsWith("/")?Ua.baseUrl:Ua.baseUrl+"/",s=yield fetch(n+t);if(!s.ok)throw new Error("could not load url: "+t);const i=yield s.arrayBuffer(),r=yield Ya().decodeAudioData(i);return r}))}static supportsType(t){const e=t.split("."),n=e[e.length-1],s=document.createElement("audio").canPlayType("audio/"+n);return""!==s}static loaded(){return ca(this,void 0,void 0,(function*(){yield Promise.resolve();while(Ua.downloads.length)yield Ua.downloads[0]}))}}Ua.baseUrl="",Ua.downloads=[];class za extends Fa{constructor(){super({clockSource:"offline",context:pa(arguments[0])?arguments[0]:sa(arguments[0],arguments[1]*arguments[2],arguments[2]),lookAhead:0,updateInterval:pa(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=pa(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(t){return ca(this,void 0,void 0,(function*(){let e=0;while(this._duration-this._currentTime>=0){this.emit("tick"),this._currentTime+=128/this.sampleRate,e++;const n=Math.floor(this.sampleRate/128);t&&e%n===0&&(yield new Promise(t=>setTimeout(t,1)))}}))}render(t=!0){return ca(this,void 0,void 0,(function*(){yield this.workletsAreReady(),yield this._renderClock(t);const e=yield this._context.startRendering();return new Ua(e)}))}close(){return Promise.resolve()}}const Ga=new ja;let Xa=Ga;function Ya(){return Xa===Ga&&ra&&Za(new Fa),Xa}function Za(t){Xa=da(t)?new Fa(t):pa(t)?new za(t):t}if(ia&&!ia.TONE_SILENCE_LOGGING){let t="v";"dev"===r&&(t="");const e=` * Tone.js ${t}${r} * `;console.log("%c"+e,"background: #000; color: #fff")}function Ha(t){return Math.pow(10,t/20)}function $a(t){return Math.log(t)/Math.LN10*20}function Qa(t){return Math.pow(2,t/12)}let Ja=440;function Ka(){return Ja}function tc(t){Ja=t}function ec(t){return Math.round(nc(t))}function nc(t){return 69+12*Math.log2(t/Ja)}function sc(t){return Ja*Math.pow(2,(t-69)/12)}class ic extends Ta{constructor(t,e,n){super(),this.defaultUnits="s",this._val=e,this._units=n,this.context=t,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:t=>this._frequencyToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:t=>this._ticksToUnits(parseInt(t,10)),regexp:/^(\d+)i$/i},m:{method:t=>this._beatsToUnits(parseInt(t,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(t,e)=>{const n=parseInt(t,10),s="."===e?1.5:1;return 1===n?this._beatsToUnits(this._getTimeSignature())*s:this._beatsToUnits(4/n)*s},regexp:/^(\d+)n(\.?)$/i},number:{method:t=>this._expressions[this.defaultUnits].method.call(this,t),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:t=>this._secondsToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:t=>parseInt(t,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:t=>{const e=parseInt(t,10);return this._beatsToUnits(8/(3*Math.floor(e)))},regexp:/^(\d+)t$/i},tr:{method:(t,e,n)=>{let s=0;return t&&"0"!==t&&(s+=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(s+=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(s+=this._beatsToUnits(parseFloat(n)/4)),s},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof ic&&this.fromType(this._val),Yo(this._val))return this._noArg();if(ta(this._val)&&Yo(this._units)){for(const t in this._expressions)if(this._expressions[t].regexp.test(this._val.trim())){this._units=t;break}}else if(Qo(this._val)){let t=0;for(const e in this._val)if(Zo(this._val[e])){const n=this._val[e],s=new this.constructor(this.context,e).valueOf()*n;t+=s}return t}if(Zo(this._units)){const t=this._expressions[this._units],e=this._val.toString().trim().match(t.regexp);return e?t.method.apply(this,e.slice(1)):t.method.call(this,this._val)}return ta(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(t){return 1/t}_beatsToUnits(t){return 60/this._getBpm()*t}_secondsToUnits(t){return t}_ticksToUnits(t){return t*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(t){switch(this._units=void 0,this.defaultUnits){case"s":this._val=t.toSeconds();break;case"i":this._val=t.toTicks();break;case"hz":this._val=t.toFrequency();break;case"midi":this._val=t.toMidi();break}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return 1e3*this.toSeconds()}}class rc extends ic{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:t=>this._now()+new this.constructor(this.context,t).valueOf(),regexp:/^\+(.+)/},quantize:{method:t=>{const e=new rc(this.context,t).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(e))},regexp:/^@(.+)/}})}quantize(t,e=1){const n=new this.constructor(this.context,t).valueOf(),s=this.valueOf(),i=Math.round(s/n),r=i*n,o=r-s;return s+o*e}toNotation(){const t=this.toSeconds(),e=["1m"];for(let i=1;i<9;i++){const t=Math.pow(2,i);e.push(t+"n."),e.push(t+"n"),e.push(t+"t")}e.push("0");let n=e[0],s=new rc(this.context,e[0]).toSeconds();return e.forEach(e=>{const i=new rc(this.context,e).toSeconds();Math.abs(i-t)3&&(s=parseFloat(parseFloat(i).toFixed(3)));const r=[n,e,s];return r.join(":")}toTicks(){const t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.round(e*this._getPPQ())}toSeconds(){return this.valueOf()}toMidi(){return ec(this.toFrequency())}_now(){return this.context.now()}}class oc extends rc{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return Ka()}static set A4(t){tc(t)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(t){return"midi"===this.defaultUnits?t:oc.mtof(t)}},note:{regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method(t,e){const n=ac[t.toLowerCase()],s=n+12*(parseInt(e,10)+1);return"midi"===this.defaultUnits?s:oc.mtof(s)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(t,e,n){let s=1;return t&&"0"!==t&&(s*=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(s*=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(s*=this._beatsToUnits(parseFloat(n)/4)),s}}})}transpose(t){return new oc(this.context,this.valueOf()*Qa(t))}harmonize(t){return t.map(t=>this.transpose(t))}toMidi(){return ec(this.valueOf())}toNote(){const t=this.toFrequency(),e=Math.log2(t/oc.A4);let n=Math.round(12*e)+57;const s=Math.floor(n/12);s<0&&(n+=-12*s);const i=cc[n%12];return i+s.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.floor(e*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(t){return t}_ticksToUnits(t){return 1/(60*t/(this._getBpm()*this._getPPQ()))}_beatsToUnits(t){return 1/super._beatsToUnits(t)}_secondsToUnits(t){return 1/t}static mtof(t){return sc(t)}static ftom(t){return ec(t)}}const ac={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},cc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class uc extends rc{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class lc extends Ta{constructor(){super();const t=va(lc.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=t.context}static getDefaults(){return{context:Ya()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(t){return new rc(this.context,t).toSeconds()}toFrequency(t){return new oc(this.context,t).toFrequency()}toTicks(t){return new uc(this.context,t).toTicks()}_getPartialProperties(t){const e=this.get();return Object.keys(e).forEach(n=>{Yo(t[n])&&delete e[n]}),e}get(){const t=ya(this);return Object.keys(t).forEach(e=>{if(Reflect.has(this,e)){const n=this[e];Zo(n)&&Zo(n.value)&&Zo(n.setValueAtTime)?t[e]=n.value:n instanceof lc?t[e]=n._getPartialProperties(t[e]):Ko(n)||$o(n)||ta(n)||Jo(n)?t[e]=n:delete t[e]}}),t}set(t){return Object.keys(t).forEach(e=>{Reflect.has(this,e)&&Zo(this[e])&&(this[e]&&Zo(this[e].value)&&Zo(this[e].setValueAtTime)?this[e].value!==t[e]&&(this[e].value=t[e]):this[e]instanceof lc?this[e].set(t[e]):this[e]=t[e])}),this}}class hc extends Ma{constructor(t="stopped"){super(),this.name="StateTimeline",this._initial=t,this.setStateAtTime(this._initial,0)}getValueAtTime(t){const e=this.get(t);return null!==e?e.state:this._initial}setStateAtTime(t,e,n){return Bo(e,0),this.add(Object.assign({},n,{state:t,time:e})),this}getLastState(t,e){const n=this._search(e);for(let s=n;s>=0;s--){const e=this._timeline[s];if(e.state===t)return e}}getNextState(t,e){const n=this._search(e);if(-1!==n)for(let s=n;s0,"timeConstant must be a number greater than 0");const i=this.toSeconds(e);return this._assertRange(s),Wo(isFinite(s)&&isFinite(i),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(t)}, ${JSON.stringify(e)}`),this._events.add({constant:n,time:i,type:"setTargetAtTime",value:s}),this.log(this.units,"setTargetAtTime",t,i,n),this._param.setTargetAtTime(s,i,n),this}setValueCurveAtTime(t,e,n,s=1){n=this.toSeconds(n),e=this.toSeconds(e);const i=this._fromType(t[0])*s;this.setValueAtTime(this._toType(i),e);const r=n/(t.length-1);for(let o=1;o{"cancelScheduledValues"===e.type?t.cancelScheduledValues(e.time):"setTargetAtTime"===e.type?t.setTargetAtTime(e.value,e.time,e.constant):t[e.type](e.value,e.time)}),this}setParam(t){Wo(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const e=this.input;return e.disconnect(this._param),this.apply(t),this._param=t,e.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(t,e,n,s,i){return n+(e-n)*Math.exp(-(i-t)/s)}_linearInterpolate(t,e,n,s,i){return e+(i-t)/(n-t)*(s-e)}_exponentialInterpolate(t,e,n,s,i){return e*Math.pow(s/e,(i-t)/(n-t))}}class dc extends lc{constructor(){super(...arguments),this.name="ToneAudioNode",this._internalChannels=[]}get numberOfInputs(){return Zo(this.input)?la(this.input)||this.input instanceof pc?1:this.input.numberOfInputs:0}get numberOfOutputs(){return Zo(this.output)?this.output.numberOfOutputs:0}_isAudioNode(t){return Zo(t)&&(t instanceof dc||ha(t))}_getInternalNodes(){const t=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&t.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&t.push(this.output),t}_setChannelProperties(t){const e=this._getInternalNodes();e.forEach(e=>{e.channelCount=t.channelCount,e.channelCountMode=t.channelCountMode,e.channelInterpretation=t.channelInterpretation})}_getChannelProperties(){const t=this._getInternalNodes();Wo(t.length>0,"ToneAudioNode does not have any internal nodes");const e=t[0];return{channelCount:e.channelCount,channelCountMode:e.channelCountMode,channelInterpretation:e.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelCount:t}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelCountMode:t}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelInterpretation:t}))}connect(t,e=0,n=0){return mc(this,t,e,n),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return Xo("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(t,e=0,n=0){return _c(this,t,e,n),this}chain(...t){return fc(this,...t),this}fan(...t){return t.forEach(t=>this.connect(t)),this}dispose(){return super.dispose(),Zo(this.input)&&(this.input instanceof dc?this.input.dispose():ha(this.input)&&this.input.disconnect()),Zo(this.output)&&(this.output instanceof dc?this.output.dispose():ha(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function fc(...t){const e=t.shift();t.reduce((t,e)=>(t instanceof dc?t.connect(e):ha(t)&&mc(t,e),e),e)}function mc(t,e,n=0,s=0){Wo(Zo(t),"Cannot connect from undefined node"),Wo(Zo(e),"Cannot connect to undefined node"),(e instanceof dc||ha(e))&&Wo(e.numberOfInputs>0,"Cannot connect to node with no inputs"),Wo(t.numberOfOutputs>0,"Cannot connect from node with no outputs");while(e instanceof dc||e instanceof pc)Zo(e.input)&&(e=e.input);while(t instanceof dc)Zo(t.output)&&(t=t.output);la(e)?t.connect(e,n):t.connect(e,n,s)}function _c(t,e,n=0,s=0){if(Zo(e))while(e instanceof dc)e=e.input;while(!ha(t))Zo(t.output)&&(t=t.output);la(e)?t.disconnect(e,n):ha(e)?t.disconnect(e,n,s):t.disconnect()}class gc extends dc{constructor(){super(va(gc.getDefaults(),arguments,["gain","units"])),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode;const t=va(gc.getDefaults(),arguments,["gain","units"]);this.gain=new pc({context:this.context,convert:t.convert,param:this._gainNode.gain,units:t.units,value:t.gain,minValue:t.minValue,maxValue:t.maxValue}),La(this,"gain")}static getDefaults(){return Object.assign(dc.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class vc extends dc{constructor(t){super(t),this.onended=Ba,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new gc({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(t){const e=this.toSeconds(t);return-1!==this._startTime&&e>=this._startTime&&(-1===this._stopTime||e<=this._stopTime)?"started":"stopped"},this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut,this._curve=t.curve,this.onended=t.onended}static getDefaults(){return Object.assign(dc.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:Ba})}_startGain(t,e=1){Wo(-1===this._startTime,"Source cannot be started more than once");const n=this.toSeconds(this._fadeIn);return this._startTime=t+n,this._startTime=Math.max(this._startTime,this.context.currentTime),n>0?(this._gainNode.gain.setValueAtTime(0,t),"linear"===this._curve?this._gainNode.gain.linearRampToValueAtTime(e,t+n):this._gainNode.gain.exponentialApproachValueAtTime(e,t,n)):this._gainNode.gain.setValueAtTime(e,t),this}stop(t){return this.log("stop",t),this._stopGain(this.toSeconds(t)),this}_stopGain(t){Wo(-1!==this._startTime,"'start' must be called before 'stop'"),this.cancelStop();const e=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(t)+e,this._stopTime=Math.max(this._stopTime,this.context.currentTime),e>0?"linear"===this._curve?this._gainNode.gain.linearRampTo(0,e,t):this._gainNode.gain.targetRampTo(0,e,t):(this._gainNode.gain.cancelAndHoldAtTime(t),this._gainNode.gain.setValueAtTime(0,t)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const t="exponential"===this._curve?2*e:0;this._stopSource(this.now()+t),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==Ba&&(this.onended(this),this.onended=Ba,!this.context.isOffline)){const t=()=>this.dispose();"undefined"!==typeof window.requestIdleCallback?window.requestIdleCallback(t):setTimeout(t,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),Wo(-1!==this._startTime,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.disconnect(),this}}class yc extends vc{constructor(){super(va(yc.getDefaults(),arguments,["offset"])),this.name="ToneConstantSource",this._source=this.context.createConstantSource();const t=va(yc.getDefaults(),arguments,["offset"]);mc(this._source,this._gainNode),this.offset=new pc({context:this.context,convert:t.convert,param:this._source.offset,units:t.units,value:t.offset,minValue:t.minValue,maxValue:t.maxValue})}static getDefaults(){return Object.assign(vc.getDefaults(),{convert:!0,offset:1,units:"number"})}start(t){const e=this.toSeconds(t);return this.log("start",e),this._startGain(e),this._source.start(e),this}_stopSource(t){this._source.stop(t)}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class wc extends dc{constructor(){super(va(wc.getDefaults(),arguments,["value","units"])),this.name="Signal",this.override=!0;const t=va(wc.getDefaults(),arguments,["value","units"]);this.output=this._constantSource=new yc({context:this.context,convert:t.convert,offset:t.value,units:t.units,minValue:t.minValue,maxValue:t.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(dc.getDefaults(),{convert:!0,units:"number",value:0})}connect(t,e=0,n=0){return xc(this,t,e,n),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(t,e){return this._param.setValueAtTime(t,e),this}getValueAtTime(t){return this._param.getValueAtTime(t)}setRampPoint(t){return this._param.setRampPoint(t),this}linearRampToValueAtTime(t,e){return this._param.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){return this._param.exponentialRampToValueAtTime(t,e),this}exponentialRampTo(t,e,n){return this._param.exponentialRampTo(t,e,n),this}linearRampTo(t,e,n){return this._param.linearRampTo(t,e,n),this}targetRampTo(t,e,n){return this._param.targetRampTo(t,e,n),this}exponentialApproachValueAtTime(t,e,n){return this._param.exponentialApproachValueAtTime(t,e,n),this}setTargetAtTime(t,e,n){return this._param.setTargetAtTime(t,e,n),this}setValueCurveAtTime(t,e,n,s){return this._param.setValueCurveAtTime(t,e,n,s),this}cancelScheduledValues(t){return this._param.cancelScheduledValues(t),this}cancelAndHoldAtTime(t){return this._param.cancelAndHoldAtTime(t),this}rampTo(t,e,n){return this._param.rampTo(t,e,n),this}get value(){return this._param.value}set value(t){this._param.value=t}get convert(){return this._param.convert}set convert(t){this._param.convert=t}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(t){this._param.overridden=t}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(t){return this._param.apply(t),this}}function xc(t,e,n,s){(e instanceof pc||la(e)||e instanceof wc&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof wc&&(e.overridden=!0)),mc(t,e,n,s)}class Tc extends pc{constructor(){super(va(Tc.getDefaults(),arguments,["value"])),this.name="TickParam",this._events=new Ma(1/0),this._multiplier=1;const t=va(Tc.getDefaults(),arguments,["value"]);this._multiplier=t.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(t.value)}),this.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(pc.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(t,e,n){e=this.toSeconds(e),this.setRampPoint(e);const s=this._fromType(t),i=this._events.get(e),r=Math.round(Math.max(1/n,1));for(let o=0;o<=r;o++){const t=n*o+e,r=this._exponentialApproach(i.time,i.value,s,n,t);this.linearRampToValueAtTime(this._toType(r),t)}return this}setValueAtTime(t,e){const n=this.toSeconds(e);super.setValueAtTime(t,e);const s=this._events.get(n),i=this._events.previousEvent(s),r=this._getTicksUntilEvent(i,n);return s.ticks=Math.max(r,0),this}linearRampToValueAtTime(t,e){const n=this.toSeconds(e);super.linearRampToValueAtTime(t,e);const s=this._events.get(n),i=this._events.previousEvent(s),r=this._getTicksUntilEvent(i,n);return s.ticks=Math.max(r,0),this}exponentialRampToValueAtTime(t,e){e=this.toSeconds(e);const n=this._fromType(t),s=this._events.get(e),i=Math.round(Math.max(10*(e-s.time),1)),r=(e-s.time)/i;for(let o=0;o<=i;o++){const t=r*o+s.time,i=this._exponentialInterpolate(s.time,s.value,e,n,t);this.linearRampToValueAtTime(this._toType(i),t)}return this}_getTicksUntilEvent(t,e){if(null===t)t={ticks:0,time:0,type:"setValueAtTime",value:0};else if(Yo(t.ticks)){const e=this._events.previousEvent(t);t.ticks=this._getTicksUntilEvent(e,t.time)}const n=this._fromType(this.getValueAtTime(t.time));let s=this._fromType(this.getValueAtTime(e));const i=this._events.get(e);return i&&i.time===e&&"setValueAtTime"===i.type&&(s=this._fromType(this.getValueAtTime(e-this.sampleTime))),.5*(e-t.time)*(n+s)+t.ticks}getTicksAtTime(t){const e=this.toSeconds(t),n=this._events.get(e);return Math.max(this._getTicksUntilEvent(n,e),0)}getDurationOfTicks(t,e){const n=this.toSeconds(e),s=this.getTicksAtTime(e);return this.getTimeOfTick(s+t)-n}getTimeOfTick(t){const e=this._events.get(t,"ticks"),n=this._events.getAfter(t,"ticks");if(e&&e.ticks===t)return e.time;if(e&&n&&"linearRampToValueAtTime"===n.type&&e.value!==n.value){const s=this._fromType(this.getValueAtTime(e.time)),i=this._fromType(this.getValueAtTime(n.time)),r=(i-s)/(n.time-e.time),o=Math.sqrt(Math.pow(s,2)-2*r*(e.ticks-t)),a=(-s+o)/r,c=(-s-o)/r;return(a>0?a:c)+e.time}return e?0===e.value?1/0:e.time+(t-e.ticks)/e.value:t/this._initialValue}ticksToTime(t,e){return this.getDurationOfTicks(t,e)}timeToTicks(t,e){const n=this.toSeconds(e),s=this.toSeconds(t),i=this.getTicksAtTime(n),r=this.getTicksAtTime(n+s);return r-i}_fromType(t){return"bpm"===this.units&&this.multiplier?1/(60/t/this.multiplier):super._fromType(t)}_toType(t){return"bpm"===this.units&&this.multiplier?t/this.multiplier*60:super._toType(t)}get multiplier(){return this._multiplier}set multiplier(t){const e=this.value;this._multiplier=t,this.cancelScheduledValues(0),this.setValueAtTime(e,0)}}class bc extends wc{constructor(){super(va(bc.getDefaults(),arguments,["value"])),this.name="TickSignal";const t=va(bc.getDefaults(),arguments,["value"]);this.input=this._param=new Tc({context:this.context,convert:t.convert,multiplier:t.multiplier,param:this._constantSource.offset,units:t.units,value:t.value})}static getDefaults(){return Object.assign(wc.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(t,e){return this._param.ticksToTime(t,e)}timeToTicks(t,e){return this._param.timeToTicks(t,e)}getTimeOfTick(t){return this._param.getTimeOfTick(t)}getDurationOfTicks(t,e){return this._param.getDurationOfTicks(t,e)}getTicksAtTime(t){return this._param.getTicksAtTime(t)}get multiplier(){return this._param.multiplier}set multiplier(t){this._param.multiplier=t}dispose(){return super.dispose(),this._param.dispose(),this}}class Cc extends lc{constructor(){super(va(Cc.getDefaults(),arguments,["frequency"])),this.name="TickSource",this._state=new hc,this._tickOffset=new Ma;const t=va(Cc.getDefaults(),arguments,["frequency"]);this.frequency=new bc({context:this.context,units:t.units,value:t.frequency}),La(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},lc.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(t,e){const n=this.toSeconds(t);return"started"!==this._state.getValueAtTime(n)&&(this._state.setStateAtTime("started",n),Zo(e)&&this.setTicksAtTime(e,n)),this}stop(t){const e=this.toSeconds(t);if("stopped"===this._state.getValueAtTime(e)){const t=this._state.get(e);t&&t.time>0&&(this._tickOffset.cancel(t.time),this._state.cancel(t.time))}return this._state.cancel(e),this._state.setStateAtTime("stopped",e),this.setTicksAtTime(0,e),this}pause(t){const e=this.toSeconds(t);return"started"===this._state.getValueAtTime(e)&&this._state.setStateAtTime("paused",e),this}cancel(t){return t=this.toSeconds(t),this._state.cancel(t),this._tickOffset.cancel(t),this}getTicksAtTime(t){const e=this.toSeconds(t),n=this._state.getLastState("stopped",e),s={state:"paused",time:e};this._state.add(s);let i=n,r=0;return this._state.forEachBetween(n.time,e+this.sampleTime,t=>{let e=i.time;const n=this._tickOffset.get(t.time);n&&n.time>=i.time&&(r=n.ticks,e=n.time),"started"===i.state&&"started"!==t.state&&(r+=this.frequency.getTicksAtTime(t.time)-this.frequency.getTicksAtTime(e)),i=t}),this._state.remove(s),r}get ticks(){return this.getTicksAtTime(this.now())}set ticks(t){this.setTicksAtTime(t,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(t){const e=this.now(),n=this.frequency.timeToTicks(t,e);this.setTicksAtTime(n,e)}getSecondsAtTime(t){t=this.toSeconds(t);const e=this._state.getLastState("stopped",t),n={state:"paused",time:t};this._state.add(n);let s=e,i=0;return this._state.forEachBetween(e.time,t+this.sampleTime,t=>{let e=s.time;const n=this._tickOffset.get(t.time);n&&n.time>=s.time&&(i=n.seconds,e=n.time),"started"===s.state&&"started"!==t.state&&(i+=t.time-e),s=t}),this._state.remove(n),i}setTicksAtTime(t,e){return e=this.toSeconds(e),this._tickOffset.cancel(e),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(t,e),ticks:t,time:e}),this}getStateAtTime(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)}getTimeOfTick(t,e=this.now()){const n=this._tickOffset.get(e),s=this._state.get(e),i=Math.max(n.time,s.time),r=this.frequency.getTicksAtTime(i)+t-n.ticks;return this.frequency.getTimeOfTick(r)}forEachTickBetween(t,e,n){let s=this._state.get(t);this._state.forEachBetween(t,e,e=>{s&&"started"===s.state&&"started"!==e.state&&this.forEachTickBetween(Math.max(s.time,t),e.time-this.sampleTime,n),s=e});let i=null;if(s&&"started"===s.state){const o=Math.max(s.time,t),a=this.frequency.getTicksAtTime(o),c=this.frequency.getTicksAtTime(s.time),u=a-c;let l=Math.ceil(u)-u;l=ka(l,1)?0:l;let h=this.frequency.getTimeOfTick(a+l);while(h{switch(t.state){case"started":const e=this._tickSource.getTicksAtTime(t.time);this.emit("start",t.time,e);break;case"stopped":0!==t.time&&this.emit("stop",t.time);break;case"paused":this.emit("pause",t.time);break}}),this._tickSource.forEachTickBetween(t,e,(t,e)=>{this.callback(t,e)}))}getStateAtTime(t){const e=this.toSeconds(t);return this._state.getValueAtTime(e)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}Pa.mixin(Ac);class Sc extends Ta{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const t=va(Sc.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=t.baseUrl,Object.keys(t.urls).forEach(e=>{this._loadingCount++;const n=t.urls[e];this.add(e,n,this._bufferLoaded.bind(this,t.onload),t.onerror)})}static getDefaults(){return{baseUrl:"",onerror:Ba,onload:Ba,urls:{}}}has(t){return this._buffers.has(t.toString())}get(t){return Wo(this.has(t),"ToneAudioBuffers has no buffer named: "+t),this._buffers.get(t.toString())}_bufferLoaded(t){this._loadingCount--,0===this._loadingCount&&t&&t()}get loaded(){return Array.from(this._buffers).every(([t,e])=>e.loaded)}add(t,e,n=Ba,s=Ba){return ta(e)?this._buffers.set(t.toString(),new Ua(this.baseUrl+e,n,s)):this._buffers.set(t.toString(),new Ua(e,n,s)),this}dispose(){return super.dispose(),this._buffers.forEach(t=>t.dispose()),this._buffers.clear(),this}}class kc extends uc{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(t){return this._getPPQ()*t}_secondsToUnits(t){return Math.floor(t/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(t){return t}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class Oc extends lc{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new Ma,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(t,e){return this._events.add({callback:t,time:this.toSeconds(e)}),1===this._events.length&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(t){return this._events.cancel(this.toSeconds(t)),this}_drawLoop(){const t=this.context.currentTime;while(this._events.length&&this._events.peek().time-this.anticipation<=t){const e=this._events.shift();e&&t-e.time<=this.expiration&&e.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}Da(t=>{t.draw=new Oc({context:t})}),Na(t=>{t.draw.dispose()});class Mc extends Ta{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(t){Wo(Zo(t.time),"Events must have a time property"),Wo(Zo(t.duration),"Events must have a duration parameter"),t.time=t.time.valueOf();let e=new Ec(t.time,t.time+t.duration,t);null===this._root?this._root=e:this._root.insert(e),this._length++;while(null!==e)e.updateHeight(),e.updateMax(),this._rebalance(e),e=e.parent;return this}remove(t){if(null!==this._root){const e=[];this._root.search(t.time,e);for(const n of e)if(n.event===t){this._removeNode(n),this._length--;break}}return this}get length(){return this._length}cancel(t){return this.forEachFrom(t,t=>this.remove(t)),this}_setRoot(t){this._root=t,null!==this._root&&(this._root.parent=null)}_replaceNodeInParent(t,e){null!==t.parent?(t.isLeftChild()?t.parent.left=e:t.parent.right=e,this._rebalance(t.parent)):this._setRoot(e)}_removeNode(t){if(null===t.left&&null===t.right)this._replaceNodeInParent(t,null);else if(null===t.right)this._replaceNodeInParent(t,t.left);else if(null===t.left)this._replaceNodeInParent(t,t.right);else{const e=t.getBalance();let n,s=null;if(e>0)if(null===t.left.right)n=t.left,n.right=t.right,s=n;else{n=t.left.right;while(null!==n.right)n=n.right;n.parent&&(n.parent.right=n.left,s=n.parent,n.left=t.left,n.right=t.right)}else if(null===t.right.left)n=t.right,n.left=t.left,s=n;else{n=t.right.left;while(null!==n.left)n=n.left;n.parent&&(n.parent.left=n.right,s=n.parent,n.left=t.left,n.right=t.right)}null!==t.parent?t.isLeftChild()?t.parent.left=n:t.parent.right=n:this._setRoot(n),s&&this._rebalance(s)}t.dispose()}_rotateLeft(t){const e=t.parent,n=t.isLeftChild(),s=t.right;s&&(t.right=s.left,s.left=t),null!==e?n?e.left=s:e.right=s:this._setRoot(s)}_rotateRight(t){const e=t.parent,n=t.isLeftChild(),s=t.left;s&&(t.left=s.right,s.right=t),null!==e?n?e.left=s:e.right=s:this._setRoot(s)}_rebalance(t){const e=t.getBalance();e>1&&t.left?t.left.getBalance()<0?this._rotateLeft(t.left):this._rotateRight(t):e<-1&&t.right&&(t.right.getBalance()>0?this._rotateRight(t.right):this._rotateLeft(t))}get(t){if(null!==this._root){const e=[];if(this._root.search(t,e),e.length>0){let t=e[0];for(let n=1;nt.low&&(t=e[n]);return t.event}}return null}forEach(t){if(null!==this._root){const e=[];this._root.traverse(t=>e.push(t)),e.forEach(e=>{e.event&&t(e.event)})}return this}forEachAtTime(t,e){if(null!==this._root){const n=[];this._root.search(t,n),n.forEach(t=>{t.event&&e(t.event)})}return this}forEachFrom(t,e){if(null!==this._root){const n=[];this._root.searchAfter(t,n),n.forEach(t=>{t.event&&e(t.event)})}return this}dispose(){return super.dispose(),null!==this._root&&this._root.traverse(t=>t.dispose()),this._root=null,this}}class Ec{constructor(t,e,n){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=n,this.low=t,this.high=e,this.max=this.high}insert(t){t.low<=this.low?null===this.left?this.left=t:this.left.insert(t):null===this.right?this.right=t:this.right.insert(t)}search(t,e){t>this.max||(null!==this.left&&this.left.search(t,e),this.low<=t&&this.high>t&&e.push(this),this.low>t||null!==this.right&&this.right.search(t,e))}searchAfter(t,e){this.low>=t&&(e.push(this),null!==this.left&&this.left.searchAfter(t,e)),null!==this.right&&this.right.searchAfter(t,e)}traverse(t){t(this),null!==this.left&&this.left.traverse(t),null!==this.right&&this.right.traverse(t)}updateHeight(){null!==this.left&&null!==this.right?this.height=Math.max(this.left.height,this.right.height)+1:null!==this.right?this.height=this.right.height+1:null!==this.left?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,null!==this.left&&(this.max=Math.max(this.max,this.left.max)),null!==this.right&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let t=0;return null!==this.left&&null!==this.right?t=this.left.height-this.right.height:null!==this.left?t=this.left.height+1:null!==this.right&&(t=-(this.right.height+1)),t}isLeftChild(){return null!==this.parent&&this.parent.left===this}get left(){return this._left}set left(t){this._left=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(t){this._right=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class Dc extends dc{constructor(){super(va(Dc.getDefaults(),arguments,["volume"])),this.name="Volume";const t=va(Dc.getDefaults(),arguments,["volume"]);this.input=this.output=new gc({context:this.context,gain:t.volume,units:"decibels"}),this.volume=this.output.gain,La(this,"volume"),this._unmutedVolume=t.volume,this.mute=t.mute}static getDefaults(){return Object.assign(dc.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(t){!this.mute&&t?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!t&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class Ic extends dc{constructor(){super(va(Ic.getDefaults(),arguments)),this.name="Destination",this.input=new Dc({context:this.context}),this.output=new gc({context:this.context}),this.volume=this.input.volume;const t=va(Ic.getDefaults(),arguments);fc(this.input,this.output,this.context.rawContext.destination),this.mute=t.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(dc.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(t){this.input.mute=t}chain(...t){return this.input.disconnect(),t.unshift(this.input),t.push(this.output),fc(...t),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}Da(t=>{t.destination=new Ic({context:t})}),Na(t=>{t.destination.dispose()});class Rc extends Ta{constructor(t){super(),this.name="TimelineValue",this._timeline=new Ma({memory:10}),this._initialValue=t}set(t,e){return this._timeline.add({value:t,time:e}),this}get(t){const e=this._timeline.get(t);return e?e.value:this._initialValue}}class Nc{constructor(t,e){this.id=Nc._eventId++;const n=Object.assign(Nc.getDefaults(),e);this.transport=t,this.callback=n.callback,this._once=n.once,this.time=n.time}static getDefaults(){return{callback:Ba,once:!1,time:0}}invoke(t){this.callback&&(this.callback(t),this._once&&this.transport.clear(this.id))}dispose(){return this.callback=void 0,this}}Nc._eventId=0;class Vc extends Nc{constructor(t,e){super(t,e),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const n=Object.assign(Vc.getDefaults(),e);this.duration=new kc(t.context,n.duration).valueOf(),this._interval=new kc(t.context,n.interval).valueOf(),this._nextTick=n.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Nc.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(t){this._createEvents(t),super.invoke(t)}_createEvents(t){const e=this.transport.getTicksAtTime(t);e>=this.time&&e>=this._nextTick&&this._nextTick+this._intervalthis.time&&(this._nextTick=this.time+Math.ceil((e-this.time)/this._interval)*this._interval),this._currentId=this.transport.scheduleOnce(this.invoke.bind(this),new kc(this.context,this._nextTick).toSeconds()),this._nextTick+=this._interval,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new kc(this.context,this._nextTick).toSeconds())}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this}}class Pc extends lc{constructor(){super(va(Pc.getDefaults(),arguments)),this.name="Transport",this._loop=new Rc(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new Ma,this._repeatedEvents=new Mc,this._syncedSignals=[],this._swingAmount=0;const t=va(Pc.getDefaults(),arguments);this._ppq=t.ppq,this._clock=new Ac({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=t.ppq,this.bpm.setValueAtTime(t.bpm,0),La(this,"bpm"),this._timeSignature=t.timeSignature,this._swingTicks=t.ppq/2}static getDefaults(){return Object.assign(lc.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(t,e){if(this._loop.get(t)&&e>=this._loopEnd&&(this.emit("loopEnd",t),this._clock.setTicksAtTime(this._loopStart,t),e=this._loopStart,this.emit("loopStart",t,this._clock.getSecondsAtTime(t)),this.emit("loop",t)),this._swingAmount>0&&e%this._ppq!==0&&e%(2*this._swingTicks)!==0){const n=e%(2*this._swingTicks)/(2*this._swingTicks),s=Math.sin(n*Math.PI)*this._swingAmount;t+=new kc(this.context,2*this._swingTicks/3).toSeconds()*s}this._timeline.forEachAtTime(e,e=>e.invoke(t))}schedule(t,e){const n=new Nc(this,{callback:t,time:new uc(this.context,e).toTicks()});return this._addEvent(n,this._timeline)}scheduleRepeat(t,e,n,s=1/0){const i=new Vc(this,{callback:t,duration:new rc(this.context,s).toTicks(),interval:new rc(this.context,e).toTicks(),time:new uc(this.context,n).toTicks()});return this._addEvent(i,this._repeatedEvents)}scheduleOnce(t,e){const n=new Nc(this,{callback:t,once:!0,time:new uc(this.context,e).toTicks()});return this._addEvent(n,this._timeline)}clear(t){if(this._scheduledEvents.hasOwnProperty(t)){const e=this._scheduledEvents[t.toString()];e.timeline.remove(e.event),e.event.dispose(),delete this._scheduledEvents[t.toString()]}return this}_addEvent(t,e){return this._scheduledEvents[t.id.toString()]={event:t,timeline:e},e.add(t),t.id}cancel(t=0){const e=this.toTicks(t);return this._timeline.forEachFrom(e,t=>this.clear(t.id)),this._repeatedEvents.forEachFrom(e,t=>this.clear(t.id)),this}_bindClockEvents(){this._clock.on("start",(t,e)=>{e=new kc(this.context,e).toSeconds(),this.emit("start",t,e)}),this._clock.on("stop",t=>{this.emit("stop",t)}),this._clock.on("pause",t=>{this.emit("pause",t)})}get state(){return this._clock.getStateAtTime(this.now())}start(t,e){let n;return Zo(e)&&(n=this.toTicks(e)),this._clock.start(t,n),this}stop(t){return this._clock.stop(t),this}pause(t){return this._clock.pause(t),this}toggle(t){return t=this.toSeconds(t),"started"!==this._clock.getStateAtTime(t)?this.start(t):this.stop(t),this}get timeSignature(){return this._timeSignature}set timeSignature(t){Ko(t)&&(t=t[0]/t[1]*4),this._timeSignature=t}get loopStart(){return new rc(this.context,this._loopStart,"i").toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t)}get loopEnd(){return new rc(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t)}get loop(){return this._loop.get(this.now())}set loop(t){this._loop.set(t,this.now())}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get swing(){return this._swingAmount}set swing(t){this._swingAmount=t}get swingSubdivision(){return new kc(this.context,this._swingTicks).toNotation()}set swingSubdivision(t){this._swingTicks=this.toTicks(t)}get position(){const t=this.now(),e=this._clock.getTicksAtTime(t);return new kc(this.context,e).toBarsBeatsSixteenths()}set position(t){const e=this.toTicks(t);this.ticks=e}get seconds(){return this._clock.seconds}set seconds(t){const e=this.now(),n=this._clock.frequency.timeToTicks(t,e);this.ticks=n}get progress(){if(this.loop){const t=this.now(),e=this._clock.getTicksAtTime(t);return(e-this._loopStart)/(this._loopEnd-this._loopStart)}return 0}get ticks(){return this._clock.ticks}set ticks(t){if(this._clock.ticks!==t){const e=this.now();if("started"===this.state){const n=this._clock.getTicksAtTime(e),s=this._clock.frequency.getDurationOfTicks(Math.ceil(n)-n,e),i=e+s;this.emit("stop",i),this._clock.setTicksAtTime(t,i),this.emit("start",i,this._clock.getSecondsAtTime(i))}else this._clock.setTicksAtTime(t,e)}}getTicksAtTime(t){return Math.round(this._clock.getTicksAtTime(t))}getSecondsAtTime(t){return this._clock.getSecondsAtTime(t)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(t){this._clock.frequency.multiplier=t}nextSubdivision(t){if(t=this.toTicks(t),"started"!==this.state)return 0;{const e=this.now(),n=this.getTicksAtTime(e),s=t-n%t;return this._clock.nextTickTime(s,e)}}syncSignal(t,e){if(!e){const n=this.now();if(0!==t.getValueAtTime(n)){const s=this.bpm.getValueAtTime(n),i=1/(60/s/this.PPQ);e=t.getValueAtTime(n)/i}else e=0}const n=new gc(e);return this.bpm.connect(n),n.connect(t._param),this._syncedSignals.push({initial:t.value,ratio:n,signal:t}),t.value=0,this}unsyncSignal(t){for(let e=this._syncedSignals.length-1;e>=0;e--){const n=this._syncedSignals[e];n.signal===t&&(n.ratio.dispose(),n.signal.value=n.initial,this._syncedSignals.splice(e,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),Wa(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}Pa.mixin(Pc),Da(t=>{t.transport=new Pc({context:t})}),Na(t=>{t.transport.dispose()});class qc extends dc{constructor(t){super(t),this.input=void 0,this._state=new hc("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=Ba,this._syncedStop=Ba,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Dc({context:this.context,mute:t.mute,volume:t.volume}),this.volume=this._volume.volume,La(this,"volume"),this.onstop=t.onstop}static getDefaults(){return Object.assign(dc.getDefaults(),{mute:!1,onstop:Ba,volume:0})}get state(){return this._synced?"started"===this.context.transport.state?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}_clampToCurrentTime(t){return this._synced?t:Math.max(t,this.context.currentTime)}start(t,e,n){let s=Yo(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t);if(s=this._clampToCurrentTime(s),this._synced||"started"!==this._state.getValueAtTime(s))if(this.log("start",s),this._state.setStateAtTime("started",s),this._synced){const t=this._state.get(s);t&&(t.offset=this.toSeconds(wa(e,0)),t.duration=n?this.toSeconds(n):void 0);const i=this.context.transport.schedule(t=>{this._start(t,e,n)},s);this._scheduled.push(i),"started"===this.context.transport.state&&this.context.transport.getSecondsAtTime(this.immediate())>s&&this._syncedStart(this.now(),this.context.transport.seconds)}else Uo(this.context),this._start(s,e,n);else Wo(Ca(s,this._state.get(s).time),"Start time must be strictly greater than previous start time"),this._state.cancel(s),this._state.setStateAtTime("started",s),this.log("restart",s),this.restart(s,e,n);return this}stop(t){let e=Yo(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t);if(e=this._clampToCurrentTime(e),"started"===this._state.getValueAtTime(e)||Zo(this._state.getNextState("started",e))){if(this.log("stop",e),this._synced){const t=this.context.transport.schedule(this._stop.bind(this),e);this._scheduled.push(t)}else this._stop(e);this._state.cancel(e),this._state.setStateAtTime("stopped",e)}return this}restart(t,e,n){return t=this.toSeconds(t),"started"===this._state.getValueAtTime(t)&&(this._state.cancel(t),this._restart(t,e,n)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(t,e)=>{if(e>0){const n=this._state.get(e);if(n&&"started"===n.state&&n.time!==e){const s=e-this.toSeconds(n.time);let i;n.duration&&(i=this.toSeconds(n.duration)-s),this._start(t,this.toSeconds(n.offset)+s,i)}}},this._syncedStop=t=>{const e=this.context.transport.getSecondsAtTime(Math.max(t-this.sampleTime,0));"started"===this._state.getValueAtTime(e)&&this._stop(t)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(t=>this.context.transport.clear(t)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=Ba,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class Fc extends vc{constructor(){super(va(Fc.getDefaults(),arguments,["url","onload"])),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1;const t=va(Fc.getDefaults(),arguments,["url","onload"]);mc(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new pc({context:this.context,param:this._source.playbackRate,units:"positive",value:t.playbackRate}),this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this._buffer=new Ua(t.url,t.onload,t.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(vc.getDefaults(),{url:new Ua,loop:!1,loopEnd:0,loopStart:0,onload:Ba,onerror:Ba,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t}get curve(){return this._curve}set curve(t){this._curve=t}start(t,e,n,s=1){Wo(this.buffer.loaded,"buffer is either not set or not loaded");const i=this.toSeconds(t);this._startGain(i,s),e=this.loop?wa(e,this.loopStart):wa(e,0);let r=Math.max(this.toSeconds(e),0);if(this.loop){const t=this.toSeconds(this.loopEnd)||this.buffer.duration,e=this.toSeconds(this.loopStart),n=t-e;Aa(r,t)&&(r=(r-e)%n+e),ka(r,this.buffer.duration)&&(r=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,Sa(r,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(i,r)),Zo(n)){let t=this.toSeconds(n);t=Math.max(t,0),this.stop(i+t)}return this}_stopSource(t){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(t)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(t){this._source.loopStart=this.toSeconds(t)}get loopEnd(){return this._source.loopEnd}set loopEnd(t){this._source.loopEnd=this.toSeconds(t)}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._source.loop}set loop(t){this._source.loop=t,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}function jc(t,e){return ca(this,void 0,void 0,(function*(){const n=e/t.context.sampleRate,s=new za(1,n,t.context.sampleRate),i=new t.constructor(Object.assign(t.get(),{frequency:2/n,detune:0,context:s})).toDestination();i.start(0);const r=yield s.render();return r.getChannelData(0)}))}class Lc extends vc{constructor(){super(va(Lc.getDefaults(),arguments,["frequency","type"])),this.name="ToneOscillatorNode",this._oscillator=this.context.createOscillator(),this._internalChannels=[this._oscillator];const t=va(Lc.getDefaults(),arguments,["frequency","type"]);mc(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new pc({context:this.context,param:this._oscillator.frequency,units:"frequency",value:t.frequency}),this.detune=new pc({context:this.context,param:this._oscillator.detune,units:"cents",value:t.detune}),La(this,["frequency","detune"])}static getDefaults(){return Object.assign(vc.getDefaults(),{detune:0,frequency:440,type:"sine"})}start(t){const e=this.toSeconds(t);return this.log("start",e),this._startGain(e),this._oscillator.start(e),this}_stopSource(t){this._oscillator.stop(t)}setPeriodicWave(t){return this._oscillator.setPeriodicWave(t),this}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._oscillator.disconnect(),this.frequency.dispose(),this.detune.dispose(),this}}class Wc extends qc{constructor(){super(va(Wc.getDefaults(),arguments,["frequency","type"])),this.name="Oscillator",this._oscillator=null;const t=va(Wc.getDefaults(),arguments,["frequency","type"]);this.frequency=new wc({context:this.context,units:"frequency",value:t.frequency}),La(this,"frequency"),this.detune=new wc({context:this.context,units:"cents",value:t.detune}),La(this,"detune"),this._partials=t.partials,this._partialCount=t.partialCount,this._type=t.type,t.partialCount&&"custom"!==t.type&&(this._type=this.baseType+t.partialCount.toString()),this.phase=t.phase}static getDefaults(){return Object.assign(qc.getDefaults(),{detune:0,frequency:440,partialCount:0,partials:[],phase:0,type:"sine"})}_start(t){const e=this.toSeconds(t),n=new Lc({context:this.context,onended:()=>this.onstop(this)});this._oscillator=n,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(e)}_stop(t){const e=this.toSeconds(t);this._oscillator&&this._oscillator.stop(e)}_restart(t){const e=this.toSeconds(t);return this.log("restart",e),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(e),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if("custom"===this._type){const t=Wc._periodicWaveCache.find(t=>t.phase===this._phase&&ga(t.partials,this._partials));return t}{const t=Wc._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=t?t.partialCount:this._partialCount,t}}get type(){return this._type}set type(t){this._type=t;const e=-1!==["sine","square","sawtooth","triangle"].indexOf(t);if(0===this._phase&&e)this._wave=void 0,this._partialCount=0,null!==this._oscillator&&(this._oscillator.type=t);else{const e=this._getCachedPeriodicWave();if(Zo(e)){const{partials:t,wave:n}=e;this._wave=n,this._partials=t,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave)}else{const[e,n]=this._getRealImaginary(t,this._phase),s=this.context.createPeriodicWave(e,n);this._wave=s,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave),Wc._periodicWaveCache.push({imag:n,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:e,type:this._type,wave:this._wave}),Wc._periodicWaveCache.length>100&&Wc._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(t){this.partialCount&&"custom"!==this._type&&"custom"!==t?this.type=t+this.partialCount:this.type=t}get partialCount(){return this._partialCount}set partialCount(t){Bo(t,0);let e=this._type;const n=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(n&&(e=n[1]),"custom"!==this._type)this.type=0===t?e:e+t.toString();else{const e=new Float32Array(t);this._partials.forEach((t,n)=>e[n]=t),this._partials=Array.from(e),this.type=this._type}}_getRealImaginary(t,e){const n=4096;let s=n/2;const i=new Float32Array(s),r=new Float32Array(s);let o=1;if("custom"===t){if(o=this._partials.length+1,this._partialCount=this._partials.length,s=o,0===this._partials.length)return[i,r]}else{const e=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(t);e?(o=parseInt(e[2],10)+1,this._partialCount=parseInt(e[2],10),t=e[1],o=Math.max(o,2),s=o):this._partialCount=0,this._partials=[]}for(let a=1;a>1&1?-1:1):0,this._partials[a-1]=s;break;case"custom":s=this._partials[a-1];break;default:throw new TypeError("Oscillator: invalid type: "+t)}0!==s?(i[a]=-s*Math.sin(e*a),r[a]=s*Math.cos(e*a)):(i[a]=0,r[a]=0)}return[i,r]}_inverseFFT(t,e,n){let s=0;const i=t.length;for(let r=0;re.includes(t));Wo(e,"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class zc extends Bc{constructor(){super(...arguments),this.name="AudioToGain",this._norm=new Uc({context:this.context,mapping:t=>(t+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Gc extends wc{constructor(){super(Object.assign(va(Gc.getDefaults(),arguments,["value"]))),this.name="Multiply",this.override=!1;const t=va(Gc.getDefaults(),arguments,["value"]);this._mult=this.input=this.output=new gc({context:this.context,minValue:t.minValue,maxValue:t.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(wc.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class Xc extends qc{constructor(){super(va(Xc.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="AMOscillator",this._modulationScale=new zc({context:this.context}),this._modulationNode=new gc({context:this.context});const t=va(Xc.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new Wc({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new Wc({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new Gc({context:this.context,units:"positive",value:t.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),La(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(Wc.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){this._modulator.restart(t),this._carrier.restart(t)}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return ca(this,void 0,void 0,(function*(){return jc(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class Yc extends qc{constructor(){super(va(Yc.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="FMOscillator",this._modulationNode=new gc({context:this.context,gain:0});const t=va(Yc.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new Wc({context:this.context,detune:t.detune,frequency:0,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.detune=this._carrier.detune,this.frequency=new wc({context:this.context,units:"frequency",value:t.frequency}),this._modulator=new Wc({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new Gc({context:this.context,units:"positive",value:t.harmonicity}),this.modulationIndex=new Gc({context:this.context,units:"positive",value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),La(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(Wc.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){return this._modulator.restart(t),this._carrier.restart(t),this}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return ca(this,void 0,void 0,(function*(){return jc(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class Zc extends qc{constructor(){super(va(Zc.getDefaults(),arguments,["frequency","width"])),this.name="PulseOscillator",this._widthGate=new gc({context:this.context,gain:0}),this._thresh=new Uc({context:this.context,mapping:t=>t<=0?-1:1});const t=va(Zc.getDefaults(),arguments,["frequency","width"]);this.width=new wc({context:this.context,units:"audioRange",value:t.width}),this._triangle=new Wc({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),La(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(qc.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(t){t=this.toSeconds(t),this._triangle.start(t),this._widthGate.gain.setValueAtTime(1,t)}_stop(t){t=this.toSeconds(t),this._triangle.stop(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(0,t)}_restart(t){this._triangle.restart(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(1,t)}get phase(){return this._triangle.phase}set phase(t){this._triangle.phase=t}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(t){this._triangle.type=t}asArray(t=1024){return ca(this,void 0,void 0,(function*(){return jc(this,t)}))}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class Hc extends qc{constructor(){super(va(Hc.getDefaults(),arguments,["frequency","type","spread"])),this.name="FatOscillator",this._oscillators=[];const t=va(Hc.getDefaults(),arguments,["frequency","type","spread"]);this.frequency=new wc({context:this.context,units:"frequency",value:t.frequency}),this.detune=new wc({context:this.context,units:"cents",value:t.detune}),this._spread=t.spread,this._type=t.type,this._phase=t.phase,this._partials=t.partials,this._partialCount=t.partialCount,this.count=t.count,La(this,["frequency","detune"])}static getDefaults(){return Object.assign(Wc.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(t){t=this.toSeconds(t),this._forEach(e=>e.start(t))}_stop(t){t=this.toSeconds(t),this._forEach(e=>e.stop(t))}_restart(t){this._forEach(e=>e.restart(t))}_forEach(t){for(let e=0;ee.type=t)}get spread(){return this._spread}set spread(t){if(this._spread=t,this._oscillators.length>1){const e=-t/2,n=t/(this._oscillators.length-1);this._forEach((t,s)=>t.detune.value=e+n*s)}}get count(){return this._oscillators.length}set count(t){if(Bo(t,1),this._oscillators.length!==t){this._forEach(t=>t.dispose()),this._oscillators=[];for(let e=0;ethis.onstop(this):Ba});"custom"===this.type&&(n.partials=this._partials),this.frequency.connect(n.frequency),this.detune.connect(n.detune),n.detune.overridden=!1,n.connect(this.output),this._oscillators[e]=n}this.spread=this._spread,"started"===this.state&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(t){this._phase=t,this._forEach((t,e)=>t.phase=this._phase+e/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(t){this._forEach(e=>e.baseType=t),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(t){this._partials=t,this._partialCount=this._partials.length,t.length&&(this._type="custom",this._forEach(e=>e.partials=t))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(t){this._partialCount=t,this._forEach(e=>e.partialCount=t),this._type=this._oscillators[0].type}asArray(t=1024){return ca(this,void 0,void 0,(function*(){return jc(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(t=>t.dispose()),this}}class $c extends qc{constructor(){super(va($c.getDefaults(),arguments,["frequency","modulationFrequency"])),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new Gc({context:this.context,value:2});const t=va($c.getDefaults(),arguments,["frequency","modulationFrequency"]);this._pulse=new Zc({context:this.context,frequency:t.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new Wc({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),La(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(qc.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(t){t=this.toSeconds(t),this._modulator.start(t),this._pulse.start(t)}_stop(t){t=this.toSeconds(t),this._modulator.stop(t),this._pulse.stop(t)}_restart(t){this._modulator.restart(t),this._pulse.restart(t)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(t){this._modulator.phase=t}asArray(t=1024){return ca(this,void 0,void 0,(function*(){return jc(this,t)}))}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const Qc={am:Xc,fat:Hc,fm:Yc,oscillator:Wc,pulse:Zc,pwm:$c};class Jc extends qc{constructor(){super(va(Jc.getDefaults(),arguments,["frequency","type"])),this.name="OmniOscillator";const t=va(Jc.getDefaults(),arguments,["frequency","type"]);this.frequency=new wc({context:this.context,units:"frequency",value:t.frequency}),this.detune=new wc({context:this.context,units:"cents",value:t.detune}),La(this,["frequency","detune"]),this.set(t)}static getDefaults(){return Object.assign(Wc.getDefaults(),Yc.getDefaults(),Xc.getDefaults(),Hc.getDefaults(),Zc.getDefaults(),$c.getDefaults())}_start(t){this._oscillator.start(t)}_stop(t){this._oscillator.stop(t)}_restart(t){return this._oscillator.restart(t),this}get type(){let t="";return["am","fm","fat"].some(t=>this._sourceType===t)&&(t=this._sourceType),t+this._oscillator.type}set type(t){"fm"===t.substr(0,2)?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"am"===t.substr(0,2)?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"fat"===t.substr(0,3)?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(3)):"pwm"===t?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):"pulse"===t?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=t)}get partials(){return this._oscillator.partials}set partials(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partials=t)}get partialCount(){return this._oscillator.partialCount}set partialCount(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partialCount=t)}set(t){return Reflect.has(t,"type")&&t.type&&(this.type=t.type),super.set(t),this}_createNewOscillator(t){if(t!==this._sourceType){this._sourceType=t;const e=Qc[t],n=this.now();if(this._oscillator){const t=this._oscillator;t.stop(n),this.context.setTimeout(()=>t.dispose(),this.blockTime)}this._oscillator=new e({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),"started"===this.state&&this._oscillator.start(n)}}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t}get sourceType(){return this._sourceType}set sourceType(t){let e="sine";"pwm"!==this._oscillator.type&&"pulse"!==this._oscillator.type&&(e=this._oscillator.type),"fm"===t?this.type="fm"+e:"am"===t?this.type="am"+e:"fat"===t?this.type="fat"+e:"oscillator"===t?this.type=e:"pulse"===t?this.type="pulse":"pwm"===t&&(this.type="pwm")}_getOscType(t,e){return t instanceof Qc[e]}get baseType(){return this._oscillator.baseType}set baseType(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||"pulse"===t||"pwm"===t||(this._oscillator.baseType=t)}get width(){return this._getOscType(this._oscillator,"pulse")?this._oscillator.width:void 0}get count(){return this._getOscType(this._oscillator,"fat")?this._oscillator.count:void 0}set count(t){this._getOscType(this._oscillator,"fat")&&$o(t)&&(this._oscillator.count=t)}get spread(){return this._getOscType(this._oscillator,"fat")?this._oscillator.spread:void 0}set spread(t){this._getOscType(this._oscillator,"fat")&&$o(t)&&(this._oscillator.spread=t)}get modulationType(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.modulationType:void 0}set modulationType(t){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&ta(t)&&(this._oscillator.modulationType=t)}get modulationIndex(){return this._getOscType(this._oscillator,"fm")?this._oscillator.modulationIndex:void 0}get harmonicity(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.harmonicity:void 0}get modulationFrequency(){return this._getOscType(this._oscillator,"pwm")?this._oscillator.modulationFrequency:void 0}asArray(t=1024){return ca(this,void 0,void 0,(function*(){return jc(this,t)}))}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}function Kc(t,e=1/0){const n=new WeakMap;return function(s,i){Reflect.defineProperty(s,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){Bo(s,t,e),n.set(this,s)}})}}function tu(t,e=1/0){const n=new WeakMap;return function(s,i){Reflect.defineProperty(s,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){Bo(this.toSeconds(s),t,e),n.set(this,s)}})}}class eu extends qc{constructor(){super(va(eu.getDefaults(),arguments,["url","onload"])),this.name="Player",this._activeSources=new Set;const t=va(eu.getDefaults(),arguments,["url","onload"]);this._buffer=new Ua({onload:this._onload.bind(this,t.onload),onerror:t.onerror,reverse:t.reverse,url:t.url}),this.autostart=t.autostart,this._loop=t.loop,this._loopStart=t.loopStart,this._loopEnd=t.loopEnd,this._playbackRate=t.playbackRate,this.fadeIn=t.fadeIn,this.fadeOut=t.fadeOut}static getDefaults(){return Object.assign(qc.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:Ba,onerror:Ba,playbackRate:1,reverse:!1})}load(t){return ca(this,void 0,void 0,(function*(){return yield this._buffer.load(t),this._onload(),this}))}_onload(t=Ba){t(),this.autostart&&this.start()}_onSourceEnd(t){this.onstop(this),this._activeSources.delete(t),0!==this._activeSources.size||this._synced||"started"!==this._state.getValueAtTime(this.now())||(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(t,e,n){return super.start(t,e,n),this}_start(t,e,n){e=this._loop?wa(e,this._loopStart):wa(e,0);const s=this.toSeconds(e),i=n;n=wa(n,Math.max(this._buffer.duration-s,0));let r=this.toSeconds(n);r/=this._playbackRate,t=this.toSeconds(t);const o=new Fc({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);this._loop||this._synced||(this._state.cancel(t+r),this._state.setStateAtTime("stopped",t+r,{implicitEnd:!0})),this._activeSources.add(o),this._loop&&Yo(i)?o.start(t,s):o.start(t,s,r-this.toSeconds(this.fadeOut))}_stop(t){const e=this.toSeconds(t);this._activeSources.forEach(t=>t.stop(e))}restart(t,e,n){return super.restart(t,e,n),this}_restart(t,e,n){this._stop(t),this._start(t,e,n)}seek(t,e){const n=this.toSeconds(e);if("started"===this._state.getValueAtTime(n)){const e=this.toSeconds(t);this._stop(n),this._start(n,e)}return this}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this.buffer.loaded&&Bo(this.toSeconds(t),0,this.buffer.duration),this._activeSources.forEach(e=>{e.loopStart=t})}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this.buffer.loaded&&Bo(this.toSeconds(t),0,this.buffer.duration),this._activeSources.forEach(e=>{e.loopEnd=t})}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._loop}set loop(t){if(this._loop!==t&&(this._loop=t,this._activeSources.forEach(e=>{e.loop=t}),t)){const t=this._state.getNextState("stopped",this.now());t&&this._state.cancel(t.time)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t;const e=this.now(),n=this._state.getNextState("stopped",e);n&&n.implicitEnd&&(this._state.cancel(n.time),this._activeSources.forEach(t=>t.cancelStop())),this._activeSources.forEach(n=>{n.playbackRate.setValueAtTime(t,e)})}get reverse(){return this._buffer.reverse}set reverse(t){this._buffer.reverse=t}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(t=>t.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}aa([tu(0)],eu.prototype,"fadeIn",void 0),aa([tu(0)],eu.prototype,"fadeOut",void 0);class nu extends dc{constructor(){super(va(nu.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="Envelope",this._sig=new wc({context:this.context,value:0}),this.output=this._sig,this.input=void 0;const t=va(nu.getDefaults(),arguments,["attack","decay","sustain","release"]);this.attack=t.attack,this.decay=t.decay,this.sustain=t.sustain,this.release=t.release,this.attackCurve=t.attackCurve,this.releaseCurve=t.releaseCurve,this.decayCurve=t.decayCurve}static getDefaults(){return Object.assign(dc.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(t,e){if(ta(t))return t;{let n;for(n in su)if(su[n][e]===t)return n;return t}}_setCurve(t,e,n){if(ta(n)&&Reflect.has(su,n)){const s=su[n];Qo(s)?"_decayCurve"!==t&&(this[t]=s[e]):this[t]=s}else{if(!Ko(n)||"_decayCurve"===t)throw new Error("Envelope: invalid curve: "+n);this[t]=n}}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(t){this._setCurve("_attackCurve","In",t)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(t){this._setCurve("_releaseCurve","Out",t)}get decayCurve(){return this._decayCurve}set decayCurve(t){Wo(["linear","exponential"].some(e=>e===t),"Invalid envelope curve: "+t),this._decayCurve=t}triggerAttack(t,e=1){this.log("triggerAttack",t,e),t=this.toSeconds(t);const n=this.toSeconds(this.attack);let s=n;const i=this.toSeconds(this.decay),r=this.getValueAtTime(t);if(r>0){const t=1/s,e=1-r;s=e/t}if(s0){const n=this.toSeconds(this.release);n{const t=128;let e,n;const s=[];for(e=0;e{const s=t[e],i=this.context.transport.schedule(s=>{t[e]=s,n.apply(this,t)},s);this._scheduledEvents.push(i)}}unsync(){return this._scheduledEvents.forEach(t=>this.context.transport.clear(t)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease),this}triggerAttackRelease(t,e,n,s){const i=this.toSeconds(n),r=this.toSeconds(e);return this.triggerAttack(t,i,s),this.triggerRelease(i+r),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class ru extends iu{constructor(){super(va(ru.getDefaults(),arguments));const t=va(ru.getDefaults(),arguments);this.portamento=t.portamento,this.onsilence=t.onsilence}static getDefaults(){return Object.assign(iu.getDefaults(),{detune:0,onsilence:Ba,portamento:0})}triggerAttack(t,e,n=1){this.log("triggerAttack",t,e,n);const s=this.toSeconds(e);return this._triggerEnvelopeAttack(s,n),this.setNote(t,s),this}triggerRelease(t){this.log("triggerRelease",t);const e=this.toSeconds(t);return this._triggerEnvelopeRelease(e),this}setNote(t,e){const n=this.toSeconds(e),s=t instanceof oc?t.toFrequency():t;if(this.portamento>0&&this.getLevelAtTime(n)>.05){const t=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(s,t,n)}else this.frequency.setValueAtTime(s,n);return this}}aa([tu(0)],ru.prototype,"portamento",void 0);class ou extends nu{constructor(){super(va(ou.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new gc({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class au extends ru{constructor(){super(va(au.getDefaults(),arguments)),this.name="Synth";const t=va(au.getDefaults(),arguments);this.oscillator=new Jc(Object.assign({context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)},t.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new ou(Object.assign({context:this.context},t.envelope)),this.oscillator.chain(this.envelope,this.output),La(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(ru.getDefaults(),{envelope:Object.assign(xa(nu.getDefaults(),Object.keys(dc.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(xa(Jc.getDefaults(),[...Object.keys(qc.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(t,e){if(this.envelope.triggerAttack(t,e),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),n=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+n)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class cu extends au{constructor(){super(va(cu.getDefaults(),arguments)),this.name="MembraneSynth",this.portamento=0;const t=va(cu.getDefaults(),arguments);this.pitchDecay=t.pitchDecay,this.octaves=t.octaves,La(this,["oscillator","envelope"])}static getDefaults(){return _a(ru.getDefaults(),au.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(t,e){const n=this.toSeconds(e),s=this.toFrequency(t instanceof oc?t.toFrequency():t),i=s*this.octaves;return this.oscillator.frequency.setValueAtTime(i,n),this.oscillator.frequency.exponentialRampToValueAtTime(s,n+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}aa([Kc(0)],cu.prototype,"octaves",void 0),aa([tu(0)],cu.prototype,"pitchDecay",void 0);const uu=new Set;function lu(t){uu.add(t)}function hu(t,e){const n=`registerProcessor("${t}", ${e})`;uu.add(n)}const pu='\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the [[ToneAudioWorklet]]. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it\'s disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === "dispose") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n';lu(pu);const du="\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n";lu(du);const fu="\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n";lu(fu);const mu="feedback-comb-filter",_u='\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: "delayTime",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}, {\n\t\t\t\tname: "feedback",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n';hu(mu,_u);class gu extends iu{constructor(){super(va(gu.getDefaults(),arguments,["urls","onload","baseUrl"],"urls")),this.name="Sampler",this._activeSources=new Map;const t=va(gu.getDefaults(),arguments,["urls","onload","baseUrl"],"urls"),e={};Object.keys(t.urls).forEach(n=>{const s=parseInt(n,10);if(Wo(ea(n)||$o(s)&&isFinite(s),"url key is neither a note or midi pitch: "+n),ea(n)){const s=new oc(this.context,n).toMidi();e[s]=t.urls[n]}else $o(s)&&isFinite(s)&&(e[s]=t.urls[s])}),this._buffers=new Sc({urls:e,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.attack=t.attack,this.release=t.release,this.curve=t.curve,this._buffers.loaded&&Promise.resolve().then(t.onload)}static getDefaults(){return Object.assign(iu.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:Ba,onerror:Ba,release:.1,urls:{}})}_findClosest(t){const e=96;let n=0;while(n{const s=nc(new oc(this.context,t).toFrequency()),i=Math.round(s),r=s-i,o=this._findClosest(i),a=i-o,c=this._buffers.get(a),u=Qa(o+r),l=new Fc({url:c,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:u}).connect(this.output);l.start(e,0,c.duration/u,n),Ko(this._activeSources.get(i))||this._activeSources.set(i,[]),this._activeSources.get(i).push(l),l.onended=()=>{if(this._activeSources&&this._activeSources.has(i)){const t=this._activeSources.get(i),e=t.indexOf(l);-1!==e&&t.splice(e,1)}}}),this}triggerRelease(t,e){return this.log("triggerRelease",t,e),Array.isArray(t)||(t=[t]),t.forEach(t=>{const n=new oc(this.context,t).toMidi();if(this._activeSources.has(n)&&this._activeSources.get(n).length){const t=this._activeSources.get(n);e=this.toSeconds(e),t.forEach(t=>{t.stop(e)}),this._activeSources.set(n,[])}}),this}releaseAll(t){const e=this.toSeconds(t);return this._activeSources.forEach(t=>{while(t.length){const n=t.shift();n.stop(e)}}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(t,e,n,s=1){const i=this.toSeconds(n);return this.triggerAttack(t,i,s),Ko(e)?(Wo(Ko(t),"notes must be an array when duration is array"),t.forEach((t,n)=>{const s=e[Math.min(n,e.length-1)];this.triggerRelease(t,i+this.toSeconds(s))})):this.triggerRelease(t,i+this.toSeconds(e)),this}add(t,e,n){if(Wo(ea(t)||isFinite(t),"note must be a pitch or midi: "+t),ea(t)){const s=new oc(this.context,t).toMidi();this._buffers.add(s,e,n)}else this._buffers.add(t,e,n);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(t=>{t.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}aa([tu(0)],gu.prototype,"attack",void 0),aa([tu(0)],gu.prototype,"release",void 0);class vu extends dc{constructor(){super(Object.assign(va(vu.getDefaults(),arguments,["pan"]))),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner;const t=va(vu.getDefaults(),arguments,["pan"]);this.pan=new pc({context:this.context,param:this._panner.pan,value:t.pan,minValue:-1,maxValue:1}),this._panner.channelCount=t.channelCount,this._panner.channelCountMode="explicit",La(this,"pan")}static getDefaults(){return Object.assign(dc.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}const yu="bit-crusher",wu="\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n";hu(yu,wu);class xu extends dc{constructor(){super(va(xu.getDefaults(),arguments,["solo"])),this.name="Solo";const t=va(xu.getDefaults(),arguments,["solo"]);this.input=this.output=new gc({context:this.context}),xu._allSolos.has(this.context)||xu._allSolos.set(this.context,new Set),xu._allSolos.get(this.context).add(this),this.solo=t.solo}static getDefaults(){return Object.assign(dc.getDefaults(),{solo:!1})}get solo(){return this._isSoloed()}set solo(t){t?this._addSolo():this._removeSolo(),xu._allSolos.get(this.context).forEach(t=>t._updateSolo())}get muted(){return 0===this.input.gain.value}_addSolo(){xu._soloed.has(this.context)||xu._soloed.set(this.context,new Set),xu._soloed.get(this.context).add(this)}_removeSolo(){xu._soloed.has(this.context)&&xu._soloed.get(this.context).delete(this)}_isSoloed(){return xu._soloed.has(this.context)&&xu._soloed.get(this.context).has(this)}_noSolos(){return!xu._soloed.has(this.context)||xu._soloed.has(this.context)&&0===xu._soloed.get(this.context).size}_updateSolo(){this._isSoloed()||this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),xu._allSolos.get(this.context).delete(this),this._removeSolo(),this}}xu._allSolos=new Map,xu._soloed=new Map;class Tu extends dc{constructor(){super(va(Tu.getDefaults(),arguments,["pan","volume"])),this.name="PanVol";const t=va(Tu.getDefaults(),arguments,["pan","volume"]);this._panner=this.input=new vu({context:this.context,pan:t.pan,channelCount:t.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Dc({context:this.context,volume:t.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=t.mute,La(this,["pan","volume"])}static getDefaults(){return Object.assign(dc.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class bu extends dc{constructor(){super(va(bu.getDefaults(),arguments,["volume","pan"])),this.name="Channel";const t=va(bu.getDefaults(),arguments,["volume","pan"]);this._solo=this.input=new xu({solo:t.solo,context:this.context}),this._panVol=this.output=new Tu({context:this.context,pan:t.pan,volume:t.volume,mute:t.mute,channelCount:t.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),La(this,["pan","volume"])}static getDefaults(){return Object.assign(dc.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(t){this._solo.solo=t}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(t){this._panVol.mute=t}_getBus(t){return bu.buses.has(t)||bu.buses.set(t,new gc({context:this.context})),bu.buses.get(t)}send(t,e=0){const n=this._getBus(t),s=new gc({context:this.context,units:"decibels",gain:e});return this.connect(s),s.connect(n),s}receive(t){const e=this._getBus(t);return e.connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}bu.buses=new Map;class Cu extends dc{constructor(){super(...arguments),this.name="Listener",this.positionX=new pc({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new pc({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new pc({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new pc({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new pc({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new pc({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new pc({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new pc({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new pc({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(dc.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}Da(t=>{t.listener=new Cu({context:t})}),Na(t=>{t.listener.dispose()});Ya().transport;Ya().destination,Ya().destination;Ya().listener;Ya().draw;Ya();var Au={name:"Synth",props:{oscillator:{type:String,default:"fmsine"},volume:{type:Number,default:-6},attack:{type:Number,default:.05},decay:{type:Number,default:.1},sustain:{type:Number,default:.5},release:{type:Number,default:.1},frequency:{type:[Number,String],required:!0},duration:{type:Number,default:1/0}},data(){return{synth:new au({oscillator:{type:this.oscillator,volume:this.volume},envelope:{attack:this.attack,decay:this.decay,sustain:this.sustain,release:this.release}}).toDestination()}},async mounted(){const t=await this.synth;this.duration!==1/0?t.triggerAttackRelease(this.frequency,this.duration):t.triggerAttack(this.frequency,t.now())},async destroyed(){const t=await this.synth;t.triggerRelease(t.now())}},Su=Au,ku=n("2877"),Ou=n("eec0"),Mu=n.n(Ou),Eu=Object(ku["a"])(Su,s,i,!1,null,"7592e858",null);"function"===typeof Mu.a&&Mu()(Eu);e["default"]=Eu.exports},"5a43":function(t,e){function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,s=new Array(e);n= eventTime;\n }\n\n return getEventTime(currentAutomationEvent) >= eventTime;\n });\n\n var removedAutomationEvent = this._automationEvents[index];\n\n if (index !== -1) {\n this._automationEvents = this._automationEvents.slice(0, index);\n }\n\n if (isCancelAndHoldAutomationEvent(automationEvent)) {\n var lastAutomationEvent = this._automationEvents[this._automationEvents.length - 1];\n\n if (removedAutomationEvent !== undefined && isAnyRampToValueAutomationEvent(removedAutomationEvent)) {\n if (isSetTargetAutomationEvent(lastAutomationEvent)) {\n throw new Error('The internal list is malformed.');\n }\n\n var startTime = isSetValueCurveAutomationEvent(lastAutomationEvent) ? lastAutomationEvent.startTime + lastAutomationEvent.duration : getEventTime(lastAutomationEvent);\n var startValue = isSetValueCurveAutomationEvent(lastAutomationEvent) ? lastAutomationEvent.values[lastAutomationEvent.values.length - 1] : lastAutomationEvent.value;\n var value = isExponentialRampToValueAutomationEvent(removedAutomationEvent) ? getExponentialRampValueAtTime(eventTime, startTime, startValue, removedAutomationEvent) : getLinearRampValueAtTime(eventTime, startTime, startValue, removedAutomationEvent);\n var truncatedAutomationEvent = isExponentialRampToValueAutomationEvent(removedAutomationEvent) ? createExtendedExponentialRampToValueAutomationEvent(value, eventTime, this._currenTime) : createExtendedLinearRampToValueAutomationEvent(value, eventTime, this._currenTime);\n\n this._automationEvents.push(truncatedAutomationEvent);\n }\n\n if (lastAutomationEvent !== undefined && isSetTargetAutomationEvent(lastAutomationEvent)) {\n this._automationEvents.push(createSetValueAutomationEvent(this.getValue(eventTime), eventTime));\n }\n\n if (lastAutomationEvent !== undefined && isSetValueCurveAutomationEvent(lastAutomationEvent) && lastAutomationEvent.startTime + lastAutomationEvent.duration > eventTime) {\n this._automationEvents[this._automationEvents.length - 1] = createSetValueCurveAutomationEvent(new Float32Array([6, 7]), lastAutomationEvent.startTime, eventTime - lastAutomationEvent.startTime);\n }\n }\n } else {\n var _index = this._automationEvents.findIndex(function (currentAutomationEvent) {\n return getEventTime(currentAutomationEvent) > eventTime;\n });\n\n var previousAutomationEvent = _index === -1 ? this._automationEvents[this._automationEvents.length - 1] : this._automationEvents[_index - 1];\n\n if (previousAutomationEvent !== undefined && isSetValueCurveAutomationEvent(previousAutomationEvent) && getEventTime(previousAutomationEvent) + previousAutomationEvent.duration > eventTime) {\n return false;\n }\n\n var persistentAutomationEvent = isExponentialRampToValueAutomationEvent(automationEvent) ? createExtendedExponentialRampToValueAutomationEvent(automationEvent.value, automationEvent.endTime, this._currenTime) : isLinearRampToValueAutomationEvent(automationEvent) ? createExtendedLinearRampToValueAutomationEvent(automationEvent.value, eventTime, this._currenTime) : automationEvent;\n\n if (_index === -1) {\n this._automationEvents.push(persistentAutomationEvent);\n } else {\n if (isSetValueCurveAutomationEvent(automationEvent) && eventTime + automationEvent.duration > getEventTime(this._automationEvents[_index])) {\n return false;\n }\n\n this._automationEvents.splice(_index, 0, persistentAutomationEvent);\n }\n }\n\n return true;\n }\n }, {\n key: \"flush\",\n value: function flush(time) {\n var index = this._automationEvents.findIndex(function (currentAutomationEvent) {\n return getEventTime(currentAutomationEvent) > time;\n });\n\n if (index > 1) {\n var remainingAutomationEvents = this._automationEvents.slice(index - 1);\n\n var firstRemainingAutomationEvent = remainingAutomationEvents[0];\n\n if (isSetTargetAutomationEvent(firstRemainingAutomationEvent)) {\n remainingAutomationEvents.unshift(createSetValueAutomationEvent(getValueOfAutomationEventAtIndexAtTime(this._automationEvents, index - 2, firstRemainingAutomationEvent.startTime, this._defaultValue), firstRemainingAutomationEvent.startTime));\n }\n\n this._automationEvents = remainingAutomationEvents;\n }\n }\n }, {\n key: \"getValue\",\n value: function getValue(time) {\n if (this._automationEvents.length === 0) {\n return this._defaultValue;\n }\n\n var indexOfNextEvent = this._automationEvents.findIndex(function (automationEvent) {\n return getEventTime(automationEvent) > time;\n });\n\n var nextAutomationEvent = this._automationEvents[indexOfNextEvent];\n var indexOfCurrentEvent = (indexOfNextEvent === -1 ? this._automationEvents.length : indexOfNextEvent) - 1;\n var currentAutomationEvent = this._automationEvents[indexOfCurrentEvent];\n\n if (currentAutomationEvent !== undefined && isSetTargetAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent) || nextAutomationEvent.insertTime > time)) {\n return getTargetValueAtTime(time, getValueOfAutomationEventAtIndexAtTime(this._automationEvents, indexOfCurrentEvent - 1, currentAutomationEvent.startTime, this._defaultValue), currentAutomationEvent);\n }\n\n if (currentAutomationEvent !== undefined && isSetValueAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent))) {\n return currentAutomationEvent.value;\n }\n\n if (currentAutomationEvent !== undefined && isSetValueCurveAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent) || currentAutomationEvent.startTime + currentAutomationEvent.duration > time)) {\n if (time < currentAutomationEvent.startTime + currentAutomationEvent.duration) {\n return getValueCurveValueAtTime(time, currentAutomationEvent);\n }\n\n return currentAutomationEvent.values[currentAutomationEvent.values.length - 1];\n }\n\n if (currentAutomationEvent !== undefined && isAnyRampToValueAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === undefined || !isAnyRampToValueAutomationEvent(nextAutomationEvent))) {\n return currentAutomationEvent.value;\n }\n\n if (nextAutomationEvent !== undefined && isExponentialRampToValueAutomationEvent(nextAutomationEvent)) {\n var _getEndTimeAndValueOf = getEndTimeAndValueOfPreviousAutomationEvent(this._automationEvents, indexOfCurrentEvent, currentAutomationEvent, nextAutomationEvent, this._defaultValue),\n _getEndTimeAndValueOf2 = _slicedToArray__default[\"default\"](_getEndTimeAndValueOf, 2),\n startTime = _getEndTimeAndValueOf2[0],\n value = _getEndTimeAndValueOf2[1];\n\n return getExponentialRampValueAtTime(time, startTime, value, nextAutomationEvent);\n }\n\n if (nextAutomationEvent !== undefined && isLinearRampToValueAutomationEvent(nextAutomationEvent)) {\n var _getEndTimeAndValueOf3 = getEndTimeAndValueOfPreviousAutomationEvent(this._automationEvents, indexOfCurrentEvent, currentAutomationEvent, nextAutomationEvent, this._defaultValue),\n _getEndTimeAndValueOf4 = _slicedToArray__default[\"default\"](_getEndTimeAndValueOf3, 2),\n _startTime = _getEndTimeAndValueOf4[0],\n _value = _getEndTimeAndValueOf4[1];\n\n return getLinearRampValueAtTime(time, _startTime, _value, nextAutomationEvent);\n }\n\n return this._defaultValue;\n }\n }]);\n\n return AutomationEventList;\n }(Symbol.iterator);\n\n var createCancelAndHoldAutomationEvent = function createCancelAndHoldAutomationEvent(cancelTime) {\n return {\n cancelTime: cancelTime,\n type: 'cancelAndHold'\n };\n };\n\n var createCancelScheduledValuesAutomationEvent = function createCancelScheduledValuesAutomationEvent(cancelTime) {\n return {\n cancelTime: cancelTime,\n type: 'cancelScheduledValues'\n };\n };\n\n var createExponentialRampToValueAutomationEvent = function createExponentialRampToValueAutomationEvent(value, endTime) {\n return {\n endTime: endTime,\n type: 'exponentialRampToValue',\n value: value\n };\n };\n\n var createLinearRampToValueAutomationEvent = function createLinearRampToValueAutomationEvent(value, endTime) {\n return {\n endTime: endTime,\n type: 'linearRampToValue',\n value: value\n };\n };\n\n var createSetTargetAutomationEvent = function createSetTargetAutomationEvent(target, startTime, timeConstant) {\n return {\n startTime: startTime,\n target: target,\n timeConstant: timeConstant,\n type: 'setTarget'\n };\n };\n\n exports.AutomationEventList = AutomationEventList;\n exports.createCancelAndHoldAutomationEvent = createCancelAndHoldAutomationEvent;\n exports.createCancelScheduledValuesAutomationEvent = createCancelScheduledValuesAutomationEvent;\n exports.createExponentialRampToValueAutomationEvent = createExponentialRampToValueAutomationEvent;\n exports.createLinearRampToValueAutomationEvent = createLinearRampToValueAutomationEvent;\n exports.createSetTargetAutomationEvent = createSetTargetAutomationEvent;\n exports.createSetValueAutomationEvent = createSetValueAutomationEvent;\n exports.createSetValueCurveAutomationEvent = createSetValueCurveAutomationEvent;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div')\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","export const version = \"14.7.77\";\n//# sourceMappingURL=version.js.map","export const createAbortError = () => new DOMException('', 'AbortError');\n//# sourceMappingURL=abort-error.js.map","export const createAddActiveInputConnectionToAudioNode = (insertElementInSet) => {\n return (activeInputs, source, [output, input, eventListener], ignoreDuplicates) => {\n insertElementInSet(activeInputs[input], [source, output, eventListener], (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output, ignoreDuplicates);\n };\n};\n//# sourceMappingURL=add-active-input-connection-to-audio-node.js.map","export const createAddAudioNodeConnections = (audioNodeConnectionsStore) => {\n return (audioNode, audioNodeRenderer, nativeAudioNode) => {\n const activeInputs = [];\n for (let i = 0; i < nativeAudioNode.numberOfInputs; i += 1) {\n activeInputs.push(new Set());\n }\n audioNodeConnectionsStore.set(audioNode, {\n activeInputs,\n outputs: new Set(),\n passiveInputs: new WeakMap(),\n renderer: audioNodeRenderer\n });\n };\n};\n//# sourceMappingURL=add-audio-node-connections.js.map","export const createAddAudioParamConnections = (audioParamConnectionsStore) => {\n return (audioParam, audioParamRenderer) => {\n audioParamConnectionsStore.set(audioParam, { activeInputs: new Set(), passiveInputs: new WeakMap(), renderer: audioParamRenderer });\n };\n};\n//# sourceMappingURL=add-audio-param-connections.js.map","export const ACTIVE_AUDIO_NODE_STORE = new WeakSet();\nexport const AUDIO_NODE_CONNECTIONS_STORE = new WeakMap();\nexport const AUDIO_NODE_STORE = new WeakMap();\nexport const AUDIO_PARAM_CONNECTIONS_STORE = new WeakMap();\nexport const AUDIO_PARAM_STORE = new WeakMap();\nexport const CONTEXT_STORE = new WeakMap();\nexport const EVENT_LISTENERS = new WeakMap();\nexport const CYCLE_COUNTERS = new WeakMap();\n// This clunky name is borrowed from the spec. :-)\nexport const NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS = new WeakMap();\nexport const NODE_TO_PROCESSOR_MAPS = new WeakMap();\n//# sourceMappingURL=globals.js.map","const handler = {\n construct() {\n return handler;\n }\n};\nexport const isConstructible = (constructible) => {\n try {\n const proxy = new Proxy(constructible, handler);\n new proxy(); // tslint:disable-line:no-unused-expression\n }\n catch {\n return false;\n }\n return true;\n};\n//# sourceMappingURL=is-constructible.js.map","/*\n * This massive regex tries to cover all the following cases.\n *\n * import './path';\n * import defaultImport from './path';\n * import { namedImport } from './path';\n * import { namedImport as renamendImport } from './path';\n * import * as namespaceImport from './path';\n * import defaultImport, { namedImport } from './path';\n * import defaultImport, { namedImport as renamendImport } from './path';\n * import defaultImport, * as namespaceImport from './path';\n */\nconst IMPORT_STATEMENT_REGEX = /^import(?:(?:[\\s]+[\\w]+|(?:[\\s]+[\\w]+[\\s]*,)?[\\s]*\\{[\\s]*[\\w]+(?:[\\s]+as[\\s]+[\\w]+)?(?:[\\s]*,[\\s]*[\\w]+(?:[\\s]+as[\\s]+[\\w]+)?)*[\\s]*}|(?:[\\s]+[\\w]+[\\s]*,)?[\\s]*\\*[\\s]+as[\\s]+[\\w]+)[\\s]+from)?(?:[\\s]*)(\"([^\"\\\\]|\\\\.)+\"|'([^'\\\\]|\\\\.)+')(?:[\\s]*);?/; // tslint:disable-line:max-line-length\nexport const splitImportStatements = (source, url) => {\n const importStatements = [];\n let sourceWithoutImportStatements = source.replace(/^[\\s]+/, '');\n let result = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX);\n while (result !== null) {\n const unresolvedUrl = result[1].slice(1, -1);\n const importStatementWithResolvedUrl = result[0]\n .replace(/([\\s]+)?;?$/, '')\n .replace(unresolvedUrl, new URL(unresolvedUrl, url).toString());\n importStatements.push(importStatementWithResolvedUrl);\n sourceWithoutImportStatements = sourceWithoutImportStatements.slice(result[0].length).replace(/^[\\s]+/, '');\n result = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX);\n }\n return [importStatements.join(';'), sourceWithoutImportStatements];\n};\n//# sourceMappingURL=split-import-statements.js.map","import { NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS } from '../globals';\nimport { isConstructible } from '../helpers/is-constructible';\nimport { splitImportStatements } from '../helpers/split-import-statements';\nconst verifyParameterDescriptors = (parameterDescriptors) => {\n if (parameterDescriptors !== undefined && !Array.isArray(parameterDescriptors)) {\n throw new TypeError('The parameterDescriptors property of given value for processorCtor is not an array.');\n }\n};\nconst verifyProcessorCtor = (processorCtor) => {\n if (!isConstructible(processorCtor)) {\n throw new TypeError('The given value for processorCtor should be a constructor.');\n }\n if (processorCtor.prototype === null || typeof processorCtor.prototype !== 'object') {\n throw new TypeError('The given value for processorCtor should have a prototype.');\n }\n};\nexport const createAddAudioWorkletModule = (cacheTestResult, createNotSupportedError, evaluateSource, exposeCurrentFrameAndCurrentTime, fetchSource, getNativeContext, getOrCreateBackupOfflineAudioContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, ongoingRequests, resolvedRequests, testAudioWorkletProcessorPostMessageSupport, window) => {\n let index = 0;\n return (context, moduleURL, options = { credentials: 'omit' }) => {\n const resolvedRequestsOfContext = resolvedRequests.get(context);\n if (resolvedRequestsOfContext !== undefined && resolvedRequestsOfContext.has(moduleURL)) {\n return Promise.resolve();\n }\n const ongoingRequestsOfContext = ongoingRequests.get(context);\n if (ongoingRequestsOfContext !== undefined) {\n const promiseOfOngoingRequest = ongoingRequestsOfContext.get(moduleURL);\n if (promiseOfOngoingRequest !== undefined) {\n return promiseOfOngoingRequest;\n }\n }\n const nativeContext = getNativeContext(context);\n // Bug #59: Safari does not implement the audioWorklet property.\n const promise = nativeContext.audioWorklet === undefined\n ? fetchSource(moduleURL)\n .then(([source, absoluteUrl]) => {\n const [importStatements, sourceWithoutImportStatements] = splitImportStatements(source, absoluteUrl);\n /*\n * This is the unminified version of the code used below:\n *\n * ```js\n * ${ importStatements };\n * ((a, b) => {\n * (a[b] = a[b] || [ ]).push(\n * (AudioWorkletProcessor, global, registerProcessor, sampleRate, self, window) => {\n * ${ sourceWithoutImportStatements }\n * }\n * );\n * })(window, '_AWGS');\n * ```\n */\n // tslint:disable-next-line:max-line-length\n const wrappedSource = `${importStatements};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${sourceWithoutImportStatements}\n})})(window,'_AWGS')`;\n // @todo Evaluating the given source code is a possible security problem.\n return evaluateSource(wrappedSource);\n })\n .then(() => {\n const evaluateAudioWorkletGlobalScope = window._AWGS.pop();\n if (evaluateAudioWorkletGlobalScope === undefined) {\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n throw new SyntaxError();\n }\n exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, () => evaluateAudioWorkletGlobalScope(class AudioWorkletProcessor {\n }, undefined, (name, processorCtor) => {\n if (name.trim() === '') {\n throw createNotSupportedError();\n }\n const nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext);\n if (nodeNameToProcessorConstructorMap !== undefined) {\n if (nodeNameToProcessorConstructorMap.has(name)) {\n throw createNotSupportedError();\n }\n verifyProcessorCtor(processorCtor);\n verifyParameterDescriptors(processorCtor.parameterDescriptors);\n nodeNameToProcessorConstructorMap.set(name, processorCtor);\n }\n else {\n verifyProcessorCtor(processorCtor);\n verifyParameterDescriptors(processorCtor.parameterDescriptors);\n NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.set(nativeContext, new Map([[name, processorCtor]]));\n }\n }, nativeContext.sampleRate, undefined, undefined));\n })\n : Promise.all([\n fetchSource(moduleURL),\n Promise.resolve(cacheTestResult(testAudioWorkletProcessorPostMessageSupport, testAudioWorkletProcessorPostMessageSupport))\n ]).then(([[source, absoluteUrl], isSupportingPostMessage]) => {\n const currentIndex = index + 1;\n index = currentIndex;\n const [importStatements, sourceWithoutImportStatements] = splitImportStatements(source, absoluteUrl);\n /*\n * Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument.\n *\n * This is the unminified version of the code used below.\n *\n * ```js\n * class extends AudioWorkletProcessor {\n *\n * __buffers = new WeakSet();\n *\n * constructor () {\n * super();\n *\n * this.port.postMessage = ((postMessage) => {\n * return (message, transferables) => {\n * const filteredTransferables = (transferables)\n * ? transferables.filter((transferable) => !this.__buffers.has(transferable))\n * : transferables;\n *\n * return postMessage.call(this.port, message, filteredTransferables);\n * };\n * })(this.port.postMessage);\n * }\n * }\n * ```\n */\n const patchedAudioWorkletProcessor = isSupportingPostMessage\n ? 'AudioWorkletProcessor'\n : 'class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}';\n /*\n * Bug #170: Chrome and Edge do call process() with an array with empty channelData for each input if no input is connected.\n *\n * Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument.\n *\n * Bug #190: Safari doesn't throw an error when loading an unparsable module.\n *\n * This is the unminified version of the code used below:\n *\n * ```js\n * `${ importStatements };\n * ((AudioWorkletProcessor, registerProcessor) => {${ sourceWithoutImportStatements }\n * })(\n * ${ patchedAudioWorkletProcessor },\n * (name, processorCtor) => registerProcessor(name, class extends processorCtor {\n *\n * __collectBuffers = (array) => {\n * array.forEach((element) => this.__buffers.add(element.buffer));\n * };\n *\n * process (inputs, outputs, parameters) {\n * inputs.forEach(this.__collectBuffers);\n * outputs.forEach(this.__collectBuffers);\n * this.__collectBuffers(Object.values(parameters));\n *\n * return super.process(\n * (inputs.map((input) => input.some((channelData) => channelData.length === 0)) ? [ ] : input),\n * outputs,\n * parameters\n * );\n * }\n *\n * })\n * );\n *\n * registerProcessor(`__sac${currentIndex}`, class extends AudioWorkletProcessor{\n *\n * process () {\n * return false;\n * }\n *\n * })`\n * ```\n */\n const memberDefinition = isSupportingPostMessage ? '' : '__c = (a) => a.forEach(e=>this.__b.add(e.buffer));';\n const bufferRegistration = isSupportingPostMessage\n ? ''\n : 'i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));';\n const wrappedSource = `${importStatements};((AudioWorkletProcessor,registerProcessor)=>{${sourceWithoutImportStatements}\n})(${patchedAudioWorkletProcessor},(n,p)=>registerProcessor(n,class extends p{${memberDefinition}process(i,o,p){${bufferRegistration}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${currentIndex}',class extends AudioWorkletProcessor{process(){return !1}})`;\n const blob = new Blob([wrappedSource], { type: 'application/javascript; charset=utf-8' });\n const url = URL.createObjectURL(blob);\n return nativeContext.audioWorklet\n .addModule(url, options)\n .then(() => {\n if (isNativeOfflineAudioContext(nativeContext)) {\n return nativeContext;\n }\n // Bug #186: Chrome and Edge do not allow to create an AudioWorkletNode on a closed AudioContext.\n const backupOfflineAudioContext = getOrCreateBackupOfflineAudioContext(nativeContext);\n return backupOfflineAudioContext.audioWorklet.addModule(url, options).then(() => backupOfflineAudioContext);\n })\n .then((nativeContextOrBackupOfflineAudioContext) => {\n if (nativeAudioWorkletNodeConstructor === null) {\n throw new SyntaxError();\n }\n try {\n // Bug #190: Safari doesn't throw an error when loading an unparsable module.\n new nativeAudioWorkletNodeConstructor(nativeContextOrBackupOfflineAudioContext, `__sac${currentIndex}`); // tslint:disable-line:no-unused-expression\n }\n catch {\n throw new SyntaxError();\n }\n })\n .finally(() => URL.revokeObjectURL(url));\n });\n if (ongoingRequestsOfContext === undefined) {\n ongoingRequests.set(context, new Map([[moduleURL, promise]]));\n }\n else {\n ongoingRequestsOfContext.set(moduleURL, promise);\n }\n promise\n .then(() => {\n const updatedResolvedRequestsOfContext = resolvedRequests.get(context);\n if (updatedResolvedRequestsOfContext === undefined) {\n resolvedRequests.set(context, new Set([moduleURL]));\n }\n else {\n updatedResolvedRequestsOfContext.add(moduleURL);\n }\n })\n .finally(() => {\n const updatedOngoingRequestsOfContext = ongoingRequests.get(context);\n if (updatedOngoingRequestsOfContext !== undefined) {\n updatedOngoingRequestsOfContext.delete(moduleURL);\n }\n });\n return promise;\n };\n};\n//# sourceMappingURL=add-audio-worklet-module.js.map","export const getValueForKey = (map, key) => {\n const value = map.get(key);\n if (value === undefined) {\n throw new Error('A value with the given key could not be found.');\n }\n return value;\n};\n//# sourceMappingURL=get-value-for-key.js.map","export const pickElementFromSet = (set, predicate) => {\n const matchingElements = Array.from(set).filter(predicate);\n if (matchingElements.length > 1) {\n throw Error('More than one element was found.');\n }\n if (matchingElements.length === 0) {\n throw Error('No element was found.');\n }\n const [matchingElement] = matchingElements;\n set.delete(matchingElement);\n return matchingElement;\n};\n//# sourceMappingURL=pick-element-from-set.js.map","import { getValueForKey } from './get-value-for-key';\nimport { pickElementFromSet } from './pick-element-from-set';\nexport const deletePassiveInputConnectionToAudioNode = (passiveInputs, source, output, input) => {\n const passiveInputConnections = getValueForKey(passiveInputs, source);\n const matchingConnection = pickElementFromSet(passiveInputConnections, (passiveInputConnection) => passiveInputConnection[0] === output && passiveInputConnection[1] === input);\n if (passiveInputConnections.size === 0) {\n passiveInputs.delete(source);\n }\n return matchingConnection;\n};\n//# sourceMappingURL=delete-passive-input-connection-to-audio-node.js.map","import { EVENT_LISTENERS } from '../globals';\nimport { getValueForKey } from './get-value-for-key';\nexport const getEventListenersOfAudioNode = (audioNode) => {\n return getValueForKey(EVENT_LISTENERS, audioNode);\n};\n//# sourceMappingURL=get-event-listeners-of-audio-node.js.map","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nimport { getEventListenersOfAudioNode } from './get-event-listeners-of-audio-node';\nexport const setInternalStateToActive = (audioNode) => {\n if (ACTIVE_AUDIO_NODE_STORE.has(audioNode)) {\n throw new Error('The AudioNode is already stored.');\n }\n ACTIVE_AUDIO_NODE_STORE.add(audioNode);\n getEventListenersOfAudioNode(audioNode).forEach((eventListener) => eventListener(true));\n};\n//# sourceMappingURL=set-internal-state-to-active.js.map","export const isAudioWorkletNode = (audioNode) => {\n return 'port' in audioNode;\n};\n//# sourceMappingURL=audio-worklet-node.js.map","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nimport { getEventListenersOfAudioNode } from './get-event-listeners-of-audio-node';\nexport const setInternalStateToPassive = (audioNode) => {\n if (!ACTIVE_AUDIO_NODE_STORE.has(audioNode)) {\n throw new Error('The AudioNode is not stored.');\n }\n ACTIVE_AUDIO_NODE_STORE.delete(audioNode);\n getEventListenersOfAudioNode(audioNode).forEach((eventListener) => eventListener(false));\n};\n//# sourceMappingURL=set-internal-state-to-passive.js.map","import { isAudioWorkletNode } from '../guards/audio-worklet-node';\nimport { setInternalStateToPassive } from './set-internal-state-to-passive';\n// Set the internalState of the audioNode to 'passive' if it is not an AudioWorkletNode and if it has no 'active' input connections.\nexport const setInternalStateToPassiveWhenNecessary = (audioNode, activeInputs) => {\n if (!isAudioWorkletNode(audioNode) && activeInputs.every((connections) => connections.size === 0)) {\n setInternalStateToPassive(audioNode);\n }\n};\n//# sourceMappingURL=set-internal-state-to-passive-when-necessary.js.map","import { deletePassiveInputConnectionToAudioNode } from '../helpers/delete-passive-input-connection-to-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassiveWhenNecessary } from '../helpers/set-internal-state-to-passive-when-necessary';\nexport const createAddConnectionToAudioNode = (addActiveInputConnectionToAudioNode, addPassiveInputConnectionToAudioNode, connectNativeAudioNodeToNativeAudioNode, deleteActiveInputConnectionToAudioNode, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getAudioNodeTailTime, getEventListenersOfAudioNode, getNativeAudioNode, insertElementInSet, isActiveAudioNode, isPartOfACycle, isPassiveAudioNode) => {\n const tailTimeTimeoutIds = new WeakMap();\n return (source, destination, output, input, isOffline) => {\n const { activeInputs, passiveInputs } = getAudioNodeConnections(destination);\n const { outputs } = getAudioNodeConnections(source);\n const eventListeners = getEventListenersOfAudioNode(source);\n const eventListener = (isActive) => {\n const nativeDestinationAudioNode = getNativeAudioNode(destination);\n const nativeSourceAudioNode = getNativeAudioNode(source);\n if (isActive) {\n const partialConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input);\n addActiveInputConnectionToAudioNode(activeInputs, source, partialConnection, false);\n if (!isOffline && !isPartOfACycle(source)) {\n connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input);\n }\n if (isPassiveAudioNode(destination)) {\n setInternalStateToActive(destination);\n }\n }\n else {\n const partialConnection = deleteActiveInputConnectionToAudioNode(activeInputs, source, output, input);\n addPassiveInputConnectionToAudioNode(passiveInputs, input, partialConnection, false);\n if (!isOffline && !isPartOfACycle(source)) {\n disconnectNativeAudioNodeFromNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input);\n }\n const tailTime = getAudioNodeTailTime(destination);\n if (tailTime === 0) {\n if (isActiveAudioNode(destination)) {\n setInternalStateToPassiveWhenNecessary(destination, activeInputs);\n }\n }\n else {\n const tailTimeTimeoutId = tailTimeTimeoutIds.get(destination);\n if (tailTimeTimeoutId !== undefined) {\n clearTimeout(tailTimeTimeoutId);\n }\n tailTimeTimeoutIds.set(destination, setTimeout(() => {\n if (isActiveAudioNode(destination)) {\n setInternalStateToPassiveWhenNecessary(destination, activeInputs);\n }\n }, tailTime * 1000));\n }\n }\n };\n if (insertElementInSet(outputs, [destination, output, input], (outputConnection) => outputConnection[0] === destination && outputConnection[1] === output && outputConnection[2] === input, true)) {\n eventListeners.add(eventListener);\n if (isActiveAudioNode(source)) {\n addActiveInputConnectionToAudioNode(activeInputs, source, [output, input, eventListener], true);\n }\n else {\n addPassiveInputConnectionToAudioNode(passiveInputs, input, [source, output, eventListener], true);\n }\n return true;\n }\n return false;\n };\n};\n//# sourceMappingURL=add-connection-to-audio-node.js.map","export const createAddPassiveInputConnectionToAudioNode = (insertElementInSet) => {\n return (passiveInputs, input, [source, output, eventListener], ignoreDuplicates) => {\n const passiveInputConnections = passiveInputs.get(source);\n if (passiveInputConnections === undefined) {\n passiveInputs.set(source, new Set([[output, input, eventListener]]));\n }\n else {\n insertElementInSet(passiveInputConnections, [output, input, eventListener], (passiveInputConnection) => passiveInputConnection[0] === output && passiveInputConnection[1] === input, ignoreDuplicates);\n }\n };\n};\n//# sourceMappingURL=add-passive-input-connection-to-audio-node.js.map","export const createAddSilentConnection = (createNativeGainNode) => {\n return (nativeContext, nativeAudioScheduledSourceNode) => {\n const nativeGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n nativeAudioScheduledSourceNode.connect(nativeGainNode).connect(nativeContext.destination);\n const disconnect = () => {\n nativeAudioScheduledSourceNode.removeEventListener('ended', disconnect);\n nativeAudioScheduledSourceNode.disconnect(nativeGainNode);\n nativeGainNode.disconnect();\n };\n nativeAudioScheduledSourceNode.addEventListener('ended', disconnect);\n };\n};\n//# sourceMappingURL=add-silent-connection.js.map","export const createAddUnrenderedAudioWorkletNode = (getUnrenderedAudioWorkletNodes) => {\n return (nativeContext, audioWorkletNode) => {\n getUnrenderedAudioWorkletNodes(nativeContext).add(audioWorkletNode);\n };\n};\n//# sourceMappingURL=add-unrendered-audio-worklet-node.js.map","const DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n fftSize: 2048,\n maxDecibels: -30,\n minDecibels: -100,\n smoothingTimeConstant: 0.8\n};\nexport const createAnalyserNodeConstructor = (audionNodeConstructor, createAnalyserNodeRenderer, createIndexSizeError, createNativeAnalyserNode, getNativeContext, isNativeOfflineAudioContext) => {\n return class AnalyserNode extends audionNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeAnalyserNode = createNativeAnalyserNode(nativeContext, mergedOptions);\n const analyserNodeRenderer = ((isNativeOfflineAudioContext(nativeContext) ? createAnalyserNodeRenderer() : null));\n super(context, false, nativeAnalyserNode, analyserNodeRenderer);\n this._nativeAnalyserNode = nativeAnalyserNode;\n }\n get fftSize() {\n return this._nativeAnalyserNode.fftSize;\n }\n set fftSize(value) {\n this._nativeAnalyserNode.fftSize = value;\n }\n get frequencyBinCount() {\n return this._nativeAnalyserNode.frequencyBinCount;\n }\n get maxDecibels() {\n return this._nativeAnalyserNode.maxDecibels;\n }\n set maxDecibels(value) {\n // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.\n const maxDecibels = this._nativeAnalyserNode.maxDecibels;\n this._nativeAnalyserNode.maxDecibels = value;\n if (!(value > this._nativeAnalyserNode.minDecibels)) {\n this._nativeAnalyserNode.maxDecibels = maxDecibels;\n throw createIndexSizeError();\n }\n }\n get minDecibels() {\n return this._nativeAnalyserNode.minDecibels;\n }\n set minDecibels(value) {\n // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.\n const minDecibels = this._nativeAnalyserNode.minDecibels;\n this._nativeAnalyserNode.minDecibels = value;\n if (!(this._nativeAnalyserNode.maxDecibels > value)) {\n this._nativeAnalyserNode.minDecibels = minDecibels;\n throw createIndexSizeError();\n }\n }\n get smoothingTimeConstant() {\n return this._nativeAnalyserNode.smoothingTimeConstant;\n }\n set smoothingTimeConstant(value) {\n this._nativeAnalyserNode.smoothingTimeConstant = value;\n }\n getByteFrequencyData(array) {\n this._nativeAnalyserNode.getByteFrequencyData(array);\n }\n getByteTimeDomainData(array) {\n this._nativeAnalyserNode.getByteTimeDomainData(array);\n }\n getFloatFrequencyData(array) {\n this._nativeAnalyserNode.getFloatFrequencyData(array);\n }\n getFloatTimeDomainData(array) {\n this._nativeAnalyserNode.getFloatTimeDomainData(array);\n }\n };\n};\n//# sourceMappingURL=analyser-node-constructor.js.map","export const isOwnedByContext = (nativeAudioNode, nativeContext) => {\n return nativeAudioNode.context === nativeContext;\n};\n//# sourceMappingURL=is-owned-by-context.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createAnalyserNodeRendererFactory = (createNativeAnalyserNode, getNativeAudioNode, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeAnalyserNodes = new WeakMap();\n const createAnalyserNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeAnalyserNode = getNativeAudioNode(proxy);\n // If the initially used nativeAnalyserNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeAnalyserNodeIsOwnedByContext = isOwnedByContext(nativeAnalyserNode, nativeOfflineAudioContext);\n if (!nativeAnalyserNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeAnalyserNode.channelCount,\n channelCountMode: nativeAnalyserNode.channelCountMode,\n channelInterpretation: nativeAnalyserNode.channelInterpretation,\n fftSize: nativeAnalyserNode.fftSize,\n maxDecibels: nativeAnalyserNode.maxDecibels,\n minDecibels: nativeAnalyserNode.minDecibels,\n smoothingTimeConstant: nativeAnalyserNode.smoothingTimeConstant\n };\n nativeAnalyserNode = createNativeAnalyserNode(nativeOfflineAudioContext, options);\n }\n renderedNativeAnalyserNodes.set(nativeOfflineAudioContext, nativeAnalyserNode);\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAnalyserNode);\n return nativeAnalyserNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeAnalyserNode = renderedNativeAnalyserNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAnalyserNode !== undefined) {\n return Promise.resolve(renderedNativeAnalyserNode);\n }\n return createAnalyserNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=analyser-node-renderer-factory.js.map","export const testAudioBufferCopyChannelMethodsOutOfBoundsSupport = (nativeAudioBuffer) => {\n try {\n nativeAudioBuffer.copyToChannel(new Float32Array(1), 0, -1);\n }\n catch {\n return false;\n }\n return true;\n};\n//# sourceMappingURL=test-audio-buffer-copy-channel-methods-out-of-bounds-support.js.map","export const createIndexSizeError = () => new DOMException('', 'IndexSizeError');\n//# sourceMappingURL=index-size-error.js.map","import { createIndexSizeError } from '../factories/index-size-error';\nexport const wrapAudioBufferGetChannelDataMethod = (audioBuffer) => {\n audioBuffer.getChannelData = ((getChannelData) => {\n return (channel) => {\n try {\n return getChannelData.call(audioBuffer, channel);\n }\n catch (err) {\n if (err.code === 12) {\n throw createIndexSizeError();\n }\n throw err;\n }\n };\n })(audioBuffer.getChannelData);\n};\n//# sourceMappingURL=wrap-audio-buffer-get-channel-data-method.js.map","import { testAudioBufferCopyChannelMethodsOutOfBoundsSupport } from '../helpers/test-audio-buffer-copy-channel-methods-out-of-bounds-support';\nimport { wrapAudioBufferGetChannelDataMethod } from '../helpers/wrap-audio-buffer-get-channel-data-method';\nconst DEFAULT_OPTIONS = {\n numberOfChannels: 1\n};\nexport const createAudioBufferConstructor = (audioBufferStore, cacheTestResult, createNotSupportedError, nativeAudioBufferConstructor, nativeOfflineAudioContextConstructor, testNativeAudioBufferConstructorSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds) => {\n let nativeOfflineAudioContext = null;\n return class AudioBuffer {\n constructor(options) {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n const { length, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS, ...options };\n if (nativeOfflineAudioContext === null) {\n nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100);\n }\n /*\n * Bug #99: Firefox does not throw a NotSupportedError when the numberOfChannels is zero. But it only does it when using the\n * factory function. But since Firefox also supports the constructor everything should be fine.\n */\n const audioBuffer = nativeAudioBufferConstructor !== null &&\n cacheTestResult(testNativeAudioBufferConstructorSupport, testNativeAudioBufferConstructorSupport)\n ? new nativeAudioBufferConstructor({ length, numberOfChannels, sampleRate })\n : nativeOfflineAudioContext.createBuffer(numberOfChannels, length, sampleRate);\n // Bug #99: Safari does not throw an error when the numberOfChannels is zero.\n if (audioBuffer.numberOfChannels === 0) {\n throw createNotSupportedError();\n }\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value.\n if (typeof audioBuffer.copyFromChannel !== 'function') {\n wrapAudioBufferCopyChannelMethods(audioBuffer);\n wrapAudioBufferGetChannelDataMethod(audioBuffer);\n // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds.\n }\n else if (!cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () => testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer))) {\n wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer);\n }\n audioBufferStore.add(audioBuffer);\n /*\n * This does violate all good pratices but it is necessary to allow this AudioBuffer to be used with native\n * (Offline)AudioContexts.\n */\n return audioBuffer;\n }\n static [Symbol.hasInstance](instance) {\n return ((instance !== null && typeof instance === 'object' && Object.getPrototypeOf(instance) === AudioBuffer.prototype) ||\n audioBufferStore.has(instance));\n }\n };\n};\n//# sourceMappingURL=audio-buffer-constructor.js.map","export const MOST_NEGATIVE_SINGLE_FLOAT = -3.4028234663852886e38;\nexport const MOST_POSITIVE_SINGLE_FLOAT = -MOST_NEGATIVE_SINGLE_FLOAT;\n//# sourceMappingURL=constants.js.map","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nexport const isActiveAudioNode = (audioNode) => ACTIVE_AUDIO_NODE_STORE.has(audioNode);\n//# sourceMappingURL=is-active-audio-node.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassive } from '../helpers/set-internal-state-to-passive';\nconst DEFAULT_OPTIONS = {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n // Bug #149: Safari does not yet support the detune AudioParam.\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n};\nexport const createAudioBufferSourceNodeConstructor = (audioNodeConstructor, createAudioBufferSourceNodeRenderer, createAudioParam, createInvalidStateError, createNativeAudioBufferSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener) => {\n return class AudioBufferSourceNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const audioBufferSourceNodeRenderer = ((isOffline ? createAudioBufferSourceNodeRenderer() : null));\n super(context, false, nativeAudioBufferSourceNode, audioBufferSourceNodeRenderer);\n this._audioBufferSourceNodeRenderer = audioBufferSourceNodeRenderer;\n this._isBufferNullified = false;\n this._isBufferSet = mergedOptions.buffer !== null;\n this._nativeAudioBufferSourceNode = nativeAudioBufferSourceNode;\n this._onended = null;\n // Bug #73: Safari does not export the correct values for maxValue and minValue.\n this._playbackRate = createAudioParam(this, isOffline, nativeAudioBufferSourceNode.playbackRate, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n }\n get buffer() {\n if (this._isBufferNullified) {\n return null;\n }\n return this._nativeAudioBufferSourceNode.buffer;\n }\n set buffer(value) {\n this._nativeAudioBufferSourceNode.buffer = value;\n // Bug #72: Only Chrome & Edge do not allow to reassign the buffer yet.\n if (value !== null) {\n if (this._isBufferSet) {\n throw createInvalidStateError();\n }\n this._isBufferSet = true;\n }\n }\n get loop() {\n return this._nativeAudioBufferSourceNode.loop;\n }\n set loop(value) {\n this._nativeAudioBufferSourceNode.loop = value;\n }\n get loopEnd() {\n return this._nativeAudioBufferSourceNode.loopEnd;\n }\n set loopEnd(value) {\n this._nativeAudioBufferSourceNode.loopEnd = value;\n }\n get loopStart() {\n return this._nativeAudioBufferSourceNode.loopStart;\n }\n set loopStart(value) {\n this._nativeAudioBufferSourceNode.loopStart = value;\n }\n get onended() {\n return this._onended;\n }\n set onended(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n this._nativeAudioBufferSourceNode.onended = wrappedListener;\n const nativeOnEnded = this._nativeAudioBufferSourceNode.onended;\n this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;\n }\n get playbackRate() {\n return this._playbackRate;\n }\n start(when = 0, offset = 0, duration) {\n this._nativeAudioBufferSourceNode.start(when, offset, duration);\n if (this._audioBufferSourceNodeRenderer !== null) {\n this._audioBufferSourceNodeRenderer.start = duration === undefined ? [when, offset] : [when, offset, duration];\n }\n if (this.context.state !== 'closed') {\n setInternalStateToActive(this);\n const resetInternalStateToPassive = () => {\n this._nativeAudioBufferSourceNode.removeEventListener('ended', resetInternalStateToPassive);\n if (isActiveAudioNode(this)) {\n setInternalStateToPassive(this);\n }\n };\n this._nativeAudioBufferSourceNode.addEventListener('ended', resetInternalStateToPassive);\n }\n }\n stop(when = 0) {\n this._nativeAudioBufferSourceNode.stop(when);\n if (this._audioBufferSourceNodeRenderer !== null) {\n this._audioBufferSourceNodeRenderer.stop = when;\n }\n }\n };\n};\n//# sourceMappingURL=audio-buffer-source-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createAudioBufferSourceNodeRendererFactory = (connectAudioParam, createNativeAudioBufferSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeAudioBufferSourceNodes = new WeakMap();\n let start = null;\n let stop = null;\n const createAudioBufferSourceNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeAudioBufferSourceNode = getNativeAudioNode(proxy);\n /*\n * If the initially used nativeAudioBufferSourceNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeAudioBufferSourceNodeIsOwnedByContext = isOwnedByContext(nativeAudioBufferSourceNode, nativeOfflineAudioContext);\n if (!nativeAudioBufferSourceNodeIsOwnedByContext) {\n const options = {\n buffer: nativeAudioBufferSourceNode.buffer,\n channelCount: nativeAudioBufferSourceNode.channelCount,\n channelCountMode: nativeAudioBufferSourceNode.channelCountMode,\n channelInterpretation: nativeAudioBufferSourceNode.channelInterpretation,\n // Bug #149: Safari does not yet support the detune AudioParam.\n loop: nativeAudioBufferSourceNode.loop,\n loopEnd: nativeAudioBufferSourceNode.loopEnd,\n loopStart: nativeAudioBufferSourceNode.loopStart,\n playbackRate: nativeAudioBufferSourceNode.playbackRate.value\n };\n nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, options);\n if (start !== null) {\n nativeAudioBufferSourceNode.start(...start);\n }\n if (stop !== null) {\n nativeAudioBufferSourceNode.stop(stop);\n }\n }\n renderedNativeAudioBufferSourceNodes.set(nativeOfflineAudioContext, nativeAudioBufferSourceNode);\n if (!nativeAudioBufferSourceNodeIsOwnedByContext) {\n // Bug #149: Safari does not yet support the detune AudioParam.\n await renderAutomation(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate);\n }\n else {\n // Bug #149: Safari does not yet support the detune AudioParam.\n await connectAudioParam(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioBufferSourceNode);\n return nativeAudioBufferSourceNode;\n };\n return {\n set start(value) {\n start = value;\n },\n set stop(value) {\n stop = value;\n },\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeAudioBufferSourceNode = renderedNativeAudioBufferSourceNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAudioBufferSourceNode !== undefined) {\n return Promise.resolve(renderedNativeAudioBufferSourceNode);\n }\n return createAudioBufferSourceNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=audio-buffer-source-node-renderer-factory.js.map","export const isAudioBufferSourceNode = (audioNode) => {\n return 'playbackRate' in audioNode;\n};\n//# sourceMappingURL=audio-buffer-source-node.js.map","export const isBiquadFilterNode = (audioNode) => {\n return 'frequency' in audioNode && 'gain' in audioNode;\n};\n//# sourceMappingURL=biquad-filter-node.js.map","export const isConstantSourceNode = (audioNode) => {\n return 'offset' in audioNode;\n};\n//# sourceMappingURL=constant-source-node.js.map","export const isGainNode = (audioNode) => {\n return !('frequency' in audioNode) && 'gain' in audioNode;\n};\n//# sourceMappingURL=gain-node.js.map","export const isOscillatorNode = (audioNode) => {\n return 'detune' in audioNode && 'frequency' in audioNode;\n};\n//# sourceMappingURL=oscillator-node.js.map","export const isStereoPannerNode = (audioNode) => {\n return 'pan' in audioNode;\n};\n//# sourceMappingURL=stereo-panner-node.js.map","import { AUDIO_NODE_CONNECTIONS_STORE } from '../globals';\nimport { getValueForKey } from './get-value-for-key';\nexport const getAudioNodeConnections = (audioNode) => {\n return getValueForKey(AUDIO_NODE_CONNECTIONS_STORE, audioNode);\n};\n//# sourceMappingURL=get-audio-node-connections.js.map","import { AUDIO_PARAM_CONNECTIONS_STORE } from '../globals';\nimport { getValueForKey } from './get-value-for-key';\nexport const getAudioParamConnections = (audioParam) => {\n return getValueForKey(AUDIO_PARAM_CONNECTIONS_STORE, audioParam);\n};\n//# sourceMappingURL=get-audio-param-connections.js.map","import { isAudioBufferSourceNode } from '../guards/audio-buffer-source-node';\nimport { isAudioWorkletNode } from '../guards/audio-worklet-node';\nimport { isBiquadFilterNode } from '../guards/biquad-filter-node';\nimport { isConstantSourceNode } from '../guards/constant-source-node';\nimport { isGainNode } from '../guards/gain-node';\nimport { isOscillatorNode } from '../guards/oscillator-node';\nimport { isStereoPannerNode } from '../guards/stereo-panner-node';\nimport { getAudioNodeConnections } from './get-audio-node-connections';\nimport { getAudioParamConnections } from './get-audio-param-connections';\nimport { isActiveAudioNode } from './is-active-audio-node';\nimport { setInternalStateToPassive } from './set-internal-state-to-passive';\nexport const deactivateActiveAudioNodeInputConnections = (audioNode, trace) => {\n const { activeInputs } = getAudioNodeConnections(audioNode);\n activeInputs.forEach((connections) => connections.forEach(([source]) => {\n if (!trace.includes(audioNode)) {\n deactivateActiveAudioNodeInputConnections(source, [...trace, audioNode]);\n }\n }));\n const audioParams = isAudioBufferSourceNode(audioNode)\n ? [\n // Bug #149: Safari does not yet support the detune AudioParam.\n audioNode.playbackRate\n ]\n : isAudioWorkletNode(audioNode)\n ? Array.from(audioNode.parameters.values())\n : isBiquadFilterNode(audioNode)\n ? [audioNode.Q, audioNode.detune, audioNode.frequency, audioNode.gain]\n : isConstantSourceNode(audioNode)\n ? [audioNode.offset]\n : isGainNode(audioNode)\n ? [audioNode.gain]\n : isOscillatorNode(audioNode)\n ? [audioNode.detune, audioNode.frequency]\n : isStereoPannerNode(audioNode)\n ? [audioNode.pan]\n : [];\n for (const audioParam of audioParams) {\n const audioParamConnections = getAudioParamConnections(audioParam);\n if (audioParamConnections !== undefined) {\n audioParamConnections.activeInputs.forEach(([source]) => deactivateActiveAudioNodeInputConnections(source, trace));\n }\n }\n if (isActiveAudioNode(audioNode)) {\n setInternalStateToPassive(audioNode);\n }\n};\n//# sourceMappingURL=deactivate-active-audio-node-input-connections.js.map","import { deactivateActiveAudioNodeInputConnections } from './deactivate-active-audio-node-input-connections';\nexport const deactivateAudioGraph = (context) => {\n deactivateActiveAudioNodeInputConnections(context.destination, []);\n};\n//# sourceMappingURL=deactivate-audio-graph.js.map","export const isValidLatencyHint = (latencyHint) => {\n return (latencyHint === undefined ||\n typeof latencyHint === 'number' ||\n (typeof latencyHint === 'string' && (latencyHint === 'balanced' || latencyHint === 'interactive' || latencyHint === 'playback')));\n};\n//# sourceMappingURL=is-valid-latency-hint.js.map","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { isValidLatencyHint } from '../helpers/is-valid-latency-hint';\nexport const createAudioContextConstructor = (baseAudioContextConstructor, createInvalidStateError, createNotSupportedError, createUnknownError, mediaElementAudioSourceNodeConstructor, mediaStreamAudioDestinationNodeConstructor, mediaStreamAudioSourceNodeConstructor, mediaStreamTrackAudioSourceNodeConstructor, nativeAudioContextConstructor) => {\n return class AudioContext extends baseAudioContextConstructor {\n constructor(options = {}) {\n if (nativeAudioContextConstructor === null) {\n throw new Error('Missing the native AudioContext constructor.');\n }\n let nativeAudioContext;\n try {\n nativeAudioContext = new nativeAudioContextConstructor(options);\n }\n catch (err) {\n // Bug #192 Safari does throw a SyntaxError if the sampleRate is not supported.\n if (err.code === 12 && err.message === 'sampleRate is not in range') {\n throw createNotSupportedError();\n }\n throw err;\n }\n // Bug #131 Safari returns null when there are four other AudioContexts running already.\n if (nativeAudioContext === null) {\n throw createUnknownError();\n }\n // Bug #51 Only Chrome and Edge throw an error if the given latencyHint is invalid.\n if (!isValidLatencyHint(options.latencyHint)) {\n throw new TypeError(`The provided value '${options.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);\n }\n // Bug #150 Safari does not support setting the sampleRate.\n if (options.sampleRate !== undefined && nativeAudioContext.sampleRate !== options.sampleRate) {\n throw createNotSupportedError();\n }\n super(nativeAudioContext, 2);\n const { latencyHint } = options;\n const { sampleRate } = nativeAudioContext;\n // @todo The values for 'balanced', 'interactive' and 'playback' are just copied from Chrome's implementation.\n this._baseLatency =\n typeof nativeAudioContext.baseLatency === 'number'\n ? nativeAudioContext.baseLatency\n : latencyHint === 'balanced'\n ? 512 / sampleRate\n : latencyHint === 'interactive' || latencyHint === undefined\n ? 256 / sampleRate\n : latencyHint === 'playback'\n ? 1024 / sampleRate\n : /*\n * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a\n * ScriptProcessorNode.\n */\n (Math.max(2, Math.min(128, Math.round((latencyHint * sampleRate) / 128))) * 128) / sampleRate;\n this._nativeAudioContext = nativeAudioContext;\n // Bug #188: Safari will set the context's state to 'interrupted' in case the user switches tabs.\n if (nativeAudioContextConstructor.name === 'webkitAudioContext') {\n this._nativeGainNode = nativeAudioContext.createGain();\n this._nativeOscillatorNode = nativeAudioContext.createOscillator();\n this._nativeGainNode.gain.value = 1e-37;\n this._nativeOscillatorNode.connect(this._nativeGainNode).connect(nativeAudioContext.destination);\n this._nativeOscillatorNode.start();\n }\n else {\n this._nativeGainNode = null;\n this._nativeOscillatorNode = null;\n }\n this._state = null;\n /*\n * Bug #34: Chrome and Edge pretend to be running right away, but fire an onstatechange event when the state actually changes\n * to 'running'.\n */\n if (nativeAudioContext.state === 'running') {\n this._state = 'suspended';\n const revokeState = () => {\n if (this._state === 'suspended') {\n this._state = null;\n }\n nativeAudioContext.removeEventListener('statechange', revokeState);\n };\n nativeAudioContext.addEventListener('statechange', revokeState);\n }\n }\n get baseLatency() {\n return this._baseLatency;\n }\n get state() {\n return this._state !== null ? this._state : this._nativeAudioContext.state;\n }\n close() {\n // Bug #35: Firefox does not throw an error if the AudioContext was closed before.\n if (this.state === 'closed') {\n return this._nativeAudioContext.close().then(() => {\n throw createInvalidStateError();\n });\n }\n // Bug #34: If the state was set to suspended before it should be revoked now.\n if (this._state === 'suspended') {\n this._state = null;\n }\n return this._nativeAudioContext.close().then(() => {\n if (this._nativeGainNode !== null && this._nativeOscillatorNode !== null) {\n this._nativeOscillatorNode.stop();\n this._nativeGainNode.disconnect();\n this._nativeOscillatorNode.disconnect();\n }\n deactivateAudioGraph(this);\n });\n }\n createMediaElementSource(mediaElement) {\n return new mediaElementAudioSourceNodeConstructor(this, { mediaElement });\n }\n createMediaStreamDestination() {\n return new mediaStreamAudioDestinationNodeConstructor(this);\n }\n createMediaStreamSource(mediaStream) {\n return new mediaStreamAudioSourceNodeConstructor(this, { mediaStream });\n }\n createMediaStreamTrackSource(mediaStreamTrack) {\n return new mediaStreamTrackAudioSourceNodeConstructor(this, { mediaStreamTrack });\n }\n resume() {\n if (this._state === 'suspended') {\n return new Promise((resolve, reject) => {\n const resolvePromise = () => {\n this._nativeAudioContext.removeEventListener('statechange', resolvePromise);\n if (this._nativeAudioContext.state === 'running') {\n resolve();\n }\n else {\n this.resume().then(resolve, reject);\n }\n };\n this._nativeAudioContext.addEventListener('statechange', resolvePromise);\n });\n }\n return this._nativeAudioContext.resume().catch((err) => {\n // Bug #55: Chrome and Edge do throw an InvalidAccessError instead of an InvalidStateError.\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined || err.code === 15) {\n throw createInvalidStateError();\n }\n throw err;\n });\n }\n suspend() {\n return this._nativeAudioContext.suspend().catch((err) => {\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined) {\n throw createInvalidStateError();\n }\n throw err;\n });\n }\n };\n};\n//# sourceMappingURL=audio-context-constructor.js.map","export const createAudioDestinationNodeConstructor = (audioNodeConstructor, createAudioDestinationNodeRenderer, createIndexSizeError, createInvalidStateError, createNativeAudioDestinationNode, getNativeContext, isNativeOfflineAudioContext, renderInputsOfAudioNode) => {\n return class AudioDestinationNode extends audioNodeConstructor {\n constructor(context, channelCount) {\n const nativeContext = getNativeContext(context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const nativeAudioDestinationNode = createNativeAudioDestinationNode(nativeContext, channelCount, isOffline);\n const audioDestinationNodeRenderer = ((isOffline ? createAudioDestinationNodeRenderer(renderInputsOfAudioNode) : null));\n super(context, false, nativeAudioDestinationNode, audioDestinationNodeRenderer);\n this._isNodeOfNativeOfflineAudioContext = isOffline;\n this._nativeAudioDestinationNode = nativeAudioDestinationNode;\n }\n get channelCount() {\n return this._nativeAudioDestinationNode.channelCount;\n }\n set channelCount(value) {\n // Bug #52: Chrome, Edge & Safari do not throw an exception at all.\n // Bug #54: Firefox does throw an IndexSizeError.\n if (this._isNodeOfNativeOfflineAudioContext) {\n throw createInvalidStateError();\n }\n // Bug #47: The AudioDestinationNode in Safari does not initialize the maxChannelCount property correctly.\n if (value > this._nativeAudioDestinationNode.maxChannelCount) {\n throw createIndexSizeError();\n }\n this._nativeAudioDestinationNode.channelCount = value;\n }\n get channelCountMode() {\n return this._nativeAudioDestinationNode.channelCountMode;\n }\n set channelCountMode(value) {\n // Bug #53: No browser does throw an exception yet.\n if (this._isNodeOfNativeOfflineAudioContext) {\n throw createInvalidStateError();\n }\n this._nativeAudioDestinationNode.channelCountMode = value;\n }\n get maxChannelCount() {\n return this._nativeAudioDestinationNode.maxChannelCount;\n }\n };\n};\n//# sourceMappingURL=audio-destination-node-constructor.js.map","export const createAudioDestinationNodeRenderer = (renderInputsOfAudioNode) => {\n const renderedNativeAudioDestinationNodes = new WeakMap();\n const createAudioDestinationNode = async (proxy, nativeOfflineAudioContext) => {\n const nativeAudioDestinationNode = nativeOfflineAudioContext.destination;\n renderedNativeAudioDestinationNodes.set(nativeOfflineAudioContext, nativeAudioDestinationNode);\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioDestinationNode);\n return nativeAudioDestinationNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeAudioDestinationNode = renderedNativeAudioDestinationNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAudioDestinationNode !== undefined) {\n return Promise.resolve(renderedNativeAudioDestinationNode);\n }\n return createAudioDestinationNode(proxy, nativeOfflineAudioContext);\n }\n };\n};\n//# sourceMappingURL=audio-destination-node-renderer-factory.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nexport const createAudioListenerFactory = (createAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeScriptProcessorNode, createNotSupportedError, getFirstSample, isNativeOfflineAudioContext, overwriteAccessors) => {\n return (context, nativeContext) => {\n const nativeListener = nativeContext.listener;\n // Bug #117: Only Chrome & Edge support the new interface already.\n const createFakeAudioParams = () => {\n const buffer = new Float32Array(1);\n const channelMergerNode = createNativeChannelMergerNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 9\n });\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n let isScriptProcessorNodeCreated = false;\n let lastOrientation = [0, 0, -1, 0, 1, 0];\n let lastPosition = [0, 0, 0];\n const createScriptProcessorNode = () => {\n if (isScriptProcessorNodeCreated) {\n return;\n }\n isScriptProcessorNodeCreated = true;\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 9, 0);\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = ({ inputBuffer }) => {\n const orientation = [\n getFirstSample(inputBuffer, buffer, 0),\n getFirstSample(inputBuffer, buffer, 1),\n getFirstSample(inputBuffer, buffer, 2),\n getFirstSample(inputBuffer, buffer, 3),\n getFirstSample(inputBuffer, buffer, 4),\n getFirstSample(inputBuffer, buffer, 5)\n ];\n if (orientation.some((value, index) => value !== lastOrientation[index])) {\n nativeListener.setOrientation(...orientation); // tslint:disable-line:deprecation\n lastOrientation = orientation;\n }\n const positon = [\n getFirstSample(inputBuffer, buffer, 6),\n getFirstSample(inputBuffer, buffer, 7),\n getFirstSample(inputBuffer, buffer, 8)\n ];\n if (positon.some((value, index) => value !== lastPosition[index])) {\n nativeListener.setPosition(...positon); // tslint:disable-line:deprecation\n lastPosition = positon;\n }\n };\n channelMergerNode.connect(scriptProcessorNode);\n };\n const createSetOrientation = (index) => (value) => {\n if (value !== lastOrientation[index]) {\n lastOrientation[index] = value;\n nativeListener.setOrientation(...lastOrientation); // tslint:disable-line:deprecation\n }\n };\n const createSetPosition = (index) => (value) => {\n if (value !== lastPosition[index]) {\n lastPosition[index] = value;\n nativeListener.setPosition(...lastPosition); // tslint:disable-line:deprecation\n }\n };\n const createFakeAudioParam = (input, initialValue, setValue) => {\n const constantSourceNode = createNativeConstantSourceNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: initialValue\n });\n constantSourceNode.connect(channelMergerNode, 0, input);\n // @todo This should be stopped when the context is closed.\n constantSourceNode.start();\n Object.defineProperty(constantSourceNode.offset, 'defaultValue', {\n get() {\n return initialValue;\n }\n });\n /*\n * Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and\n * minValue for GainNodes.\n */\n const audioParam = createAudioParam({ context }, isOffline, constantSourceNode.offset, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n overwriteAccessors(audioParam, 'value', (get) => () => get.call(audioParam), (set) => (value) => {\n try {\n set.call(audioParam, value);\n }\n catch (err) {\n if (err.code !== 9) {\n throw err;\n }\n }\n createScriptProcessorNode();\n if (isOffline) {\n // Bug #117: Using setOrientation() and setPosition() doesn't work with an OfflineAudioContext.\n setValue(value);\n }\n });\n audioParam.cancelAndHoldAtTime = ((cancelAndHoldAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = cancelAndHoldAtTime.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.cancelAndHoldAtTime);\n audioParam.cancelScheduledValues = ((cancelScheduledValues) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = cancelScheduledValues.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.cancelScheduledValues);\n audioParam.exponentialRampToValueAtTime = ((exponentialRampToValueAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = exponentialRampToValueAtTime.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.exponentialRampToValueAtTime);\n audioParam.linearRampToValueAtTime = ((linearRampToValueAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = linearRampToValueAtTime.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.linearRampToValueAtTime);\n audioParam.setTargetAtTime = ((setTargetAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = setTargetAtTime.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.setTargetAtTime);\n audioParam.setValueAtTime = ((setValueAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = setValueAtTime.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.setValueAtTime);\n audioParam.setValueCurveAtTime = ((setValueCurveAtTime) => {\n if (isOffline) {\n return () => {\n throw createNotSupportedError();\n };\n }\n return (...args) => {\n const value = setValueCurveAtTime.apply(audioParam, args);\n createScriptProcessorNode();\n return value;\n };\n })(audioParam.setValueCurveAtTime);\n return audioParam;\n };\n return {\n forwardX: createFakeAudioParam(0, 0, createSetOrientation(0)),\n forwardY: createFakeAudioParam(1, 0, createSetOrientation(1)),\n forwardZ: createFakeAudioParam(2, -1, createSetOrientation(2)),\n positionX: createFakeAudioParam(6, 0, createSetPosition(0)),\n positionY: createFakeAudioParam(7, 0, createSetPosition(1)),\n positionZ: createFakeAudioParam(8, 0, createSetPosition(2)),\n upX: createFakeAudioParam(3, 0, createSetOrientation(3)),\n upY: createFakeAudioParam(4, 1, createSetOrientation(4)),\n upZ: createFakeAudioParam(5, 0, createSetOrientation(5))\n };\n };\n const { forwardX, forwardY, forwardZ, positionX, positionY, positionZ, upX, upY, upZ } = nativeListener.forwardX === undefined ? createFakeAudioParams() : nativeListener;\n return {\n get forwardX() {\n return forwardX;\n },\n get forwardY() {\n return forwardY;\n },\n get forwardZ() {\n return forwardZ;\n },\n get positionX() {\n return positionX;\n },\n get positionY() {\n return positionY;\n },\n get positionZ() {\n return positionZ;\n },\n get upX() {\n return upX;\n },\n get upY() {\n return upY;\n },\n get upZ() {\n return upZ;\n }\n };\n };\n};\n//# sourceMappingURL=audio-listener-factory.js.map","export const isAudioNode = (audioNodeOrAudioParam) => {\n return 'context' in audioNodeOrAudioParam;\n};\n//# sourceMappingURL=audio-node.js.map","import { isAudioNode } from './audio-node';\nexport const isAudioNodeOutputConnection = (outputConnection) => {\n return isAudioNode(outputConnection[0]);\n};\n//# sourceMappingURL=audio-node-output-connection.js.map","export const insertElementInSet = (set, element, predicate, ignoreDuplicates) => {\n for (const lmnt of set) {\n if (predicate(lmnt)) {\n if (ignoreDuplicates) {\n return false;\n }\n throw Error('The set contains at least one similar element.');\n }\n }\n set.add(element);\n return true;\n};\n//# sourceMappingURL=insert-element-in-set.js.map","import { insertElementInSet } from './insert-element-in-set';\nexport const addActiveInputConnectionToAudioParam = (activeInputs, source, [output, eventListener], ignoreDuplicates) => {\n insertElementInSet(activeInputs, [source, output, eventListener], (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output, ignoreDuplicates);\n};\n//# sourceMappingURL=add-active-input-connection-to-audio-param.js.map","import { insertElementInSet } from './insert-element-in-set';\nexport const addPassiveInputConnectionToAudioParam = (passiveInputs, [source, output, eventListener], ignoreDuplicates) => {\n const passiveInputConnections = passiveInputs.get(source);\n if (passiveInputConnections === undefined) {\n passiveInputs.set(source, new Set([[output, eventListener]]));\n }\n else {\n insertElementInSet(passiveInputConnections, [output, eventListener], (passiveInputConnection) => passiveInputConnection[0] === output, ignoreDuplicates);\n }\n};\n//# sourceMappingURL=add-passive-input-connection-to-audio-param.js.map","export const isNativeAudioNodeFaker = (nativeAudioNodeOrNativeAudioNodeFaker) => {\n return 'inputs' in nativeAudioNodeOrNativeAudioNodeFaker;\n};\n//# sourceMappingURL=native-audio-node-faker.js.map","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nexport const connectNativeAudioNodeToNativeAudioNode = (nativeSourceAudioNode, nativeDestinationAudioNode, output, input) => {\n if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) {\n const fakeNativeDestinationAudioNode = nativeDestinationAudioNode.inputs[input];\n nativeSourceAudioNode.connect(fakeNativeDestinationAudioNode, output, 0);\n return [fakeNativeDestinationAudioNode, output, 0];\n }\n nativeSourceAudioNode.connect(nativeDestinationAudioNode, output, input);\n return [nativeDestinationAudioNode, output, input];\n};\n//# sourceMappingURL=connect-native-audio-node-to-native-audio-node.js.map","export const deleteActiveInputConnection = (activeInputConnections, source, output) => {\n for (const activeInputConnection of activeInputConnections) {\n if (activeInputConnection[0] === source && activeInputConnection[1] === output) {\n activeInputConnections.delete(activeInputConnection);\n return activeInputConnection;\n }\n }\n return null;\n};\n//# sourceMappingURL=delete-active-input-connection.js.map","import { pickElementFromSet } from './pick-element-from-set';\nexport const deleteActiveInputConnectionToAudioParam = (activeInputs, source, output) => {\n return pickElementFromSet(activeInputs, (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output);\n};\n//# sourceMappingURL=delete-active-input-connection-to-audio-param.js.map","import { getEventListenersOfAudioNode } from './get-event-listeners-of-audio-node';\nexport const deleteEventListenerOfAudioNode = (audioNode, eventListener) => {\n const eventListeners = getEventListenersOfAudioNode(audioNode);\n if (!eventListeners.delete(eventListener)) {\n throw new Error('Missing the expected event listener.');\n }\n};\n//# sourceMappingURL=delete-event-listeners-of-audio-node.js.map","import { getValueForKey } from './get-value-for-key';\nimport { pickElementFromSet } from './pick-element-from-set';\nexport const deletePassiveInputConnectionToAudioParam = (passiveInputs, source, output) => {\n const passiveInputConnections = getValueForKey(passiveInputs, source);\n const matchingConnection = pickElementFromSet(passiveInputConnections, (passiveInputConnection) => passiveInputConnection[0] === output);\n if (passiveInputConnections.size === 0) {\n passiveInputs.delete(source);\n }\n return matchingConnection;\n};\n//# sourceMappingURL=delete-passive-input-connection-to-audio-param.js.map","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nexport const disconnectNativeAudioNodeFromNativeAudioNode = (nativeSourceAudioNode, nativeDestinationAudioNode, output, input) => {\n if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) {\n nativeSourceAudioNode.disconnect(nativeDestinationAudioNode.inputs[input], output, 0);\n }\n else {\n nativeSourceAudioNode.disconnect(nativeDestinationAudioNode, output, input);\n }\n};\n//# sourceMappingURL=disconnect-native-audio-node-from-native-audio-node.js.map","import { AUDIO_NODE_STORE } from '../globals';\nimport { getValueForKey } from './get-value-for-key';\nexport const getNativeAudioNode = (audioNode) => {\n return getValueForKey(AUDIO_NODE_STORE, audioNode);\n};\n//# sourceMappingURL=get-native-audio-node.js.map","import { AUDIO_PARAM_STORE } from '../globals';\nimport { getValueForKey } from './get-value-for-key';\nexport const getNativeAudioParam = (audioParam) => {\n return getValueForKey(AUDIO_PARAM_STORE, audioParam);\n};\n//# sourceMappingURL=get-native-audio-param.js.map","import { CYCLE_COUNTERS } from '../globals';\nexport const isPartOfACycle = (audioNode) => {\n return CYCLE_COUNTERS.has(audioNode);\n};\n//# sourceMappingURL=is-part-of-a-cycle.js.map","import { ACTIVE_AUDIO_NODE_STORE } from '../globals';\nexport const isPassiveAudioNode = (audioNode) => {\n return !ACTIVE_AUDIO_NODE_STORE.has(audioNode);\n};\n//# sourceMappingURL=is-passive-audio-node.js.map","export const testAudioNodeDisconnectMethodSupport = (nativeAudioContext, nativeAudioWorkletNodeConstructor) => {\n return new Promise((resolve) => {\n /*\n * This bug existed in Safari up until v14.0.2. Since AudioWorklets were not supported in Safari until v14.1 the presence of the\n * constructor for an AudioWorkletNode can be used here to skip the test.\n */\n if (nativeAudioWorkletNodeConstructor !== null) {\n resolve(true);\n }\n else {\n const analyzer = nativeAudioContext.createScriptProcessor(256, 1, 1); // tslint:disable-line deprecation\n const dummy = nativeAudioContext.createGain();\n // Bug #95: Safari does not play one sample buffers.\n const ones = nativeAudioContext.createBuffer(1, 2, 44100);\n const channelData = ones.getChannelData(0);\n channelData[0] = 1;\n channelData[1] = 1;\n const source = nativeAudioContext.createBufferSource();\n source.buffer = ones;\n source.loop = true;\n source.connect(analyzer).connect(nativeAudioContext.destination);\n source.connect(dummy);\n source.disconnect(dummy);\n // tslint:disable-next-line:deprecation\n analyzer.onaudioprocess = (event) => {\n const chnnlDt = event.inputBuffer.getChannelData(0); // tslint:disable-line deprecation\n if (Array.prototype.some.call(chnnlDt, (sample) => sample === 1)) {\n resolve(true);\n }\n else {\n resolve(false);\n }\n source.stop();\n analyzer.onaudioprocess = null; // tslint:disable-line:deprecation\n source.disconnect(analyzer);\n analyzer.disconnect(nativeAudioContext.destination);\n };\n source.start();\n }\n });\n};\n//# sourceMappingURL=test-audio-node-disconnect-method-support.js.map","export const visitEachAudioNodeOnce = (cycles, visitor) => {\n const counts = new Map();\n for (const cycle of cycles) {\n for (const audioNode of cycle) {\n const count = counts.get(audioNode);\n counts.set(audioNode, count === undefined ? 1 : count + 1);\n }\n }\n counts.forEach((count, audioNode) => visitor(audioNode, count));\n};\n//# sourceMappingURL=visit-each-audio-node-once.js.map","export const isNativeAudioNode = (nativeAudioNodeOrAudioParam) => {\n return 'context' in nativeAudioNodeOrAudioParam;\n};\n//# sourceMappingURL=native-audio-node.js.map","import { isNativeAudioNode } from '../guards/native-audio-node';\nexport const wrapAudioNodeDisconnectMethod = (nativeAudioNode) => {\n const connections = new Map();\n nativeAudioNode.connect = ((connect) => {\n // tslint:disable-next-line:invalid-void no-inferrable-types\n return (destination, output = 0, input = 0) => {\n const returnValue = isNativeAudioNode(destination) ? connect(destination, output, input) : connect(destination, output);\n // Save the new connection only if the calls to connect above didn't throw an error.\n const connectionsToDestination = connections.get(destination);\n if (connectionsToDestination === undefined) {\n connections.set(destination, [{ input, output }]);\n }\n else {\n if (connectionsToDestination.every((connection) => connection.input !== input || connection.output !== output)) {\n connectionsToDestination.push({ input, output });\n }\n }\n return returnValue;\n };\n })(nativeAudioNode.connect.bind(nativeAudioNode));\n nativeAudioNode.disconnect = ((disconnect) => {\n return (destinationOrOutput, output, input) => {\n disconnect.apply(nativeAudioNode);\n if (destinationOrOutput === undefined) {\n connections.clear();\n }\n else if (typeof destinationOrOutput === 'number') {\n for (const [destination, connectionsToDestination] of connections) {\n const filteredConnections = connectionsToDestination.filter((connection) => connection.output !== destinationOrOutput);\n if (filteredConnections.length === 0) {\n connections.delete(destination);\n }\n else {\n connections.set(destination, filteredConnections);\n }\n }\n }\n else if (connections.has(destinationOrOutput)) {\n if (output === undefined) {\n connections.delete(destinationOrOutput);\n }\n else {\n const connectionsToDestination = connections.get(destinationOrOutput);\n if (connectionsToDestination !== undefined) {\n const filteredConnections = connectionsToDestination.filter((connection) => connection.output !== output && (connection.input !== input || input === undefined));\n if (filteredConnections.length === 0) {\n connections.delete(destinationOrOutput);\n }\n else {\n connections.set(destinationOrOutput, filteredConnections);\n }\n }\n }\n }\n for (const [destination, connectionsToDestination] of connections) {\n connectionsToDestination.forEach((connection) => {\n if (isNativeAudioNode(destination)) {\n nativeAudioNode.connect(destination, connection.output, connection.input);\n }\n else {\n nativeAudioNode.connect(destination, connection.output);\n }\n });\n }\n };\n })(nativeAudioNode.disconnect);\n};\n//# sourceMappingURL=wrap-audio-node-disconnect-method.js.map","import { AUDIO_NODE_STORE, EVENT_LISTENERS } from '../globals';\nimport { isAudioNode } from '../guards/audio-node';\nimport { isAudioNodeOutputConnection } from '../guards/audio-node-output-connection';\nimport { addActiveInputConnectionToAudioParam } from '../helpers/add-active-input-connection-to-audio-param';\nimport { addPassiveInputConnectionToAudioParam } from '../helpers/add-passive-input-connection-to-audio-param';\nimport { connectNativeAudioNodeToNativeAudioNode } from '../helpers/connect-native-audio-node-to-native-audio-node';\nimport { deleteActiveInputConnection } from '../helpers/delete-active-input-connection';\nimport { deleteActiveInputConnectionToAudioParam } from '../helpers/delete-active-input-connection-to-audio-param';\nimport { deleteEventListenerOfAudioNode } from '../helpers/delete-event-listeners-of-audio-node';\nimport { deletePassiveInputConnectionToAudioNode } from '../helpers/delete-passive-input-connection-to-audio-node';\nimport { deletePassiveInputConnectionToAudioParam } from '../helpers/delete-passive-input-connection-to-audio-param';\nimport { disconnectNativeAudioNodeFromNativeAudioNode } from '../helpers/disconnect-native-audio-node-from-native-audio-node';\nimport { getAudioNodeConnections } from '../helpers/get-audio-node-connections';\nimport { getAudioParamConnections } from '../helpers/get-audio-param-connections';\nimport { getEventListenersOfAudioNode } from '../helpers/get-event-listeners-of-audio-node';\nimport { getNativeAudioNode } from '../helpers/get-native-audio-node';\nimport { getNativeAudioParam } from '../helpers/get-native-audio-param';\nimport { insertElementInSet } from '../helpers/insert-element-in-set';\nimport { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { isPartOfACycle } from '../helpers/is-part-of-a-cycle';\nimport { isPassiveAudioNode } from '../helpers/is-passive-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassiveWhenNecessary } from '../helpers/set-internal-state-to-passive-when-necessary';\nimport { testAudioNodeDisconnectMethodSupport } from '../helpers/test-audio-node-disconnect-method-support';\nimport { visitEachAudioNodeOnce } from '../helpers/visit-each-audio-node-once';\nimport { wrapAudioNodeDisconnectMethod } from '../helpers/wrap-audio-node-disconnect-method';\nconst addConnectionToAudioParamOfAudioContext = (source, destination, output, isOffline) => {\n const { activeInputs, passiveInputs } = getAudioParamConnections(destination);\n const { outputs } = getAudioNodeConnections(source);\n const eventListeners = getEventListenersOfAudioNode(source);\n const eventListener = (isActive) => {\n const nativeAudioNode = getNativeAudioNode(source);\n const nativeAudioParam = getNativeAudioParam(destination);\n if (isActive) {\n const partialConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output);\n addActiveInputConnectionToAudioParam(activeInputs, source, partialConnection, false);\n if (!isOffline && !isPartOfACycle(source)) {\n nativeAudioNode.connect(nativeAudioParam, output);\n }\n }\n else {\n const partialConnection = deleteActiveInputConnectionToAudioParam(activeInputs, source, output);\n addPassiveInputConnectionToAudioParam(passiveInputs, partialConnection, false);\n if (!isOffline && !isPartOfACycle(source)) {\n nativeAudioNode.disconnect(nativeAudioParam, output);\n }\n }\n };\n if (insertElementInSet(outputs, [destination, output], (outputConnection) => outputConnection[0] === destination && outputConnection[1] === output, true)) {\n eventListeners.add(eventListener);\n if (isActiveAudioNode(source)) {\n addActiveInputConnectionToAudioParam(activeInputs, source, [output, eventListener], true);\n }\n else {\n addPassiveInputConnectionToAudioParam(passiveInputs, [source, output, eventListener], true);\n }\n return true;\n }\n return false;\n};\nconst deleteInputConnectionOfAudioNode = (source, destination, output, input) => {\n const { activeInputs, passiveInputs } = getAudioNodeConnections(destination);\n const activeInputConnection = deleteActiveInputConnection(activeInputs[input], source, output);\n if (activeInputConnection === null) {\n const passiveInputConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input);\n return [passiveInputConnection[2], false];\n }\n return [activeInputConnection[2], true];\n};\nconst deleteInputConnectionOfAudioParam = (source, destination, output) => {\n const { activeInputs, passiveInputs } = getAudioParamConnections(destination);\n const activeInputConnection = deleteActiveInputConnection(activeInputs, source, output);\n if (activeInputConnection === null) {\n const passiveInputConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output);\n return [passiveInputConnection[1], false];\n }\n return [activeInputConnection[2], true];\n};\nconst deleteInputsOfAudioNode = (source, isOffline, destination, output, input) => {\n const [listener, isActive] = deleteInputConnectionOfAudioNode(source, destination, output, input);\n if (listener !== null) {\n deleteEventListenerOfAudioNode(source, listener);\n if (isActive && !isOffline && !isPartOfACycle(source)) {\n disconnectNativeAudioNodeFromNativeAudioNode(getNativeAudioNode(source), getNativeAudioNode(destination), output, input);\n }\n }\n if (isActiveAudioNode(destination)) {\n const { activeInputs } = getAudioNodeConnections(destination);\n setInternalStateToPassiveWhenNecessary(destination, activeInputs);\n }\n};\nconst deleteInputsOfAudioParam = (source, isOffline, destination, output) => {\n const [listener, isActive] = deleteInputConnectionOfAudioParam(source, destination, output);\n if (listener !== null) {\n deleteEventListenerOfAudioNode(source, listener);\n if (isActive && !isOffline && !isPartOfACycle(source)) {\n getNativeAudioNode(source).disconnect(getNativeAudioParam(destination), output);\n }\n }\n};\nconst deleteAnyConnection = (source, isOffline) => {\n const audioNodeConnectionsOfSource = getAudioNodeConnections(source);\n const destinations = [];\n for (const outputConnection of audioNodeConnectionsOfSource.outputs) {\n if (isAudioNodeOutputConnection(outputConnection)) {\n deleteInputsOfAudioNode(source, isOffline, ...outputConnection);\n }\n else {\n deleteInputsOfAudioParam(source, isOffline, ...outputConnection);\n }\n destinations.push(outputConnection[0]);\n }\n audioNodeConnectionsOfSource.outputs.clear();\n return destinations;\n};\nconst deleteConnectionAtOutput = (source, isOffline, output) => {\n const audioNodeConnectionsOfSource = getAudioNodeConnections(source);\n const destinations = [];\n for (const outputConnection of audioNodeConnectionsOfSource.outputs) {\n if (outputConnection[1] === output) {\n if (isAudioNodeOutputConnection(outputConnection)) {\n deleteInputsOfAudioNode(source, isOffline, ...outputConnection);\n }\n else {\n deleteInputsOfAudioParam(source, isOffline, ...outputConnection);\n }\n destinations.push(outputConnection[0]);\n audioNodeConnectionsOfSource.outputs.delete(outputConnection);\n }\n }\n return destinations;\n};\nconst deleteConnectionToDestination = (source, isOffline, destination, output, input) => {\n const audioNodeConnectionsOfSource = getAudioNodeConnections(source);\n return Array.from(audioNodeConnectionsOfSource.outputs)\n .filter((outputConnection) => outputConnection[0] === destination &&\n (output === undefined || outputConnection[1] === output) &&\n (input === undefined || outputConnection[2] === input))\n .map((outputConnection) => {\n if (isAudioNodeOutputConnection(outputConnection)) {\n deleteInputsOfAudioNode(source, isOffline, ...outputConnection);\n }\n else {\n deleteInputsOfAudioParam(source, isOffline, ...outputConnection);\n }\n audioNodeConnectionsOfSource.outputs.delete(outputConnection);\n return outputConnection[0];\n });\n};\nexport const createAudioNodeConstructor = (addAudioNodeConnections, addConnectionToAudioNode, cacheTestResult, createIncrementCycleCounter, createIndexSizeError, createInvalidAccessError, createNotSupportedError, decrementCycleCounter, detectCycles, eventTargetConstructor, getNativeContext, isNativeAudioContext, isNativeAudioNode, isNativeAudioParam, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor) => {\n return class AudioNode extends eventTargetConstructor {\n constructor(context, isActive, nativeAudioNode, audioNodeRenderer) {\n super(nativeAudioNode);\n this._context = context;\n this._nativeAudioNode = nativeAudioNode;\n const nativeContext = getNativeContext(context);\n // Bug #12: Safari does not support to disconnect a specific destination.\n if (isNativeAudioContext(nativeContext) &&\n true !==\n cacheTestResult(testAudioNodeDisconnectMethodSupport, () => {\n return testAudioNodeDisconnectMethodSupport(nativeContext, nativeAudioWorkletNodeConstructor);\n })) {\n wrapAudioNodeDisconnectMethod(nativeAudioNode);\n }\n AUDIO_NODE_STORE.set(this, nativeAudioNode);\n EVENT_LISTENERS.set(this, new Set());\n if (context.state !== 'closed' && isActive) {\n setInternalStateToActive(this);\n }\n addAudioNodeConnections(this, audioNodeRenderer, nativeAudioNode);\n }\n get channelCount() {\n return this._nativeAudioNode.channelCount;\n }\n set channelCount(value) {\n this._nativeAudioNode.channelCount = value;\n }\n get channelCountMode() {\n return this._nativeAudioNode.channelCountMode;\n }\n set channelCountMode(value) {\n this._nativeAudioNode.channelCountMode = value;\n }\n get channelInterpretation() {\n return this._nativeAudioNode.channelInterpretation;\n }\n set channelInterpretation(value) {\n this._nativeAudioNode.channelInterpretation = value;\n }\n get context() {\n return this._context;\n }\n get numberOfInputs() {\n return this._nativeAudioNode.numberOfInputs;\n }\n get numberOfOutputs() {\n return this._nativeAudioNode.numberOfOutputs;\n }\n // tslint:disable-next-line:invalid-void\n connect(destination, output = 0, input = 0) {\n // Bug #174: Safari does expose a wrong numberOfOutputs for MediaStreamAudioDestinationNodes.\n if (output < 0 || output >= this._nativeAudioNode.numberOfOutputs) {\n throw createIndexSizeError();\n }\n const nativeContext = getNativeContext(this._context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n if (isNativeAudioNode(destination) || isNativeAudioParam(destination)) {\n throw createInvalidAccessError();\n }\n if (isAudioNode(destination)) {\n const nativeDestinationAudioNode = getNativeAudioNode(destination);\n try {\n const connection = connectNativeAudioNodeToNativeAudioNode(this._nativeAudioNode, nativeDestinationAudioNode, output, input);\n const isPassive = isPassiveAudioNode(this);\n if (isOffline || isPassive) {\n this._nativeAudioNode.disconnect(...connection);\n }\n if (this.context.state !== 'closed' && !isPassive && isPassiveAudioNode(destination)) {\n setInternalStateToActive(destination);\n }\n }\n catch (err) {\n // Bug #41: Safari does not throw the correct exception so far.\n if (err.code === 12) {\n throw createInvalidAccessError();\n }\n throw err;\n }\n const isNewConnectionToAudioNode = addConnectionToAudioNode(this, destination, output, input, isOffline);\n // Bug #164: Only Firefox detects cycles so far.\n if (isNewConnectionToAudioNode) {\n const cycles = detectCycles([this], destination);\n visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline));\n }\n return destination;\n }\n const nativeAudioParam = getNativeAudioParam(destination);\n /*\n * Bug #73, #147 & #153: Safari does not support to connect an input signal to the playbackRate AudioParam of an\n * AudioBufferSourceNode. This can't be easily detected and that's why the outdated name property is used here to identify\n * Safari. In addition to that the maxValue property is used to only detect the affected versions below v14.0.2.\n */\n if (nativeAudioParam.name === 'playbackRate' && nativeAudioParam.maxValue === 1024) {\n throw createNotSupportedError();\n }\n try {\n this._nativeAudioNode.connect(nativeAudioParam, output);\n if (isOffline || isPassiveAudioNode(this)) {\n this._nativeAudioNode.disconnect(nativeAudioParam, output);\n }\n }\n catch (err) {\n // Bug #58: Safari doesn't throw an InvalidAccessError yet.\n if (err.code === 12) {\n throw createInvalidAccessError();\n }\n throw err;\n }\n const isNewConnectionToAudioParam = addConnectionToAudioParamOfAudioContext(this, destination, output, isOffline);\n // Bug #164: Only Firefox detects cycles so far.\n if (isNewConnectionToAudioParam) {\n const cycles = detectCycles([this], destination);\n visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline));\n }\n }\n disconnect(destinationOrOutput, output, input) {\n let destinations;\n const nativeContext = getNativeContext(this._context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n if (destinationOrOutput === undefined) {\n destinations = deleteAnyConnection(this, isOffline);\n }\n else if (typeof destinationOrOutput === 'number') {\n if (destinationOrOutput < 0 || destinationOrOutput >= this.numberOfOutputs) {\n throw createIndexSizeError();\n }\n destinations = deleteConnectionAtOutput(this, isOffline, destinationOrOutput);\n }\n else {\n if (output !== undefined && (output < 0 || output >= this.numberOfOutputs)) {\n throw createIndexSizeError();\n }\n if (isAudioNode(destinationOrOutput) && input !== undefined && (input < 0 || input >= destinationOrOutput.numberOfInputs)) {\n throw createIndexSizeError();\n }\n destinations = deleteConnectionToDestination(this, isOffline, destinationOrOutput, output, input);\n if (destinations.length === 0) {\n throw createInvalidAccessError();\n }\n }\n // Bug #164: Only Firefox detects cycles so far.\n for (const destination of destinations) {\n const cycles = detectCycles([this], destination);\n visitEachAudioNodeOnce(cycles, decrementCycleCounter);\n }\n }\n };\n};\n//# sourceMappingURL=audio-node-constructor.js.map","import { AutomationEventList } from 'automation-events';\nexport const createAudioParamFactory = (addAudioParamConnections, audioParamAudioNodeStore, audioParamStore, createAudioParamRenderer, createCancelAndHoldAutomationEvent, createCancelScheduledValuesAutomationEvent, createExponentialRampToValueAutomationEvent, createLinearRampToValueAutomationEvent, createSetTargetAutomationEvent, createSetValueAutomationEvent, createSetValueCurveAutomationEvent, nativeAudioContextConstructor, setValueAtTimeUntilPossible) => {\n return (audioNode, isAudioParamOfOfflineAudioContext, nativeAudioParam, maxValue = null, minValue = null) => {\n const automationEventList = new AutomationEventList(nativeAudioParam.defaultValue);\n const audioParamRenderer = isAudioParamOfOfflineAudioContext ? createAudioParamRenderer(automationEventList) : null;\n const audioParam = {\n get defaultValue() {\n return nativeAudioParam.defaultValue;\n },\n get maxValue() {\n return maxValue === null ? nativeAudioParam.maxValue : maxValue;\n },\n get minValue() {\n return minValue === null ? nativeAudioParam.minValue : minValue;\n },\n get value() {\n return nativeAudioParam.value;\n },\n set value(value) {\n nativeAudioParam.value = value;\n // Bug #98: Firefox & Safari do not yet treat the value setter like a call to setValueAtTime().\n audioParam.setValueAtTime(value, audioNode.context.currentTime);\n },\n cancelAndHoldAtTime(cancelTime) {\n // Bug #28: Firefox & Safari do not yet implement cancelAndHoldAtTime().\n if (typeof nativeAudioParam.cancelAndHoldAtTime === 'function') {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createCancelAndHoldAutomationEvent(cancelTime));\n nativeAudioParam.cancelAndHoldAtTime(cancelTime);\n }\n else {\n const previousLastEvent = Array.from(automationEventList).pop();\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createCancelAndHoldAutomationEvent(cancelTime));\n const currentLastEvent = Array.from(automationEventList).pop();\n nativeAudioParam.cancelScheduledValues(cancelTime);\n if (previousLastEvent !== currentLastEvent && currentLastEvent !== undefined) {\n if (currentLastEvent.type === 'exponentialRampToValue') {\n nativeAudioParam.exponentialRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime);\n }\n else if (currentLastEvent.type === 'linearRampToValue') {\n nativeAudioParam.linearRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime);\n }\n else if (currentLastEvent.type === 'setValue') {\n nativeAudioParam.setValueAtTime(currentLastEvent.value, currentLastEvent.startTime);\n }\n else if (currentLastEvent.type === 'setValueCurve') {\n nativeAudioParam.setValueCurveAtTime(currentLastEvent.values, currentLastEvent.startTime, currentLastEvent.duration);\n }\n }\n }\n return audioParam;\n },\n cancelScheduledValues(cancelTime) {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createCancelScheduledValuesAutomationEvent(cancelTime));\n nativeAudioParam.cancelScheduledValues(cancelTime);\n return audioParam;\n },\n exponentialRampToValueAtTime(value, endTime) {\n // Bug #45: Safari does not throw an error yet.\n if (value === 0) {\n throw new RangeError();\n }\n // Bug #187: Safari does not throw an error yet.\n if (!Number.isFinite(endTime) || endTime < 0) {\n throw new RangeError();\n }\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createExponentialRampToValueAutomationEvent(value, endTime));\n nativeAudioParam.exponentialRampToValueAtTime(value, endTime);\n return audioParam;\n },\n linearRampToValueAtTime(value, endTime) {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createLinearRampToValueAutomationEvent(value, endTime));\n nativeAudioParam.linearRampToValueAtTime(value, endTime);\n return audioParam;\n },\n setTargetAtTime(target, startTime, timeConstant) {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createSetTargetAutomationEvent(target, startTime, timeConstant));\n nativeAudioParam.setTargetAtTime(target, startTime, timeConstant);\n return audioParam;\n },\n setValueAtTime(value, startTime) {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createSetValueAutomationEvent(value, startTime));\n nativeAudioParam.setValueAtTime(value, startTime);\n return audioParam;\n },\n setValueCurveAtTime(values, startTime, duration) {\n // Bug 183: Safari only accepts a Float32Array.\n const convertedValues = values instanceof Float32Array ? values : new Float32Array(values);\n /*\n * Bug #152: Safari does not correctly interpolate the values of the curve.\n * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the\n * existence of the webkitAudioContext is used as a workaround here.\n */\n if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext') {\n const endTime = startTime + duration;\n const sampleRate = audioNode.context.sampleRate;\n const firstSample = Math.ceil(startTime * sampleRate);\n const lastSample = Math.floor(endTime * sampleRate);\n const numberOfInterpolatedValues = lastSample - firstSample;\n const interpolatedValues = new Float32Array(numberOfInterpolatedValues);\n for (let i = 0; i < numberOfInterpolatedValues; i += 1) {\n const theoreticIndex = ((convertedValues.length - 1) / duration) * ((firstSample + i) / sampleRate - startTime);\n const lowerIndex = Math.floor(theoreticIndex);\n const upperIndex = Math.ceil(theoreticIndex);\n interpolatedValues[i] =\n lowerIndex === upperIndex\n ? convertedValues[lowerIndex]\n : (1 - (theoreticIndex - lowerIndex)) * convertedValues[lowerIndex] +\n (1 - (upperIndex - theoreticIndex)) * convertedValues[upperIndex];\n }\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createSetValueCurveAutomationEvent(interpolatedValues, startTime, duration));\n nativeAudioParam.setValueCurveAtTime(interpolatedValues, startTime, duration);\n const timeOfLastSample = lastSample / sampleRate;\n if (timeOfLastSample < endTime) {\n setValueAtTimeUntilPossible(audioParam, interpolatedValues[interpolatedValues.length - 1], timeOfLastSample);\n }\n setValueAtTimeUntilPossible(audioParam, convertedValues[convertedValues.length - 1], endTime);\n }\n else {\n if (audioParamRenderer === null) {\n automationEventList.flush(audioNode.context.currentTime);\n }\n automationEventList.add(createSetValueCurveAutomationEvent(convertedValues, startTime, duration));\n nativeAudioParam.setValueCurveAtTime(convertedValues, startTime, duration);\n }\n return audioParam;\n }\n };\n audioParamStore.set(audioParam, nativeAudioParam);\n audioParamAudioNodeStore.set(audioParam, audioNode);\n addAudioParamConnections(audioParam, audioParamRenderer);\n return audioParam;\n };\n};\n//# sourceMappingURL=audio-param-factory.js.map","export const createAudioParamRenderer = (automationEventList) => {\n return {\n replay(audioParam) {\n for (const automationEvent of automationEventList) {\n if (automationEvent.type === 'exponentialRampToValue') {\n const { endTime, value } = automationEvent;\n audioParam.exponentialRampToValueAtTime(value, endTime);\n }\n else if (automationEvent.type === 'linearRampToValue') {\n const { endTime, value } = automationEvent;\n audioParam.linearRampToValueAtTime(value, endTime);\n }\n else if (automationEvent.type === 'setTarget') {\n const { startTime, target, timeConstant } = automationEvent;\n audioParam.setTargetAtTime(target, startTime, timeConstant);\n }\n else if (automationEvent.type === 'setValue') {\n const { startTime, value } = automationEvent;\n audioParam.setValueAtTime(value, startTime);\n }\n else if (automationEvent.type === 'setValueCurve') {\n const { duration, startTime, values } = automationEvent;\n audioParam.setValueCurveAtTime(values, startTime, duration);\n }\n else {\n throw new Error(\"Can't apply an unknown automation.\");\n }\n }\n }\n };\n};\n//# sourceMappingURL=audio-param-renderer.js.map","export class ReadOnlyMap {\n constructor(parameters) {\n this._map = new Map(parameters);\n }\n get size() {\n return this._map.size;\n }\n entries() {\n return this._map.entries();\n }\n forEach(callback, thisArg = null) {\n return this._map.forEach((value, key) => callback.call(thisArg, value, key, this));\n }\n get(name) {\n return this._map.get(name);\n }\n has(name) {\n return this._map.has(name);\n }\n keys() {\n return this._map.keys();\n }\n values() {\n return this._map.values();\n }\n}\n//# sourceMappingURL=read-only-map.js.map","import { NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS } from '../globals';\nimport { ReadOnlyMap } from '../read-only-map';\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n // Bug #61: The channelCountMode should be 'max' according to the spec but is set to 'explicit' to achieve consistent behavior.\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 1,\n numberOfOutputs: 1,\n parameterData: {},\n processorOptions: {}\n};\nexport const createAudioWorkletNodeConstructor = (addUnrenderedAudioWorkletNode, audioNodeConstructor, createAudioParam, createAudioWorkletNodeRenderer, createNativeAudioWorkletNode, getAudioNodeConnections, getBackupOfflineAudioContext, getNativeContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, sanitizeAudioWorkletNodeOptions, setActiveAudioWorkletNodeInputs, testAudioWorkletNodeOptionsClonability, wrapEventListener) => {\n return class AudioWorkletNode extends audioNodeConstructor {\n constructor(context, name, options) {\n var _a;\n const nativeContext = getNativeContext(context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const mergedOptions = sanitizeAudioWorkletNodeOptions({ ...DEFAULT_OPTIONS, ...options });\n // Bug #191: Safari doesn't throw an error if the options aren't clonable.\n testAudioWorkletNodeOptionsClonability(mergedOptions);\n const nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext);\n const processorConstructor = nodeNameToProcessorConstructorMap === null || nodeNameToProcessorConstructorMap === void 0 ? void 0 : nodeNameToProcessorConstructorMap.get(name);\n // Bug #186: Chrome and Edge do not allow to create an AudioWorkletNode on a closed AudioContext.\n const nativeContextOrBackupOfflineAudioContext = isOffline || nativeContext.state !== 'closed'\n ? nativeContext\n : (_a = getBackupOfflineAudioContext(nativeContext)) !== null && _a !== void 0 ? _a : nativeContext;\n const nativeAudioWorkletNode = createNativeAudioWorkletNode(nativeContextOrBackupOfflineAudioContext, isOffline ? null : context.baseLatency, nativeAudioWorkletNodeConstructor, name, processorConstructor, mergedOptions);\n const audioWorkletNodeRenderer = ((isOffline ? createAudioWorkletNodeRenderer(name, mergedOptions, processorConstructor) : null));\n /*\n * @todo Add a mechanism to switch an AudioWorkletNode to passive once the process() function of the AudioWorkletProcessor\n * returns false.\n */\n super(context, true, nativeAudioWorkletNode, audioWorkletNodeRenderer);\n const parameters = [];\n nativeAudioWorkletNode.parameters.forEach((nativeAudioParam, nm) => {\n const audioParam = createAudioParam(this, isOffline, nativeAudioParam);\n parameters.push([nm, audioParam]);\n });\n this._nativeAudioWorkletNode = nativeAudioWorkletNode;\n this._onprocessorerror = null;\n this._parameters = new ReadOnlyMap(parameters);\n /*\n * Bug #86 & #87: Invoking the renderer of an AudioWorkletNode might be necessary if it has no direct or indirect connection to\n * the destination.\n */\n if (isOffline) {\n addUnrenderedAudioWorkletNode(nativeContext, this);\n }\n const { activeInputs } = getAudioNodeConnections(this);\n setActiveAudioWorkletNodeInputs(nativeAudioWorkletNode, activeInputs);\n }\n get onprocessorerror() {\n return this._onprocessorerror;\n }\n set onprocessorerror(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n this._nativeAudioWorkletNode.onprocessorerror = wrappedListener;\n const nativeOnProcessorError = this._nativeAudioWorkletNode.onprocessorerror;\n this._onprocessorerror =\n nativeOnProcessorError !== null && nativeOnProcessorError === wrappedListener\n ? value\n : nativeOnProcessorError;\n }\n get parameters() {\n if (this._parameters === null) {\n // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.\n return this._nativeAudioWorkletNode.parameters;\n }\n return this._parameters;\n }\n get port() {\n return this._nativeAudioWorkletNode.port;\n }\n };\n};\n//# sourceMappingURL=audio-worklet-node-constructor.js.map","export function copyFromChannel(audioBuffer, \n// @todo There is currently no way to define something like { [ key: number | string ]: Float32Array }\nparent, key, channelNumber, bufferOffset) {\n if (typeof audioBuffer.copyFromChannel === 'function') {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength === 0) {\n parent[key] = new Float32Array(128);\n }\n audioBuffer.copyFromChannel(parent[key], channelNumber, bufferOffset);\n // Bug #5: Safari does not support copyFromChannel().\n }\n else {\n const channelData = audioBuffer.getChannelData(channelNumber);\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength === 0) {\n parent[key] = channelData.slice(bufferOffset, bufferOffset + 128);\n }\n else {\n const slicedInput = new Float32Array(channelData.buffer, bufferOffset * Float32Array.BYTES_PER_ELEMENT, 128);\n parent[key].set(slicedInput);\n }\n }\n}\n//# sourceMappingURL=copy-from-channel.js.map","export const copyToChannel = (audioBuffer, parent, key, channelNumber, bufferOffset) => {\n if (typeof audioBuffer.copyToChannel === 'function') {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength !== 0) {\n audioBuffer.copyToChannel(parent[key], channelNumber, bufferOffset);\n }\n // Bug #5: Safari does not support copyToChannel().\n }\n else {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (parent[key].byteLength !== 0) {\n audioBuffer.getChannelData(channelNumber).set(parent[key], bufferOffset);\n }\n }\n};\n//# sourceMappingURL=copy-to-channel.js.map","export const createNestedArrays = (x, y) => {\n const arrays = [];\n for (let i = 0; i < x; i += 1) {\n const array = [];\n const length = typeof y === 'number' ? y : y[i];\n for (let j = 0; j < length; j += 1) {\n array.push(new Float32Array(128));\n }\n arrays.push(array);\n }\n return arrays;\n};\n//# sourceMappingURL=create-nested-arrays.js.map","import { NODE_TO_PROCESSOR_MAPS } from '../globals';\nimport { getNativeAudioNode } from './get-native-audio-node';\nimport { getValueForKey } from './get-value-for-key';\nexport const getAudioWorkletProcessor = (nativeOfflineAudioContext, proxy) => {\n const nodeToProcessorMap = getValueForKey(NODE_TO_PROCESSOR_MAPS, nativeOfflineAudioContext);\n const nativeAudioWorkletNode = getNativeAudioNode(proxy);\n return getValueForKey(nodeToProcessorMap, nativeAudioWorkletNode);\n};\n//# sourceMappingURL=get-audio-worklet-processor.js.map","import { copyFromChannel } from '../helpers/copy-from-channel';\nimport { copyToChannel } from '../helpers/copy-to-channel';\nimport { createNestedArrays } from '../helpers/create-nested-arrays';\nimport { getAudioNodeConnections } from '../helpers/get-audio-node-connections';\nimport { getAudioWorkletProcessor } from '../helpers/get-audio-worklet-processor';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nconst processBuffer = async (proxy, renderedBuffer, nativeOfflineAudioContext, options, outputChannelCount, processorConstructor, exposeCurrentFrameAndCurrentTime) => {\n // Ceil the length to the next full render quantum.\n // Bug #17: Safari does not yet expose the length.\n const length = renderedBuffer === null ? Math.ceil(proxy.context.length / 128) * 128 : renderedBuffer.length;\n const numberOfInputChannels = options.channelCount * options.numberOfInputs;\n const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0);\n const processedBuffer = numberOfOutputChannels === 0\n ? null\n : nativeOfflineAudioContext.createBuffer(numberOfOutputChannels, length, nativeOfflineAudioContext.sampleRate);\n if (processorConstructor === undefined) {\n throw new Error('Missing the processor constructor.');\n }\n const audioNodeConnections = getAudioNodeConnections(proxy);\n const audioWorkletProcessor = await getAudioWorkletProcessor(nativeOfflineAudioContext, proxy);\n const inputs = createNestedArrays(options.numberOfInputs, options.channelCount);\n const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount);\n const parameters = Array.from(proxy.parameters.keys()).reduce((prmtrs, name) => ({ ...prmtrs, [name]: new Float32Array(128) }), {});\n for (let i = 0; i < length; i += 128) {\n if (options.numberOfInputs > 0 && renderedBuffer !== null) {\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < options.channelCount; k += 1) {\n copyFromChannel(renderedBuffer, inputs[j], k, k, i);\n }\n }\n }\n if (processorConstructor.parameterDescriptors !== undefined && renderedBuffer !== null) {\n processorConstructor.parameterDescriptors.forEach(({ name }, index) => {\n copyFromChannel(renderedBuffer, parameters, name, numberOfInputChannels + index, i);\n });\n }\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (outputs[j][k].byteLength === 0) {\n outputs[j][k] = new Float32Array(128);\n }\n }\n }\n try {\n const potentiallyEmptyInputs = inputs.map((input, index) => {\n if (audioNodeConnections.activeInputs[index].size === 0) {\n return [];\n }\n return input;\n });\n const activeSourceFlag = exposeCurrentFrameAndCurrentTime(i / nativeOfflineAudioContext.sampleRate, nativeOfflineAudioContext.sampleRate, () => audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters));\n if (processedBuffer !== null) {\n for (let j = 0, outputChannelSplitterNodeOutput = 0; j < options.numberOfOutputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n copyToChannel(processedBuffer, outputs[j], k, outputChannelSplitterNodeOutput + k, i);\n }\n outputChannelSplitterNodeOutput += outputChannelCount[j];\n }\n }\n if (!activeSourceFlag) {\n break;\n }\n }\n catch (error) {\n proxy.dispatchEvent(new ErrorEvent('processorerror', {\n colno: error.colno,\n filename: error.filename,\n lineno: error.lineno,\n message: error.message\n }));\n break;\n }\n }\n return processedBuffer;\n};\nexport const createAudioWorkletNodeRendererFactory = (connectAudioParam, connectMultipleOutputs, createNativeAudioBufferSourceNode, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, deleteUnrenderedAudioWorkletNode, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getNativeAudioNode, nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext) => {\n return (name, options, processorConstructor) => {\n const renderedNativeAudioNodes = new WeakMap();\n let processedBufferPromise = null;\n const createAudioNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeAudioWorkletNode = getNativeAudioNode(proxy);\n let nativeOutputNodes = null;\n const nativeAudioWorkletNodeIsOwnedByContext = isOwnedByContext(nativeAudioWorkletNode, nativeOfflineAudioContext);\n const outputChannelCount = Array.isArray(options.outputChannelCount)\n ? options.outputChannelCount\n : Array.from(options.outputChannelCount);\n // Bug #61: Only Chrome, Edge & Firefox have an implementation of the AudioWorkletNode yet.\n if (nativeAudioWorkletNodeConstructor === null) {\n const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0);\n const outputChannelSplitterNode = createNativeChannelSplitterNode(nativeOfflineAudioContext, {\n channelCount: Math.max(1, numberOfOutputChannels),\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: Math.max(1, numberOfOutputChannels)\n });\n const outputChannelMergerNodes = [];\n for (let i = 0; i < proxy.numberOfOutputs; i += 1) {\n outputChannelMergerNodes.push(createNativeChannelMergerNode(nativeOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: outputChannelCount[i]\n }));\n }\n const outputGainNode = createNativeGainNode(nativeOfflineAudioContext, {\n channelCount: options.channelCount,\n channelCountMode: options.channelCountMode,\n channelInterpretation: options.channelInterpretation,\n gain: 1\n });\n outputGainNode.connect = connectMultipleOutputs.bind(null, outputChannelMergerNodes);\n outputGainNode.disconnect = disconnectMultipleOutputs.bind(null, outputChannelMergerNodes);\n nativeOutputNodes = [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode];\n }\n else if (!nativeAudioWorkletNodeIsOwnedByContext) {\n nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor(nativeOfflineAudioContext, name);\n }\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeOutputNodes === null ? nativeAudioWorkletNode : nativeOutputNodes[2]);\n if (nativeOutputNodes !== null) {\n if (processedBufferPromise === null) {\n if (processorConstructor === undefined) {\n throw new Error('Missing the processor constructor.');\n }\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n // Bug #47: The AudioDestinationNode in Safari gets not initialized correctly.\n const numberOfInputChannels = proxy.channelCount * proxy.numberOfInputs;\n const numberOfParameters = processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length;\n const numberOfChannels = numberOfInputChannels + numberOfParameters;\n const renderBuffer = async () => {\n const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(numberOfChannels, \n // Ceil the length to the next full render quantum.\n // Bug #17: Safari does not yet expose the length.\n Math.ceil(proxy.context.length / 128) * 128, nativeOfflineAudioContext.sampleRate);\n const gainNodes = [];\n const inputChannelSplitterNodes = [];\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes.push(createNativeGainNode(partialOfflineAudioContext, {\n channelCount: options.channelCount,\n channelCountMode: options.channelCountMode,\n channelInterpretation: options.channelInterpretation,\n gain: 1\n }));\n inputChannelSplitterNodes.push(createNativeChannelSplitterNode(partialOfflineAudioContext, {\n channelCount: options.channelCount,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: options.channelCount\n }));\n }\n const constantSourceNodes = await Promise.all(Array.from(proxy.parameters.values()).map(async (audioParam) => {\n const constantSourceNode = createNativeConstantSourceNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: audioParam.value\n });\n await renderAutomation(partialOfflineAudioContext, audioParam, constantSourceNode.offset);\n return constantSourceNode;\n }));\n const inputChannelMergerNode = createNativeChannelMergerNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters)\n });\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes[i].connect(inputChannelSplitterNodes[i]);\n for (let j = 0; j < options.channelCount; j += 1) {\n inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j, i * options.channelCount + j);\n }\n }\n for (const [index, constantSourceNode] of constantSourceNodes.entries()) {\n constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index);\n constantSourceNode.start(0);\n }\n inputChannelMergerNode.connect(partialOfflineAudioContext.destination);\n await Promise.all(gainNodes.map((gainNode) => renderInputsOfAudioNode(proxy, partialOfflineAudioContext, gainNode)));\n return renderNativeOfflineAudioContext(partialOfflineAudioContext);\n };\n processedBufferPromise = processBuffer(proxy, numberOfChannels === 0 ? null : await renderBuffer(), nativeOfflineAudioContext, options, outputChannelCount, processorConstructor, exposeCurrentFrameAndCurrentTime);\n }\n const processedBuffer = await processedBufferPromise;\n const audioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n const [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode] = nativeOutputNodes;\n if (processedBuffer !== null) {\n audioBufferSourceNode.buffer = processedBuffer;\n audioBufferSourceNode.start(0);\n }\n audioBufferSourceNode.connect(outputChannelSplitterNode);\n for (let i = 0, outputChannelSplitterNodeOutput = 0; i < proxy.numberOfOutputs; i += 1) {\n const outputChannelMergerNode = outputChannelMergerNodes[i];\n for (let j = 0; j < outputChannelCount[i]; j += 1) {\n outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j);\n }\n outputChannelSplitterNodeOutput += outputChannelCount[i];\n }\n return outputGainNode;\n }\n if (!nativeAudioWorkletNodeIsOwnedByContext) {\n for (const [nm, audioParam] of proxy.parameters.entries()) {\n await renderAutomation(nativeOfflineAudioContext, audioParam, \n // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.\n nativeAudioWorkletNode.parameters.get(nm));\n }\n }\n else {\n for (const [nm, audioParam] of proxy.parameters.entries()) {\n await connectAudioParam(nativeOfflineAudioContext, audioParam, \n // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.\n nativeAudioWorkletNode.parameters.get(nm));\n }\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioWorkletNode);\n return nativeAudioWorkletNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n deleteUnrenderedAudioWorkletNode(nativeOfflineAudioContext, proxy);\n const renderedNativeAudioWorkletNodeOrGainNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAudioWorkletNodeOrGainNode !== undefined) {\n return Promise.resolve(renderedNativeAudioWorkletNodeOrGainNode);\n }\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=audio-worklet-node-renderer-factory.js.map","export const createBaseAudioContextConstructor = (addAudioWorkletModule, analyserNodeConstructor, audioBufferConstructor, audioBufferSourceNodeConstructor, biquadFilterNodeConstructor, channelMergerNodeConstructor, channelSplitterNodeConstructor, constantSourceNodeConstructor, convolverNodeConstructor, decodeAudioData, delayNodeConstructor, dynamicsCompressorNodeConstructor, gainNodeConstructor, iIRFilterNodeConstructor, minimalBaseAudioContextConstructor, oscillatorNodeConstructor, pannerNodeConstructor, periodicWaveConstructor, stereoPannerNodeConstructor, waveShaperNodeConstructor) => {\n return class BaseAudioContext extends minimalBaseAudioContextConstructor {\n constructor(_nativeContext, numberOfChannels) {\n super(_nativeContext, numberOfChannels);\n this._nativeContext = _nativeContext;\n this._audioWorklet =\n addAudioWorkletModule === undefined\n ? undefined\n : {\n addModule: (moduleURL, options) => {\n return addAudioWorkletModule(this, moduleURL, options);\n }\n };\n }\n get audioWorklet() {\n return this._audioWorklet;\n }\n createAnalyser() {\n return new analyserNodeConstructor(this);\n }\n createBiquadFilter() {\n return new biquadFilterNodeConstructor(this);\n }\n createBuffer(numberOfChannels, length, sampleRate) {\n return new audioBufferConstructor({ length, numberOfChannels, sampleRate });\n }\n createBufferSource() {\n return new audioBufferSourceNodeConstructor(this);\n }\n createChannelMerger(numberOfInputs = 6) {\n return new channelMergerNodeConstructor(this, { numberOfInputs });\n }\n createChannelSplitter(numberOfOutputs = 6) {\n return new channelSplitterNodeConstructor(this, { numberOfOutputs });\n }\n createConstantSource() {\n return new constantSourceNodeConstructor(this);\n }\n createConvolver() {\n return new convolverNodeConstructor(this);\n }\n createDelay(maxDelayTime = 1) {\n return new delayNodeConstructor(this, { maxDelayTime });\n }\n createDynamicsCompressor() {\n return new dynamicsCompressorNodeConstructor(this);\n }\n createGain() {\n return new gainNodeConstructor(this);\n }\n createIIRFilter(feedforward, feedback) {\n return new iIRFilterNodeConstructor(this, { feedback, feedforward });\n }\n createOscillator() {\n return new oscillatorNodeConstructor(this);\n }\n createPanner() {\n return new pannerNodeConstructor(this);\n }\n createPeriodicWave(real, imag, constraints = { disableNormalization: false }) {\n return new periodicWaveConstructor(this, { ...constraints, imag, real });\n }\n createStereoPanner() {\n return new stereoPannerNodeConstructor(this);\n }\n createWaveShaper() {\n return new waveShaperNodeConstructor(this);\n }\n decodeAudioData(audioData, successCallback, errorCallback) {\n return decodeAudioData(this._nativeContext, audioData).then((audioBuffer) => {\n if (typeof successCallback === 'function') {\n successCallback(audioBuffer);\n }\n return audioBuffer;\n }, (err) => {\n if (typeof errorCallback === 'function') {\n errorCallback(err);\n }\n throw err;\n });\n }\n };\n};\n//# sourceMappingURL=base-audio-context-constructor.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nconst DEFAULT_OPTIONS = {\n Q: 1,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n detune: 0,\n frequency: 350,\n gain: 0,\n type: 'lowpass'\n};\nexport const createBiquadFilterNodeConstructor = (audioNodeConstructor, createAudioParam, createBiquadFilterNodeRenderer, createInvalidAccessError, createNativeBiquadFilterNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class BiquadFilterNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeBiquadFilterNode = createNativeBiquadFilterNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const biquadFilterNodeRenderer = (isOffline ? createBiquadFilterNodeRenderer() : null);\n super(context, false, nativeBiquadFilterNode, biquadFilterNodeRenderer);\n // Bug #80: Safari does not export the correct values for maxValue and minValue.\n this._Q = createAudioParam(this, isOffline, nativeBiquadFilterNode.Q, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n // Bug #78: Firefox & Safari do not export the correct values for maxValue and minValue.\n this._detune = createAudioParam(this, isOffline, nativeBiquadFilterNode.detune, 1200 * Math.log2(MOST_POSITIVE_SINGLE_FLOAT), -1200 * Math.log2(MOST_POSITIVE_SINGLE_FLOAT));\n // Bug #77: Firefox & Safari do not export the correct value for minValue.\n this._frequency = createAudioParam(this, isOffline, nativeBiquadFilterNode.frequency, context.sampleRate / 2, 0);\n // Bug #79: Firefox & Safari do not export the correct values for maxValue and minValue.\n this._gain = createAudioParam(this, isOffline, nativeBiquadFilterNode.gain, 40 * Math.log10(MOST_POSITIVE_SINGLE_FLOAT), MOST_NEGATIVE_SINGLE_FLOAT);\n this._nativeBiquadFilterNode = nativeBiquadFilterNode;\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n get detune() {\n return this._detune;\n }\n get frequency() {\n return this._frequency;\n }\n get gain() {\n return this._gain;\n }\n get Q() {\n return this._Q;\n }\n get type() {\n return this._nativeBiquadFilterNode.type;\n }\n set type(value) {\n this._nativeBiquadFilterNode.type = value;\n }\n getFrequencyResponse(frequencyHz, magResponse, phaseResponse) {\n // Bug #189: Safari does throw an InvalidStateError.\n try {\n this._nativeBiquadFilterNode.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);\n }\n catch (err) {\n if (err.code === 11) {\n throw createInvalidAccessError();\n }\n throw err;\n }\n // Bug #68: Safari does not throw an error if the parameters differ in their length.\n if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) {\n throw createInvalidAccessError();\n }\n }\n };\n};\n//# sourceMappingURL=biquad-filter-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createBiquadFilterNodeRendererFactory = (connectAudioParam, createNativeBiquadFilterNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeBiquadFilterNodes = new WeakMap();\n const createBiquadFilterNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeBiquadFilterNode = getNativeAudioNode(proxy);\n /*\n * If the initially used nativeBiquadFilterNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeBiquadFilterNodeIsOwnedByContext = isOwnedByContext(nativeBiquadFilterNode, nativeOfflineAudioContext);\n if (!nativeBiquadFilterNodeIsOwnedByContext) {\n const options = {\n Q: nativeBiquadFilterNode.Q.value,\n channelCount: nativeBiquadFilterNode.channelCount,\n channelCountMode: nativeBiquadFilterNode.channelCountMode,\n channelInterpretation: nativeBiquadFilterNode.channelInterpretation,\n detune: nativeBiquadFilterNode.detune.value,\n frequency: nativeBiquadFilterNode.frequency.value,\n gain: nativeBiquadFilterNode.gain.value,\n type: nativeBiquadFilterNode.type\n };\n nativeBiquadFilterNode = createNativeBiquadFilterNode(nativeOfflineAudioContext, options);\n }\n renderedNativeBiquadFilterNodes.set(nativeOfflineAudioContext, nativeBiquadFilterNode);\n if (!nativeBiquadFilterNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.Q, nativeBiquadFilterNode.Q);\n await renderAutomation(nativeOfflineAudioContext, proxy.detune, nativeBiquadFilterNode.detune);\n await renderAutomation(nativeOfflineAudioContext, proxy.frequency, nativeBiquadFilterNode.frequency);\n await renderAutomation(nativeOfflineAudioContext, proxy.gain, nativeBiquadFilterNode.gain);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.Q, nativeBiquadFilterNode.Q);\n await connectAudioParam(nativeOfflineAudioContext, proxy.detune, nativeBiquadFilterNode.detune);\n await connectAudioParam(nativeOfflineAudioContext, proxy.frequency, nativeBiquadFilterNode.frequency);\n await connectAudioParam(nativeOfflineAudioContext, proxy.gain, nativeBiquadFilterNode.gain);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeBiquadFilterNode);\n return nativeBiquadFilterNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeBiquadFilterNode = renderedNativeBiquadFilterNodes.get(nativeOfflineAudioContext);\n if (renderedNativeBiquadFilterNode !== undefined) {\n return Promise.resolve(renderedNativeBiquadFilterNode);\n }\n return createBiquadFilterNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=biquad-filter-node-renderer-factory.js.map","export const createCacheTestResult = (ongoingTests, testResults) => {\n return (tester, test) => {\n const cachedTestResult = testResults.get(tester);\n if (cachedTestResult !== undefined) {\n return cachedTestResult;\n }\n const ongoingTest = ongoingTests.get(tester);\n if (ongoingTest !== undefined) {\n return ongoingTest;\n }\n try {\n const synchronousTestResult = test();\n if (synchronousTestResult instanceof Promise) {\n ongoingTests.set(tester, synchronousTestResult);\n return synchronousTestResult\n .catch(() => false)\n .then((finalTestResult) => {\n ongoingTests.delete(tester);\n testResults.set(tester, finalTestResult);\n return finalTestResult;\n });\n }\n testResults.set(tester, synchronousTestResult);\n return synchronousTestResult;\n }\n catch {\n testResults.set(tester, false);\n return false;\n }\n };\n};\n//# sourceMappingURL=cache-test-result.js.map","const DEFAULT_OPTIONS = {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 6\n};\nexport const createChannelMergerNodeConstructor = (audioNodeConstructor, createChannelMergerNodeRenderer, createNativeChannelMergerNode, getNativeContext, isNativeOfflineAudioContext) => {\n return class ChannelMergerNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeChannelMergerNode = createNativeChannelMergerNode(nativeContext, mergedOptions);\n const channelMergerNodeRenderer = ((isNativeOfflineAudioContext(nativeContext) ? createChannelMergerNodeRenderer() : null));\n super(context, false, nativeChannelMergerNode, channelMergerNodeRenderer);\n }\n };\n};\n//# sourceMappingURL=channel-merger-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createChannelMergerNodeRendererFactory = (createNativeChannelMergerNode, getNativeAudioNode, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeAudioNodes = new WeakMap();\n const createAudioNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeAudioNode = getNativeAudioNode(proxy);\n // If the initially used nativeAudioNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeAudioNodeIsOwnedByContext = isOwnedByContext(nativeAudioNode, nativeOfflineAudioContext);\n if (!nativeAudioNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeAudioNode.channelCount,\n channelCountMode: nativeAudioNode.channelCountMode,\n channelInterpretation: nativeAudioNode.channelInterpretation,\n numberOfInputs: nativeAudioNode.numberOfInputs\n };\n nativeAudioNode = createNativeChannelMergerNode(nativeOfflineAudioContext, options);\n }\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioNode);\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioNode);\n return nativeAudioNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAudioNode !== undefined) {\n return Promise.resolve(renderedNativeAudioNode);\n }\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=channel-merger-node-renderer-factory.js.map","const DEFAULT_OPTIONS = {\n channelCount: 6,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: 6\n};\nexport const createChannelSplitterNodeConstructor = (audioNodeConstructor, createChannelSplitterNodeRenderer, createNativeChannelSplitterNode, getNativeContext, isNativeOfflineAudioContext, sanitizeChannelSplitterOptions) => {\n return class ChannelSplitterNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = sanitizeChannelSplitterOptions({ ...DEFAULT_OPTIONS, ...options });\n const nativeChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, mergedOptions);\n const channelSplitterNodeRenderer = ((isNativeOfflineAudioContext(nativeContext) ? createChannelSplitterNodeRenderer() : null));\n super(context, false, nativeChannelSplitterNode, channelSplitterNodeRenderer);\n }\n };\n};\n//# sourceMappingURL=channel-splitter-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createChannelSplitterNodeRendererFactory = (createNativeChannelSplitterNode, getNativeAudioNode, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeAudioNodes = new WeakMap();\n const createAudioNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeAudioNode = getNativeAudioNode(proxy);\n // If the initially used nativeAudioNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeAudioNodeIsOwnedByContext = isOwnedByContext(nativeAudioNode, nativeOfflineAudioContext);\n if (!nativeAudioNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeAudioNode.channelCount,\n channelCountMode: nativeAudioNode.channelCountMode,\n channelInterpretation: nativeAudioNode.channelInterpretation,\n numberOfOutputs: nativeAudioNode.numberOfOutputs\n };\n nativeAudioNode = createNativeChannelSplitterNode(nativeOfflineAudioContext, options);\n }\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioNode);\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioNode);\n return nativeAudioNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAudioNode !== undefined) {\n return Promise.resolve(renderedNativeAudioNode);\n }\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=channel-splitter-node-renderer-factory.js.map","export const createConnectAudioParam = (renderInputsOfAudioParam) => {\n return (nativeOfflineAudioContext, audioParam, nativeAudioParam) => {\n return renderInputsOfAudioParam(audioParam, nativeOfflineAudioContext, nativeAudioParam);\n };\n};\n//# sourceMappingURL=connect-audio-param.js.map","import { isNativeAudioNode } from '../guards/native-audio-node';\nexport const createConnectMultipleOutputs = (createIndexSizeError) => {\n return (outputAudioNodes, destination, output = 0, input = 0) => {\n const outputAudioNode = outputAudioNodes[output];\n if (outputAudioNode === undefined) {\n throw createIndexSizeError();\n }\n if (isNativeAudioNode(destination)) {\n return outputAudioNode.connect(destination, 0, input);\n }\n return outputAudioNode.connect(destination, 0);\n };\n};\n//# sourceMappingURL=connect-multiple-outputs.js.map","export const createConnectedNativeAudioBufferSourceNodeFactory = (createNativeAudioBufferSourceNode) => {\n return (nativeContext, nativeAudioNode) => {\n const nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n const nativeAudioBuffer = nativeContext.createBuffer(1, 2, 44100);\n nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;\n nativeAudioBufferSourceNode.loop = true;\n nativeAudioBufferSourceNode.connect(nativeAudioNode);\n nativeAudioBufferSourceNode.start();\n return () => {\n nativeAudioBufferSourceNode.stop();\n nativeAudioBufferSourceNode.disconnect(nativeAudioNode);\n };\n };\n};\n//# sourceMappingURL=connected-native-audio-buffer-source-node-factory.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassive } from '../helpers/set-internal-state-to-passive';\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n offset: 1\n};\nexport const createConstantSourceNodeConstructor = (audioNodeConstructor, createAudioParam, createConstantSourceNodeRendererFactory, createNativeConstantSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener) => {\n return class ConstantSourceNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeConstantSourceNode = createNativeConstantSourceNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const constantSourceNodeRenderer = ((isOffline ? createConstantSourceNodeRendererFactory() : null));\n super(context, false, nativeConstantSourceNode, constantSourceNodeRenderer);\n this._constantSourceNodeRenderer = constantSourceNodeRenderer;\n this._nativeConstantSourceNode = nativeConstantSourceNode;\n /*\n * Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and minValue\n * for GainNodes.\n */\n this._offset = createAudioParam(this, isOffline, nativeConstantSourceNode.offset, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n this._onended = null;\n }\n get offset() {\n return this._offset;\n }\n get onended() {\n return this._onended;\n }\n set onended(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n this._nativeConstantSourceNode.onended = wrappedListener;\n const nativeOnEnded = this._nativeConstantSourceNode.onended;\n this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;\n }\n start(when = 0) {\n this._nativeConstantSourceNode.start(when);\n if (this._constantSourceNodeRenderer !== null) {\n this._constantSourceNodeRenderer.start = when;\n }\n if (this.context.state !== 'closed') {\n setInternalStateToActive(this);\n const resetInternalStateToPassive = () => {\n this._nativeConstantSourceNode.removeEventListener('ended', resetInternalStateToPassive);\n if (isActiveAudioNode(this)) {\n setInternalStateToPassive(this);\n }\n };\n this._nativeConstantSourceNode.addEventListener('ended', resetInternalStateToPassive);\n }\n }\n stop(when = 0) {\n this._nativeConstantSourceNode.stop(when);\n if (this._constantSourceNodeRenderer !== null) {\n this._constantSourceNodeRenderer.stop = when;\n }\n }\n };\n};\n//# sourceMappingURL=constant-source-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createConstantSourceNodeRendererFactory = (connectAudioParam, createNativeConstantSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeConstantSourceNodes = new WeakMap();\n let start = null;\n let stop = null;\n const createConstantSourceNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeConstantSourceNode = getNativeAudioNode(proxy);\n /*\n * If the initially used nativeConstantSourceNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeConstantSourceNodeIsOwnedByContext = isOwnedByContext(nativeConstantSourceNode, nativeOfflineAudioContext);\n if (!nativeConstantSourceNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeConstantSourceNode.channelCount,\n channelCountMode: nativeConstantSourceNode.channelCountMode,\n channelInterpretation: nativeConstantSourceNode.channelInterpretation,\n offset: nativeConstantSourceNode.offset.value\n };\n nativeConstantSourceNode = createNativeConstantSourceNode(nativeOfflineAudioContext, options);\n if (start !== null) {\n nativeConstantSourceNode.start(start);\n }\n if (stop !== null) {\n nativeConstantSourceNode.stop(stop);\n }\n }\n renderedNativeConstantSourceNodes.set(nativeOfflineAudioContext, nativeConstantSourceNode);\n if (!nativeConstantSourceNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.offset, nativeConstantSourceNode.offset);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.offset, nativeConstantSourceNode.offset);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConstantSourceNode);\n return nativeConstantSourceNode;\n };\n return {\n set start(value) {\n start = value;\n },\n set stop(value) {\n stop = value;\n },\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeConstantSourceNode = renderedNativeConstantSourceNodes.get(nativeOfflineAudioContext);\n if (renderedNativeConstantSourceNode !== undefined) {\n return Promise.resolve(renderedNativeConstantSourceNode);\n }\n return createConstantSourceNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=constant-source-node-renderer-factory.js.map","export const createConvertNumberToUnsignedLong = (unit32Array) => {\n return (value) => {\n unit32Array[0] = value;\n return unit32Array[0];\n };\n};\n//# sourceMappingURL=convert-number-to-unsigned-long.js.map","const DEFAULT_OPTIONS = {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'clamped-max',\n channelInterpretation: 'speakers',\n disableNormalization: false\n};\nexport const createConvolverNodeConstructor = (audioNodeConstructor, createConvolverNodeRenderer, createNativeConvolverNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class ConvolverNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeConvolverNode = createNativeConvolverNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const convolverNodeRenderer = (isOffline ? createConvolverNodeRenderer() : null);\n super(context, false, nativeConvolverNode, convolverNodeRenderer);\n this._isBufferNullified = false;\n this._nativeConvolverNode = nativeConvolverNode;\n if (mergedOptions.buffer !== null) {\n setAudioNodeTailTime(this, mergedOptions.buffer.duration);\n }\n }\n get buffer() {\n if (this._isBufferNullified) {\n return null;\n }\n return this._nativeConvolverNode.buffer;\n }\n set buffer(value) {\n this._nativeConvolverNode.buffer = value;\n // Bug #115: Safari does not allow to set the buffer to null.\n if (value === null && this._nativeConvolverNode.buffer !== null) {\n const nativeContext = this._nativeConvolverNode.context;\n this._nativeConvolverNode.buffer = nativeContext.createBuffer(1, 1, 44100);\n this._isBufferNullified = true;\n setAudioNodeTailTime(this, 0);\n }\n else {\n this._isBufferNullified = false;\n setAudioNodeTailTime(this, this._nativeConvolverNode.buffer === null ? 0 : this._nativeConvolverNode.buffer.duration);\n }\n }\n get normalize() {\n return this._nativeConvolverNode.normalize;\n }\n set normalize(value) {\n this._nativeConvolverNode.normalize = value;\n }\n };\n};\n//# sourceMappingURL=convolver-node-constructor.js.map","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createConvolverNodeRendererFactory = (createNativeConvolverNode, getNativeAudioNode, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeConvolverNodes = new WeakMap();\n const createConvolverNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeConvolverNode = getNativeAudioNode(proxy);\n // If the initially used nativeConvolverNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeConvolverNodeIsOwnedByContext = isOwnedByContext(nativeConvolverNode, nativeOfflineAudioContext);\n if (!nativeConvolverNodeIsOwnedByContext) {\n const options = {\n buffer: nativeConvolverNode.buffer,\n channelCount: nativeConvolverNode.channelCount,\n channelCountMode: nativeConvolverNode.channelCountMode,\n channelInterpretation: nativeConvolverNode.channelInterpretation,\n disableNormalization: !nativeConvolverNode.normalize\n };\n nativeConvolverNode = createNativeConvolverNode(nativeOfflineAudioContext, options);\n }\n renderedNativeConvolverNodes.set(nativeOfflineAudioContext, nativeConvolverNode);\n if (isNativeAudioNodeFaker(nativeConvolverNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConvolverNode.inputs[0]);\n }\n else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConvolverNode);\n }\n return nativeConvolverNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeConvolverNode = renderedNativeConvolverNodes.get(nativeOfflineAudioContext);\n if (renderedNativeConvolverNode !== undefined) {\n return Promise.resolve(renderedNativeConvolverNode);\n }\n return createConvolverNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=convolver-node-renderer-factory.js.map","export const createCreateNativeOfflineAudioContext = (createNotSupportedError, nativeOfflineAudioContextConstructor) => {\n return (numberOfChannels, length, sampleRate) => {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n try {\n return new nativeOfflineAudioContextConstructor(numberOfChannels, length, sampleRate);\n }\n catch (err) {\n // Bug #143, #144 & #146: Safari throws a SyntaxError when numberOfChannels, length or sampleRate are invalid.\n if (err.name === 'SyntaxError') {\n throw createNotSupportedError();\n }\n throw err;\n }\n };\n};\n//# sourceMappingURL=create-native-offline-audio-context.js.map","export const createDataCloneError = () => new DOMException('', 'DataCloneError');\n//# sourceMappingURL=data-clone-error.js.map","export const detachArrayBuffer = (arrayBuffer) => {\n const { port1, port2 } = new MessageChannel();\n return new Promise((resolve) => {\n const closeAndResolve = () => {\n port2.onmessage = null;\n port1.close();\n port2.close();\n resolve();\n };\n port2.onmessage = () => closeAndResolve();\n try {\n port1.postMessage(arrayBuffer, [arrayBuffer]);\n }\n finally {\n closeAndResolve();\n }\n });\n};\n//# sourceMappingURL=detach-array-buffer.js.map","import { detachArrayBuffer } from '../helpers/detach-array-buffer';\nimport { wrapAudioBufferGetChannelDataMethod } from '../helpers/wrap-audio-buffer-get-channel-data-method';\nexport const createDecodeAudioData = (audioBufferStore, cacheTestResult, createDataCloneError, createEncodingError, detachedArrayBuffers, getNativeContext, isNativeContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, testPromiseSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds) => {\n return (anyContext, audioData) => {\n const nativeContext = isNativeContext(anyContext) ? anyContext : getNativeContext(anyContext);\n // Bug #43: Only Chrome and Edge do throw a DataCloneError.\n if (detachedArrayBuffers.has(audioData)) {\n const err = createDataCloneError();\n return Promise.reject(err);\n }\n // The audioData parameter maybe of a type which can't be added to a WeakSet.\n try {\n detachedArrayBuffers.add(audioData);\n }\n catch {\n // Ignore errors.\n }\n // Bug #21: Safari does not support promises yet.\n if (cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeContext))) {\n return nativeContext.decodeAudioData(audioData).then((audioBuffer) => {\n // Bug #133: Safari does neuter the ArrayBuffer.\n detachArrayBuffer(audioData).catch(() => {\n // Ignore errors.\n });\n // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds.\n if (!cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () => testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer))) {\n wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer);\n }\n audioBufferStore.add(audioBuffer);\n return audioBuffer;\n });\n }\n // Bug #21: Safari does not return a Promise yet.\n return new Promise((resolve, reject) => {\n const complete = async () => {\n // Bug #133: Safari does neuter the ArrayBuffer.\n try {\n await detachArrayBuffer(audioData);\n }\n catch {\n // Ignore errors.\n }\n };\n const fail = (err) => {\n reject(err);\n complete();\n };\n // Bug #26: Safari throws a synchronous error.\n try {\n // Bug #1: Safari requires a successCallback.\n nativeContext.decodeAudioData(audioData, (audioBuffer) => {\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value.\n if (typeof audioBuffer.copyFromChannel !== 'function') {\n wrapAudioBufferCopyChannelMethods(audioBuffer);\n wrapAudioBufferGetChannelDataMethod(audioBuffer);\n }\n audioBufferStore.add(audioBuffer);\n complete().then(() => resolve(audioBuffer));\n }, (err) => {\n // Bug #4: Safari returns null instead of an error.\n if (err === null) {\n fail(createEncodingError());\n }\n else {\n fail(err);\n }\n });\n }\n catch (err) {\n fail(err);\n }\n });\n };\n};\n//# sourceMappingURL=decode-audio-data.js.map","import { isAudioNodeOutputConnection } from '../guards/audio-node-output-connection';\nexport const createDecrementCycleCounter = (connectNativeAudioNodeToNativeAudioNode, cycleCounters, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, getNativeContext, isActiveAudioNode, isNativeOfflineAudioContext) => {\n return (audioNode, count) => {\n const cycleCounter = cycleCounters.get(audioNode);\n if (cycleCounter === undefined) {\n throw new Error('Missing the expected cycle count.');\n }\n const nativeContext = getNativeContext(audioNode.context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n if (cycleCounter === count) {\n cycleCounters.delete(audioNode);\n if (!isOffline && isActiveAudioNode(audioNode)) {\n const nativeSourceAudioNode = getNativeAudioNode(audioNode);\n const { outputs } = getAudioNodeConnections(audioNode);\n for (const output of outputs) {\n if (isAudioNodeOutputConnection(output)) {\n const nativeDestinationAudioNode = getNativeAudioNode(output[0]);\n connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]);\n }\n else {\n const nativeDestinationAudioParam = getNativeAudioParam(output[0]);\n nativeSourceAudioNode.connect(nativeDestinationAudioParam, output[1]);\n }\n }\n }\n }\n else {\n cycleCounters.set(audioNode, cycleCounter - count);\n }\n };\n};\n//# sourceMappingURL=decrement-cycle-counter.js.map","const DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n delayTime: 0,\n maxDelayTime: 1\n};\nexport const createDelayNodeConstructor = (audioNodeConstructor, createAudioParam, createDelayNodeRenderer, createNativeDelayNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class DelayNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeDelayNode = createNativeDelayNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const delayNodeRenderer = (isOffline ? createDelayNodeRenderer(mergedOptions.maxDelayTime) : null);\n super(context, false, nativeDelayNode, delayNodeRenderer);\n this._delayTime = createAudioParam(this, isOffline, nativeDelayNode.delayTime);\n setAudioNodeTailTime(this, mergedOptions.maxDelayTime);\n }\n get delayTime() {\n return this._delayTime;\n }\n };\n};\n//# sourceMappingURL=delay-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createDelayNodeRendererFactory = (connectAudioParam, createNativeDelayNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return (maxDelayTime) => {\n const renderedNativeDelayNodes = new WeakMap();\n const createDelayNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeDelayNode = getNativeAudioNode(proxy);\n // If the initially used nativeDelayNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeDelayNodeIsOwnedByContext = isOwnedByContext(nativeDelayNode, nativeOfflineAudioContext);\n if (!nativeDelayNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeDelayNode.channelCount,\n channelCountMode: nativeDelayNode.channelCountMode,\n channelInterpretation: nativeDelayNode.channelInterpretation,\n delayTime: nativeDelayNode.delayTime.value,\n maxDelayTime\n };\n nativeDelayNode = createNativeDelayNode(nativeOfflineAudioContext, options);\n }\n renderedNativeDelayNodes.set(nativeOfflineAudioContext, nativeDelayNode);\n if (!nativeDelayNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.delayTime, nativeDelayNode.delayTime);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.delayTime, nativeDelayNode.delayTime);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeDelayNode);\n return nativeDelayNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeDelayNode = renderedNativeDelayNodes.get(nativeOfflineAudioContext);\n if (renderedNativeDelayNode !== undefined) {\n return Promise.resolve(renderedNativeDelayNode);\n }\n return createDelayNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=delay-node-renderer-factory.js.map","export const createDeleteActiveInputConnectionToAudioNode = (pickElementFromSet) => {\n return (activeInputs, source, output, input) => {\n return pickElementFromSet(activeInputs[input], (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output);\n };\n};\n//# sourceMappingURL=delete-active-input-connection-to-audio-node.js.map","export const createDeleteUnrenderedAudioWorkletNode = (getUnrenderedAudioWorkletNodes) => {\n return (nativeContext, audioWorkletNode) => {\n getUnrenderedAudioWorkletNodes(nativeContext).delete(audioWorkletNode);\n };\n};\n//# sourceMappingURL=delete-unrendered-audio-worklet-node.js.map","export const isDelayNode = (audioNode) => {\n return 'delayTime' in audioNode;\n};\n//# sourceMappingURL=delay-node.js.map","import { isAudioNode } from '../guards/audio-node';\nimport { isDelayNode } from '../guards/delay-node';\nexport const createDetectCycles = (audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey) => {\n return function detectCycles(chain, nextLink) {\n const audioNode = isAudioNode(nextLink) ? nextLink : getValueForKey(audioParamAudioNodeStore, nextLink);\n if (isDelayNode(audioNode)) {\n return [];\n }\n if (chain[0] === audioNode) {\n return [chain];\n }\n if (chain.includes(audioNode)) {\n return [];\n }\n const { outputs } = getAudioNodeConnections(audioNode);\n return Array.from(outputs)\n .map((outputConnection) => detectCycles([...chain, audioNode], outputConnection[0]))\n .reduce((mergedCycles, nestedCycles) => mergedCycles.concat(nestedCycles), []);\n };\n};\n//# sourceMappingURL=detect-cycles.js.map","import { isNativeAudioNode } from '../guards/native-audio-node';\nconst getOutputAudioNodeAtIndex = (createIndexSizeError, outputAudioNodes, output) => {\n const outputAudioNode = outputAudioNodes[output];\n if (outputAudioNode === undefined) {\n throw createIndexSizeError();\n }\n return outputAudioNode;\n};\nexport const createDisconnectMultipleOutputs = (createIndexSizeError) => {\n return (outputAudioNodes, destinationOrOutput = undefined, output = undefined, input = 0) => {\n if (destinationOrOutput === undefined) {\n return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect());\n }\n if (typeof destinationOrOutput === 'number') {\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, destinationOrOutput).disconnect();\n }\n if (isNativeAudioNode(destinationOrOutput)) {\n if (output === undefined) {\n return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect(destinationOrOutput));\n }\n if (input === undefined) {\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0);\n }\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0, input);\n }\n if (output === undefined) {\n return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect(destinationOrOutput));\n }\n return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0);\n };\n};\n//# sourceMappingURL=disconnect-multiple-outputs.js.map","const DEFAULT_OPTIONS = {\n attack: 0.003,\n channelCount: 2,\n channelCountMode: 'clamped-max',\n channelInterpretation: 'speakers',\n knee: 30,\n ratio: 12,\n release: 0.25,\n threshold: -24\n};\nexport const createDynamicsCompressorNodeConstructor = (audioNodeConstructor, createAudioParam, createDynamicsCompressorNodeRenderer, createNativeDynamicsCompressorNode, createNotSupportedError, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class DynamicsCompressorNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeDynamicsCompressorNode = createNativeDynamicsCompressorNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const dynamicsCompressorNodeRenderer = (isOffline ? createDynamicsCompressorNodeRenderer() : null);\n super(context, false, nativeDynamicsCompressorNode, dynamicsCompressorNodeRenderer);\n this._attack = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.attack);\n this._knee = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.knee);\n this._nativeDynamicsCompressorNode = nativeDynamicsCompressorNode;\n this._ratio = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.ratio);\n this._release = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.release);\n this._threshold = createAudioParam(this, isOffline, nativeDynamicsCompressorNode.threshold);\n setAudioNodeTailTime(this, 0.006);\n }\n get attack() {\n return this._attack;\n }\n // Bug #108: Safari allows a channelCount of three and above which is why the getter and setter needs to be overwritten here.\n get channelCount() {\n return this._nativeDynamicsCompressorNode.channelCount;\n }\n set channelCount(value) {\n const previousChannelCount = this._nativeDynamicsCompressorNode.channelCount;\n this._nativeDynamicsCompressorNode.channelCount = value;\n if (value > 2) {\n this._nativeDynamicsCompressorNode.channelCount = previousChannelCount;\n throw createNotSupportedError();\n }\n }\n /*\n * Bug #109: Only Chrome and Firefox disallow a channelCountMode of 'max' yet which is why the getter and setter needs to be\n * overwritten here.\n */\n get channelCountMode() {\n return this._nativeDynamicsCompressorNode.channelCountMode;\n }\n set channelCountMode(value) {\n const previousChannelCount = this._nativeDynamicsCompressorNode.channelCountMode;\n this._nativeDynamicsCompressorNode.channelCountMode = value;\n if (value === 'max') {\n this._nativeDynamicsCompressorNode.channelCountMode = previousChannelCount;\n throw createNotSupportedError();\n }\n }\n get knee() {\n return this._knee;\n }\n get ratio() {\n return this._ratio;\n }\n get reduction() {\n // Bug #111: Safari returns an AudioParam instead of a number.\n if (typeof this._nativeDynamicsCompressorNode.reduction.value === 'number') {\n return this._nativeDynamicsCompressorNode.reduction.value;\n }\n return this._nativeDynamicsCompressorNode.reduction;\n }\n get release() {\n return this._release;\n }\n get threshold() {\n return this._threshold;\n }\n };\n};\n//# sourceMappingURL=dynamics-compressor-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createDynamicsCompressorNodeRendererFactory = (connectAudioParam, createNativeDynamicsCompressorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeDynamicsCompressorNodes = new WeakMap();\n const createDynamicsCompressorNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeDynamicsCompressorNode = getNativeAudioNode(proxy);\n /*\n * If the initially used nativeDynamicsCompressorNode was not constructed on the same OfflineAudioContext it needs to be\n * created again.\n */\n const nativeDynamicsCompressorNodeIsOwnedByContext = isOwnedByContext(nativeDynamicsCompressorNode, nativeOfflineAudioContext);\n if (!nativeDynamicsCompressorNodeIsOwnedByContext) {\n const options = {\n attack: nativeDynamicsCompressorNode.attack.value,\n channelCount: nativeDynamicsCompressorNode.channelCount,\n channelCountMode: nativeDynamicsCompressorNode.channelCountMode,\n channelInterpretation: nativeDynamicsCompressorNode.channelInterpretation,\n knee: nativeDynamicsCompressorNode.knee.value,\n ratio: nativeDynamicsCompressorNode.ratio.value,\n release: nativeDynamicsCompressorNode.release.value,\n threshold: nativeDynamicsCompressorNode.threshold.value\n };\n nativeDynamicsCompressorNode = createNativeDynamicsCompressorNode(nativeOfflineAudioContext, options);\n }\n renderedNativeDynamicsCompressorNodes.set(nativeOfflineAudioContext, nativeDynamicsCompressorNode);\n if (!nativeDynamicsCompressorNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.attack, nativeDynamicsCompressorNode.attack);\n await renderAutomation(nativeOfflineAudioContext, proxy.knee, nativeDynamicsCompressorNode.knee);\n await renderAutomation(nativeOfflineAudioContext, proxy.ratio, nativeDynamicsCompressorNode.ratio);\n await renderAutomation(nativeOfflineAudioContext, proxy.release, nativeDynamicsCompressorNode.release);\n await renderAutomation(nativeOfflineAudioContext, proxy.threshold, nativeDynamicsCompressorNode.threshold);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.attack, nativeDynamicsCompressorNode.attack);\n await connectAudioParam(nativeOfflineAudioContext, proxy.knee, nativeDynamicsCompressorNode.knee);\n await connectAudioParam(nativeOfflineAudioContext, proxy.ratio, nativeDynamicsCompressorNode.ratio);\n await connectAudioParam(nativeOfflineAudioContext, proxy.release, nativeDynamicsCompressorNode.release);\n await connectAudioParam(nativeOfflineAudioContext, proxy.threshold, nativeDynamicsCompressorNode.threshold);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeDynamicsCompressorNode);\n return nativeDynamicsCompressorNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeDynamicsCompressorNode = renderedNativeDynamicsCompressorNodes.get(nativeOfflineAudioContext);\n if (renderedNativeDynamicsCompressorNode !== undefined) {\n return Promise.resolve(renderedNativeDynamicsCompressorNode);\n }\n return createDynamicsCompressorNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=dynamics-compressor-node-renderer-factory.js.map","export const createEncodingError = () => new DOMException('', 'EncodingError');\n//# sourceMappingURL=encoding-error.js.map","export const createEvaluateSource = (window) => {\n return (source) => new Promise((resolve, reject) => {\n if (window === null) {\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n reject(new SyntaxError());\n return;\n }\n const head = window.document.head;\n if (head === null) {\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n reject(new SyntaxError());\n }\n else {\n const script = window.document.createElement('script');\n // @todo Safari doesn't like URLs with a type of 'application/javascript; charset=utf-8'.\n const blob = new Blob([source], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n const originalOnErrorHandler = window.onerror;\n const removeErrorEventListenerAndRevokeUrl = () => {\n window.onerror = originalOnErrorHandler;\n URL.revokeObjectURL(url);\n };\n window.onerror = (message, src, lineno, colno, error) => {\n // @todo Edge thinks the source is the one of the html document.\n if (src === url || (src === window.location.href && lineno === 1 && colno === 1)) {\n removeErrorEventListenerAndRevokeUrl();\n reject(error);\n return false;\n }\n if (originalOnErrorHandler !== null) {\n return originalOnErrorHandler(message, src, lineno, colno, error);\n }\n };\n script.onerror = () => {\n removeErrorEventListenerAndRevokeUrl();\n // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException.\n reject(new SyntaxError());\n };\n script.onload = () => {\n removeErrorEventListenerAndRevokeUrl();\n resolve();\n };\n script.src = url;\n script.type = 'module';\n head.appendChild(script);\n }\n });\n};\n//# sourceMappingURL=evaluate-source.js.map","export const createEventTargetConstructor = (wrapEventListener) => {\n return class EventTarget {\n constructor(_nativeEventTarget) {\n this._nativeEventTarget = _nativeEventTarget;\n this._listeners = new WeakMap();\n }\n addEventListener(type, listener, options) {\n if (listener !== null) {\n let wrappedEventListener = this._listeners.get(listener);\n if (wrappedEventListener === undefined) {\n wrappedEventListener = wrapEventListener(this, listener);\n if (typeof listener === 'function') {\n this._listeners.set(listener, wrappedEventListener);\n }\n }\n this._nativeEventTarget.addEventListener(type, wrappedEventListener, options);\n }\n }\n dispatchEvent(event) {\n return this._nativeEventTarget.dispatchEvent(event);\n }\n removeEventListener(type, listener, options) {\n const wrappedEventListener = listener === null ? undefined : this._listeners.get(listener);\n this._nativeEventTarget.removeEventListener(type, wrappedEventListener === undefined ? null : wrappedEventListener, options);\n }\n };\n};\n//# sourceMappingURL=event-target-constructor.js.map","export const createExposeCurrentFrameAndCurrentTime = (window) => {\n return (currentTime, sampleRate, fn) => {\n Object.defineProperties(window, {\n currentFrame: {\n configurable: true,\n get() {\n return Math.round(currentTime * sampleRate);\n }\n },\n currentTime: {\n configurable: true,\n get() {\n return currentTime;\n }\n }\n });\n try {\n return fn();\n }\n finally {\n if (window !== null) {\n delete window.currentFrame;\n delete window.currentTime;\n }\n }\n };\n};\n//# sourceMappingURL=expose-current-frame-and-current-time.js.map","export const createFetchSource = (createAbortError) => {\n return async (url) => {\n try {\n const response = await fetch(url);\n if (response.ok) {\n return [await response.text(), response.url];\n }\n }\n catch {\n // Ignore errors.\n } // tslint:disable-line:no-empty\n throw createAbortError();\n };\n};\n//# sourceMappingURL=fetch-source.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n gain: 1\n};\nexport const createGainNodeConstructor = (audioNodeConstructor, createAudioParam, createGainNodeRenderer, createNativeGainNode, getNativeContext, isNativeOfflineAudioContext) => {\n return class GainNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeGainNode = createNativeGainNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const gainNodeRenderer = (isOffline ? createGainNodeRenderer() : null);\n super(context, false, nativeGainNode, gainNodeRenderer);\n // Bug #74: Safari does not export the correct values for maxValue and minValue.\n this._gain = createAudioParam(this, isOffline, nativeGainNode.gain, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n }\n get gain() {\n return this._gain;\n }\n };\n};\n//# sourceMappingURL=gain-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createGainNodeRendererFactory = (connectAudioParam, createNativeGainNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeGainNodes = new WeakMap();\n const createGainNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeGainNode = getNativeAudioNode(proxy);\n // If the initially used nativeGainNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeGainNodeIsOwnedByContext = isOwnedByContext(nativeGainNode, nativeOfflineAudioContext);\n if (!nativeGainNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeGainNode.channelCount,\n channelCountMode: nativeGainNode.channelCountMode,\n channelInterpretation: nativeGainNode.channelInterpretation,\n gain: nativeGainNode.gain.value\n };\n nativeGainNode = createNativeGainNode(nativeOfflineAudioContext, options);\n }\n renderedNativeGainNodes.set(nativeOfflineAudioContext, nativeGainNode);\n if (!nativeGainNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.gain, nativeGainNode.gain);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.gain, nativeGainNode.gain);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeGainNode);\n return nativeGainNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeGainNode = renderedNativeGainNodes.get(nativeOfflineAudioContext);\n if (renderedNativeGainNode !== undefined) {\n return Promise.resolve(renderedNativeGainNode);\n }\n return createGainNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=gain-node-renderer-factory.js.map","export const createGetActiveAudioWorkletNodeInputs = (activeAudioWorkletNodeInputsStore, getValueForKey) => {\n return (nativeAudioWorkletNode) => getValueForKey(activeAudioWorkletNodeInputsStore, nativeAudioWorkletNode);\n};\n//# sourceMappingURL=get-active-audio-worklet-node-inputs.js.map","export const createGetAudioNodeRenderer = (getAudioNodeConnections) => {\n return (audioNode) => {\n const audioNodeConnections = getAudioNodeConnections(audioNode);\n if (audioNodeConnections.renderer === null) {\n throw new Error('Missing the renderer of the given AudioNode in the audio graph.');\n }\n return audioNodeConnections.renderer;\n };\n};\n//# sourceMappingURL=get-audio-node-renderer.js.map","export const createGetAudioNodeTailTime = (audioNodeTailTimeStore) => {\n return (audioNode) => { var _a; return (_a = audioNodeTailTimeStore.get(audioNode)) !== null && _a !== void 0 ? _a : 0; };\n};\n//# sourceMappingURL=get-audio-node-tail-time.js.map","export const createGetAudioParamRenderer = (getAudioParamConnections) => {\n return (audioParam) => {\n const audioParamConnections = getAudioParamConnections(audioParam);\n if (audioParamConnections.renderer === null) {\n throw new Error('Missing the renderer of the given AudioParam in the audio graph.');\n }\n return audioParamConnections.renderer;\n };\n};\n//# sourceMappingURL=get-audio-param-renderer.js.map","export const createGetBackupOfflineAudioContext = (backupOfflineAudioContextStore) => {\n return (nativeContext) => {\n return backupOfflineAudioContextStore.get(nativeContext);\n };\n};\n//# sourceMappingURL=get-backup-offline-audio-context.js.map","export const createInvalidStateError = () => new DOMException('', 'InvalidStateError');\n//# sourceMappingURL=invalid-state-error.js.map","import { createInvalidStateError } from './invalid-state-error';\nexport const createGetNativeContext = (contextStore) => {\n return (context) => {\n const nativeContext = contextStore.get(context);\n if (nativeContext === undefined) {\n throw createInvalidStateError();\n }\n return (nativeContext);\n };\n};\n//# sourceMappingURL=get-native-context.js.map","export const createGetOrCreateBackupOfflineAudioContext = (backupOfflineAudioContextStore, nativeOfflineAudioContextConstructor) => {\n return (nativeContext) => {\n let backupOfflineAudioContext = backupOfflineAudioContextStore.get(nativeContext);\n if (backupOfflineAudioContext !== undefined) {\n return backupOfflineAudioContext;\n }\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz.\n backupOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100);\n backupOfflineAudioContextStore.set(nativeContext, backupOfflineAudioContext);\n return backupOfflineAudioContext;\n };\n};\n//# sourceMappingURL=get-or-create-backup-offline-audio-context.js.map","export const createGetUnrenderedAudioWorkletNodes = (unrenderedAudioWorkletNodeStore) => {\n return (nativeContext) => {\n const unrenderedAudioWorkletNodes = unrenderedAudioWorkletNodeStore.get(nativeContext);\n if (unrenderedAudioWorkletNodes === undefined) {\n throw new Error('The context has no set of AudioWorkletNodes.');\n }\n return unrenderedAudioWorkletNodes;\n };\n};\n//# sourceMappingURL=get-unrendered-audio-worklet-nodes.js.map","export const createInvalidAccessError = () => new DOMException('', 'InvalidAccessError');\n//# sourceMappingURL=invalid-access-error.js.map","import { createInvalidAccessError } from '../factories/invalid-access-error';\nexport const wrapIIRFilterNodeGetFrequencyResponseMethod = (nativeIIRFilterNode) => {\n nativeIIRFilterNode.getFrequencyResponse = ((getFrequencyResponse) => {\n return (frequencyHz, magResponse, phaseResponse) => {\n if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) {\n throw createInvalidAccessError();\n }\n return getFrequencyResponse.call(nativeIIRFilterNode, frequencyHz, magResponse, phaseResponse);\n };\n })(nativeIIRFilterNode.getFrequencyResponse);\n};\n//# sourceMappingURL=wrap-iir-filter-node-get-frequency-response-method.js.map","import { wrapIIRFilterNodeGetFrequencyResponseMethod } from '../helpers/wrap-iir-filter-node-get-frequency-response-method';\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers'\n};\nexport const createIIRFilterNodeConstructor = (audioNodeConstructor, createNativeIIRFilterNode, createIIRFilterNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class IIRFilterNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeIIRFilterNode = createNativeIIRFilterNode(nativeContext, isOffline ? null : context.baseLatency, mergedOptions);\n const iirFilterNodeRenderer = ((isOffline ? createIIRFilterNodeRenderer(mergedOptions.feedback, mergedOptions.feedforward) : null));\n super(context, false, nativeIIRFilterNode, iirFilterNodeRenderer);\n // Bug #23 & #24: FirefoxDeveloper does not throw an InvalidAccessError.\n // @todo Write a test which allows other browsers to remain unpatched.\n wrapIIRFilterNodeGetFrequencyResponseMethod(nativeIIRFilterNode);\n this._nativeIIRFilterNode = nativeIIRFilterNode;\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n getFrequencyResponse(frequencyHz, magResponse, phaseResponse) {\n return this._nativeIIRFilterNode.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);\n }\n };\n};\n//# sourceMappingURL=iir-filter-node-constructor.js.map","// This implementation as shamelessly inspired by source code of\n// tslint:disable-next-line:max-line-length\n// {@link https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/platform/audio/IIRFilter.cpp|Chromium's IIRFilter}.\nexport const filterBuffer = (feedback, feedbackLength, feedforward, feedforwardLength, minLength, xBuffer, yBuffer, bufferIndex, bufferLength, input, output) => {\n const inputLength = input.length;\n let i = bufferIndex;\n for (let j = 0; j < inputLength; j += 1) {\n let y = feedforward[0] * input[j];\n for (let k = 1; k < minLength; k += 1) {\n const x = (i - k) & (bufferLength - 1); // tslint:disable-line:no-bitwise\n y += feedforward[k] * xBuffer[x];\n y -= feedback[k] * yBuffer[x];\n }\n for (let k = minLength; k < feedforwardLength; k += 1) {\n y += feedforward[k] * xBuffer[(i - k) & (bufferLength - 1)]; // tslint:disable-line:no-bitwise\n }\n for (let k = minLength; k < feedbackLength; k += 1) {\n y -= feedback[k] * yBuffer[(i - k) & (bufferLength - 1)]; // tslint:disable-line:no-bitwise\n }\n xBuffer[i] = input[j];\n yBuffer[i] = y;\n i = (i + 1) & (bufferLength - 1); // tslint:disable-line:no-bitwise\n output[j] = y;\n }\n return i;\n};\n//# sourceMappingURL=filter-buffer.js.map","import { filterBuffer } from '../helpers/filter-buffer';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nconst filterFullBuffer = (renderedBuffer, nativeOfflineAudioContext, feedback, feedforward) => {\n const convertedFeedback = feedback instanceof Float64Array ? feedback : new Float64Array(feedback);\n const convertedFeedforward = feedforward instanceof Float64Array ? feedforward : new Float64Array(feedforward);\n const feedbackLength = convertedFeedback.length;\n const feedforwardLength = convertedFeedforward.length;\n const minLength = Math.min(feedbackLength, feedforwardLength);\n if (convertedFeedback[0] !== 1) {\n for (let i = 0; i < feedbackLength; i += 1) {\n convertedFeedforward[i] /= convertedFeedback[0];\n }\n for (let i = 1; i < feedforwardLength; i += 1) {\n convertedFeedback[i] /= convertedFeedback[0];\n }\n }\n const bufferLength = 32;\n const xBuffer = new Float32Array(bufferLength);\n const yBuffer = new Float32Array(bufferLength);\n const filteredBuffer = nativeOfflineAudioContext.createBuffer(renderedBuffer.numberOfChannels, renderedBuffer.length, renderedBuffer.sampleRate);\n const numberOfChannels = renderedBuffer.numberOfChannels;\n for (let i = 0; i < numberOfChannels; i += 1) {\n const input = renderedBuffer.getChannelData(i);\n const output = filteredBuffer.getChannelData(i);\n xBuffer.fill(0);\n yBuffer.fill(0);\n filterBuffer(convertedFeedback, feedbackLength, convertedFeedforward, feedforwardLength, minLength, xBuffer, yBuffer, 0, bufferLength, input, output);\n }\n return filteredBuffer;\n};\nexport const createIIRFilterNodeRendererFactory = (createNativeAudioBufferSourceNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderInputsOfAudioNode, renderNativeOfflineAudioContext) => {\n return (feedback, feedforward) => {\n const renderedNativeAudioNodes = new WeakMap();\n let filteredBufferPromise = null;\n const createAudioNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeAudioBufferSourceNode = null;\n let nativeIIRFilterNode = getNativeAudioNode(proxy);\n // If the initially used nativeIIRFilterNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeIIRFilterNodeIsOwnedByContext = isOwnedByContext(nativeIIRFilterNode, nativeOfflineAudioContext);\n // Bug #9: Safari does not support IIRFilterNodes.\n if (nativeOfflineAudioContext.createIIRFilter === undefined) {\n nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n }\n else if (!nativeIIRFilterNodeIsOwnedByContext) {\n // @todo TypeScript defines the parameters of createIIRFilter() as arrays of numbers.\n nativeIIRFilterNode = nativeOfflineAudioContext.createIIRFilter(feedforward, feedback);\n }\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioBufferSourceNode === null ? nativeIIRFilterNode : nativeAudioBufferSourceNode);\n if (nativeAudioBufferSourceNode !== null) {\n if (filteredBufferPromise === null) {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(\n // Bug #47: The AudioDestinationNode in Safari gets not initialized correctly.\n proxy.context.destination.channelCount, \n // Bug #17: Safari does not yet expose the length.\n proxy.context.length, nativeOfflineAudioContext.sampleRate);\n filteredBufferPromise = (async () => {\n await renderInputsOfAudioNode(proxy, partialOfflineAudioContext, partialOfflineAudioContext.destination);\n const renderedBuffer = await renderNativeOfflineAudioContext(partialOfflineAudioContext);\n return filterFullBuffer(renderedBuffer, nativeOfflineAudioContext, feedback, feedforward);\n })();\n }\n const filteredBuffer = await filteredBufferPromise;\n nativeAudioBufferSourceNode.buffer = filteredBuffer;\n nativeAudioBufferSourceNode.start(0);\n return nativeAudioBufferSourceNode;\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeIIRFilterNode);\n return nativeIIRFilterNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n if (renderedNativeAudioNode !== undefined) {\n return Promise.resolve(renderedNativeAudioNode);\n }\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=iir-filter-node-renderer-factory.js.map","import { isAudioNodeOutputConnection } from '../guards/audio-node-output-connection';\nexport const createIncrementCycleCounterFactory = (cycleCounters, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, isActiveAudioNode) => {\n return (isOffline) => {\n return (audioNode, count) => {\n const cycleCounter = cycleCounters.get(audioNode);\n if (cycleCounter === undefined) {\n if (!isOffline && isActiveAudioNode(audioNode)) {\n const nativeSourceAudioNode = getNativeAudioNode(audioNode);\n const { outputs } = getAudioNodeConnections(audioNode);\n for (const output of outputs) {\n if (isAudioNodeOutputConnection(output)) {\n const nativeDestinationAudioNode = getNativeAudioNode(output[0]);\n disconnectNativeAudioNodeFromNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]);\n }\n else {\n const nativeDestinationAudioParam = getNativeAudioParam(output[0]);\n nativeSourceAudioNode.disconnect(nativeDestinationAudioParam, output[1]);\n }\n }\n }\n cycleCounters.set(audioNode, count);\n }\n else {\n cycleCounters.set(audioNode, cycleCounter + count);\n }\n };\n };\n};\n//# sourceMappingURL=increment-cycle-counter-factory.js.map","export const createIsAnyAudioContext = (contextStore, isNativeAudioContext) => {\n return (anything) => {\n const nativeContext = contextStore.get(anything);\n return isNativeAudioContext(nativeContext) || isNativeAudioContext(anything);\n };\n};\n//# sourceMappingURL=is-any-audio-context.js.map","export const createIsAnyAudioNode = (audioNodeStore, isNativeAudioNode) => {\n return (anything) => audioNodeStore.has(anything) || isNativeAudioNode(anything);\n};\n//# sourceMappingURL=is-any-audio-node.js.map","export const createIsAnyAudioParam = (audioParamStore, isNativeAudioParam) => {\n return (anything) => audioParamStore.has(anything) || isNativeAudioParam(anything);\n};\n//# sourceMappingURL=is-any-audio-param.js.map","export const createIsAnyOfflineAudioContext = (contextStore, isNativeOfflineAudioContext) => {\n return (anything) => {\n const nativeContext = contextStore.get(anything);\n return isNativeOfflineAudioContext(nativeContext) || isNativeOfflineAudioContext(anything);\n };\n};\n//# sourceMappingURL=is-any-offline-audio-context.js.map","export const createIsNativeAudioContext = (nativeAudioContextConstructor) => {\n return (anything) => {\n return nativeAudioContextConstructor !== null && anything instanceof nativeAudioContextConstructor;\n };\n};\n//# sourceMappingURL=is-native-audio-context.js.map","export const createIsNativeAudioNode = (window) => {\n return (anything) => {\n return window !== null && typeof window.AudioNode === 'function' && anything instanceof window.AudioNode;\n };\n};\n//# sourceMappingURL=is-native-audio-node.js.map","export const createIsNativeAudioParam = (window) => {\n return (anything) => {\n return window !== null && typeof window.AudioParam === 'function' && anything instanceof window.AudioParam;\n };\n};\n//# sourceMappingURL=is-native-audio-param.js.map","export const createIsNativeContext = (isNativeAudioContext, isNativeOfflineAudioContext) => {\n return (anything) => {\n return isNativeAudioContext(anything) || isNativeOfflineAudioContext(anything);\n };\n};\n//# sourceMappingURL=is-native-context.js.map","export const createIsNativeOfflineAudioContext = (nativeOfflineAudioContextConstructor) => {\n return (anything) => {\n return nativeOfflineAudioContextConstructor !== null && anything instanceof nativeOfflineAudioContextConstructor;\n };\n};\n//# sourceMappingURL=is-native-offline-audio-context.js.map","export const createIsSecureContext = (window) => window !== null && window.isSecureContext;\n//# sourceMappingURL=is-secure-context.js.map","export const createMediaElementAudioSourceNodeConstructor = (audioNodeConstructor, createNativeMediaElementAudioSourceNode, getNativeContext, isNativeOfflineAudioContext) => {\n return class MediaElementAudioSourceNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const nativeMediaElementAudioSourceNode = createNativeMediaElementAudioSourceNode(nativeContext, options);\n // Bug #171: Safari allows to create a MediaElementAudioSourceNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeContext)) {\n throw TypeError();\n }\n super(context, true, nativeMediaElementAudioSourceNode, null);\n this._nativeMediaElementAudioSourceNode = nativeMediaElementAudioSourceNode;\n }\n get mediaElement() {\n return this._nativeMediaElementAudioSourceNode.mediaElement;\n }\n };\n};\n//# sourceMappingURL=media-element-audio-source-node-constructor.js.map","const DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers'\n};\nexport const createMediaStreamAudioDestinationNodeConstructor = (audioNodeConstructor, createNativeMediaStreamAudioDestinationNode, getNativeContext, isNativeOfflineAudioContext) => {\n return class MediaStreamAudioDestinationNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n // Bug #173: Safari allows to create a MediaStreamAudioDestinationNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeContext)) {\n throw new TypeError();\n }\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeMediaStreamAudioDestinationNode = createNativeMediaStreamAudioDestinationNode(nativeContext, mergedOptions);\n super(context, false, nativeMediaStreamAudioDestinationNode, null);\n this._nativeMediaStreamAudioDestinationNode = nativeMediaStreamAudioDestinationNode;\n }\n get stream() {\n return this._nativeMediaStreamAudioDestinationNode.stream;\n }\n };\n};\n//# sourceMappingURL=media-stream-audio-destination-node-constructor.js.map","export const createMediaStreamAudioSourceNodeConstructor = (audioNodeConstructor, createNativeMediaStreamAudioSourceNode, getNativeContext, isNativeOfflineAudioContext) => {\n return class MediaStreamAudioSourceNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const nativeMediaStreamAudioSourceNode = createNativeMediaStreamAudioSourceNode(nativeContext, options);\n // Bug #172: Safari allows to create a MediaStreamAudioSourceNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeContext)) {\n throw new TypeError();\n }\n super(context, true, nativeMediaStreamAudioSourceNode, null);\n this._nativeMediaStreamAudioSourceNode = nativeMediaStreamAudioSourceNode;\n }\n get mediaStream() {\n return this._nativeMediaStreamAudioSourceNode.mediaStream;\n }\n };\n};\n//# sourceMappingURL=media-stream-audio-source-node-constructor.js.map","export const createMediaStreamTrackAudioSourceNodeConstructor = (audioNodeConstructor, createNativeMediaStreamTrackAudioSourceNode, getNativeContext) => {\n return class MediaStreamTrackAudioSourceNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const nativeMediaStreamTrackAudioSourceNode = createNativeMediaStreamTrackAudioSourceNode(nativeContext, options);\n super(context, true, nativeMediaStreamTrackAudioSourceNode, null);\n }\n };\n};\n//# sourceMappingURL=media-stream-track-audio-source-node-constructor.js.map","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { isValidLatencyHint } from '../helpers/is-valid-latency-hint';\nexport const createMinimalAudioContextConstructor = (createInvalidStateError, createNotSupportedError, createUnknownError, minimalBaseAudioContextConstructor, nativeAudioContextConstructor) => {\n return class MinimalAudioContext extends minimalBaseAudioContextConstructor {\n constructor(options = {}) {\n if (nativeAudioContextConstructor === null) {\n throw new Error('Missing the native AudioContext constructor.');\n }\n let nativeAudioContext;\n try {\n nativeAudioContext = new nativeAudioContextConstructor(options);\n }\n catch (err) {\n // Bug #192 Safari does throw a SyntaxError if the sampleRate is not supported.\n if (err.code === 12 && err.message === 'sampleRate is not in range') {\n throw createNotSupportedError();\n }\n throw err;\n }\n // Bug #131 Safari returns null when there are four other AudioContexts running already.\n if (nativeAudioContext === null) {\n throw createUnknownError();\n }\n // Bug #51 Only Chrome and Edge throw an error if the given latencyHint is invalid.\n if (!isValidLatencyHint(options.latencyHint)) {\n throw new TypeError(`The provided value '${options.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);\n }\n // Bug #150 Safari does not support setting the sampleRate.\n if (options.sampleRate !== undefined && nativeAudioContext.sampleRate !== options.sampleRate) {\n throw createNotSupportedError();\n }\n super(nativeAudioContext, 2);\n const { latencyHint } = options;\n const { sampleRate } = nativeAudioContext;\n // @todo The values for 'balanced', 'interactive' and 'playback' are just copied from Chrome's implementation.\n this._baseLatency =\n typeof nativeAudioContext.baseLatency === 'number'\n ? nativeAudioContext.baseLatency\n : latencyHint === 'balanced'\n ? 512 / sampleRate\n : latencyHint === 'interactive' || latencyHint === undefined\n ? 256 / sampleRate\n : latencyHint === 'playback'\n ? 1024 / sampleRate\n : /*\n * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a\n * ScriptProcessorNode.\n */\n (Math.max(2, Math.min(128, Math.round((latencyHint * sampleRate) / 128))) * 128) / sampleRate;\n this._nativeAudioContext = nativeAudioContext;\n // Bug #188: Safari will set the context's state to 'interrupted' in case the user switches tabs.\n if (nativeAudioContextConstructor.name === 'webkitAudioContext') {\n this._nativeGainNode = nativeAudioContext.createGain();\n this._nativeOscillatorNode = nativeAudioContext.createOscillator();\n this._nativeGainNode.gain.value = 1e-37;\n this._nativeOscillatorNode.connect(this._nativeGainNode).connect(nativeAudioContext.destination);\n this._nativeOscillatorNode.start();\n }\n else {\n this._nativeGainNode = null;\n this._nativeOscillatorNode = null;\n }\n this._state = null;\n /*\n * Bug #34: Chrome and Edge pretend to be running right away, but fire an onstatechange event when the state actually changes\n * to 'running'.\n */\n if (nativeAudioContext.state === 'running') {\n this._state = 'suspended';\n const revokeState = () => {\n if (this._state === 'suspended') {\n this._state = null;\n }\n nativeAudioContext.removeEventListener('statechange', revokeState);\n };\n nativeAudioContext.addEventListener('statechange', revokeState);\n }\n }\n get baseLatency() {\n return this._baseLatency;\n }\n get state() {\n return this._state !== null ? this._state : this._nativeAudioContext.state;\n }\n close() {\n // Bug #35: Firefox does not throw an error if the AudioContext was closed before.\n if (this.state === 'closed') {\n return this._nativeAudioContext.close().then(() => {\n throw createInvalidStateError();\n });\n }\n // Bug #34: If the state was set to suspended before it should be revoked now.\n if (this._state === 'suspended') {\n this._state = null;\n }\n return this._nativeAudioContext.close().then(() => {\n if (this._nativeGainNode !== null && this._nativeOscillatorNode !== null) {\n this._nativeOscillatorNode.stop();\n this._nativeGainNode.disconnect();\n this._nativeOscillatorNode.disconnect();\n }\n deactivateAudioGraph(this);\n });\n }\n resume() {\n if (this._state === 'suspended') {\n return new Promise((resolve, reject) => {\n const resolvePromise = () => {\n this._nativeAudioContext.removeEventListener('statechange', resolvePromise);\n if (this._nativeAudioContext.state === 'running') {\n resolve();\n }\n else {\n this.resume().then(resolve, reject);\n }\n };\n this._nativeAudioContext.addEventListener('statechange', resolvePromise);\n });\n }\n return this._nativeAudioContext.resume().catch((err) => {\n // Bug #55: Chrome and Edge do throw an InvalidAccessError instead of an InvalidStateError.\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined || err.code === 15) {\n throw createInvalidStateError();\n }\n throw err;\n });\n }\n suspend() {\n return this._nativeAudioContext.suspend().catch((err) => {\n // Bug #56: Safari invokes the catch handler but without an error.\n if (err === undefined) {\n throw createInvalidStateError();\n }\n throw err;\n });\n }\n };\n};\n//# sourceMappingURL=minimal-audio-context-constructor.js.map","import { CONTEXT_STORE } from '../globals';\nexport const createMinimalBaseAudioContextConstructor = (audioDestinationNodeConstructor, createAudioListener, eventTargetConstructor, isNativeOfflineAudioContext, unrenderedAudioWorkletNodeStore, wrapEventListener) => {\n return class MinimalBaseAudioContext extends eventTargetConstructor {\n constructor(_nativeContext, numberOfChannels) {\n super(_nativeContext);\n this._nativeContext = _nativeContext;\n CONTEXT_STORE.set(this, _nativeContext);\n if (isNativeOfflineAudioContext(_nativeContext)) {\n unrenderedAudioWorkletNodeStore.set(_nativeContext, new Set());\n }\n this._destination = new audioDestinationNodeConstructor(this, numberOfChannels);\n this._listener = createAudioListener(this, _nativeContext);\n this._onstatechange = null;\n }\n get currentTime() {\n return this._nativeContext.currentTime;\n }\n get destination() {\n return this._destination;\n }\n get listener() {\n return this._listener;\n }\n get onstatechange() {\n return this._onstatechange;\n }\n set onstatechange(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n this._nativeContext.onstatechange = wrappedListener;\n const nativeOnStateChange = this._nativeContext.onstatechange;\n this._onstatechange = nativeOnStateChange !== null && nativeOnStateChange === wrappedListener ? value : nativeOnStateChange;\n }\n get sampleRate() {\n return this._nativeContext.sampleRate;\n }\n get state() {\n return this._nativeContext.state;\n }\n };\n};\n//# sourceMappingURL=minimal-base-audio-context-constructor.js.map","export const testPromiseSupport = (nativeContext) => {\n // This 12 numbers represent the 48 bytes of an empty WAVE file with a single sample.\n const uint32Array = new Uint32Array([1179011410, 40, 1163280727, 544501094, 16, 131073, 44100, 176400, 1048580, 1635017060, 4, 0]);\n try {\n // Bug #1: Safari requires a successCallback.\n const promise = nativeContext.decodeAudioData(uint32Array.buffer, () => {\n // Ignore the success callback.\n });\n if (promise === undefined) {\n return false;\n }\n promise.catch(() => {\n // Ignore rejected errors.\n });\n return true;\n }\n catch {\n // Ignore errors.\n }\n return false;\n};\n//# sourceMappingURL=test-promise-support.js.map","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { testPromiseSupport } from '../helpers/test-promise-support';\nconst DEFAULT_OPTIONS = {\n numberOfChannels: 1\n};\nexport const createMinimalOfflineAudioContextConstructor = (cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, minimalBaseAudioContextConstructor, startRendering) => {\n return class MinimalOfflineAudioContext extends minimalBaseAudioContextConstructor {\n constructor(options) {\n const { length, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS, ...options };\n const nativeOfflineAudioContext = createNativeOfflineAudioContext(numberOfChannels, length, sampleRate);\n // #21 Safari does not support promises and therefore would fire the statechange event before the promise can be resolved.\n if (!cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {\n nativeOfflineAudioContext.addEventListener('statechange', (() => {\n let i = 0;\n const delayStateChangeEvent = (event) => {\n if (this._state === 'running') {\n if (i > 0) {\n nativeOfflineAudioContext.removeEventListener('statechange', delayStateChangeEvent);\n event.stopImmediatePropagation();\n this._waitForThePromiseToSettle(event);\n }\n else {\n i += 1;\n }\n }\n };\n return delayStateChangeEvent;\n })());\n }\n super(nativeOfflineAudioContext, numberOfChannels);\n this._length = length;\n this._nativeOfflineAudioContext = nativeOfflineAudioContext;\n this._state = null;\n }\n get length() {\n // Bug #17: Safari does not yet expose the length.\n if (this._nativeOfflineAudioContext.length === undefined) {\n return this._length;\n }\n return this._nativeOfflineAudioContext.length;\n }\n get state() {\n return this._state === null ? this._nativeOfflineAudioContext.state : this._state;\n }\n startRendering() {\n /*\n * Bug #9 & #59: It is theoretically possible that startRendering() will first render a partialOfflineAudioContext. Therefore\n * the state of the nativeOfflineAudioContext might no transition to running immediately.\n */\n if (this._state === 'running') {\n return Promise.reject(createInvalidStateError());\n }\n this._state = 'running';\n return startRendering(this.destination, this._nativeOfflineAudioContext).finally(() => {\n this._state = null;\n deactivateAudioGraph(this);\n });\n }\n _waitForThePromiseToSettle(event) {\n if (this._state === null) {\n this._nativeOfflineAudioContext.dispatchEvent(event);\n }\n else {\n setTimeout(() => this._waitForThePromiseToSettle(event));\n }\n }\n };\n};\n//# sourceMappingURL=minimal-offline-audio-context-constructor.js.map","export const createMonitorConnections = (insertElementInSet, isNativeAudioNode) => {\n return (nativeAudioNode, whenConnected, whenDisconnected) => {\n const connections = new Set();\n nativeAudioNode.connect = ((connect) => {\n // tslint:disable-next-line:invalid-void no-inferrable-types\n return (destination, output = 0, input = 0) => {\n const wasDisconnected = connections.size === 0;\n if (isNativeAudioNode(destination)) {\n // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet.\n connect.call(nativeAudioNode, destination, output, input);\n insertElementInSet(connections, [destination, output, input], (connection) => connection[0] === destination && connection[1] === output && connection[2] === input, true);\n if (wasDisconnected) {\n whenConnected();\n }\n return destination;\n }\n connect.call(nativeAudioNode, destination, output);\n insertElementInSet(connections, [destination, output], (connection) => connection[0] === destination && connection[1] === output, true);\n if (wasDisconnected) {\n whenConnected();\n }\n return;\n };\n })(nativeAudioNode.connect);\n nativeAudioNode.disconnect = ((disconnect) => {\n return (destinationOrOutput, output, input) => {\n const wasConnected = connections.size > 0;\n if (destinationOrOutput === undefined) {\n disconnect.apply(nativeAudioNode);\n connections.clear();\n }\n else if (typeof destinationOrOutput === 'number') {\n // @todo TypeScript cannot infer the overloaded signature with 1 argument yet.\n disconnect.call(nativeAudioNode, destinationOrOutput);\n for (const connection of connections) {\n if (connection[1] === destinationOrOutput) {\n connections.delete(connection);\n }\n }\n }\n else {\n if (isNativeAudioNode(destinationOrOutput)) {\n // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet.\n disconnect.call(nativeAudioNode, destinationOrOutput, output, input);\n }\n else {\n // @todo TypeScript cannot infer the overloaded signature with 2 arguments yet.\n disconnect.call(nativeAudioNode, destinationOrOutput, output);\n }\n for (const connection of connections) {\n if (connection[0] === destinationOrOutput &&\n (output === undefined || connection[1] === output) &&\n (input === undefined || connection[2] === input)) {\n connections.delete(connection);\n }\n }\n }\n const isDisconnected = connections.size === 0;\n if (wasConnected && isDisconnected) {\n whenDisconnected();\n }\n };\n })(nativeAudioNode.disconnect);\n return nativeAudioNode;\n };\n};\n//# sourceMappingURL=monitor-connections.js.map","export const assignNativeAudioNodeOption = (nativeAudioNode, options, option) => {\n const value = options[option];\n if (value !== undefined && value !== nativeAudioNode[option]) {\n nativeAudioNode[option] = value;\n }\n};\n//# sourceMappingURL=assign-native-audio-node-option.js.map","import { assignNativeAudioNodeOption } from './assign-native-audio-node-option';\nexport const assignNativeAudioNodeOptions = (nativeAudioNode, options) => {\n assignNativeAudioNodeOption(nativeAudioNode, options, 'channelCount');\n assignNativeAudioNodeOption(nativeAudioNode, options, 'channelCountMode');\n assignNativeAudioNodeOption(nativeAudioNode, options, 'channelInterpretation');\n};\n//# sourceMappingURL=assign-native-audio-node-options.js.map","export const testAnalyserNodeGetFloatTimeDomainDataMethodSupport = (nativeAnalyserNode) => {\n return typeof nativeAnalyserNode.getFloatTimeDomainData === 'function';\n};\n//# sourceMappingURL=test-analyser-node-get-float-time-domain-data-method-support.js.map","export const wrapAnalyserNodeGetFloatTimeDomainDataMethod = (nativeAnalyserNode) => {\n nativeAnalyserNode.getFloatTimeDomainData = (array) => {\n const byteTimeDomainData = new Uint8Array(array.length);\n nativeAnalyserNode.getByteTimeDomainData(byteTimeDomainData);\n const length = Math.max(byteTimeDomainData.length, nativeAnalyserNode.fftSize);\n for (let i = 0; i < length; i += 1) {\n array[i] = (byteTimeDomainData[i] - 128) * 0.0078125;\n }\n return array;\n };\n};\n//# sourceMappingURL=wrap-analyser-node-get-float-time-domain-data-method.js.map","import { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { testAnalyserNodeGetFloatTimeDomainDataMethodSupport } from '../helpers/test-analyser-node-get-float-time-domain-data-method-support';\nimport { wrapAnalyserNodeGetFloatTimeDomainDataMethod } from '../helpers/wrap-analyser-node-get-float-time-domain-data-method';\nexport const createNativeAnalyserNodeFactory = (cacheTestResult, createIndexSizeError) => {\n return (nativeContext, options) => {\n const nativeAnalyserNode = nativeContext.createAnalyser();\n // Bug #37: Firefox does not create an AnalyserNode with the default properties.\n assignNativeAudioNodeOptions(nativeAnalyserNode, options);\n // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.\n if (!(options.maxDecibels > options.minDecibels)) {\n throw createIndexSizeError();\n }\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'fftSize');\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'maxDecibels');\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'minDecibels');\n assignNativeAudioNodeOption(nativeAnalyserNode, options, 'smoothingTimeConstant');\n // Bug #36: Safari does not support getFloatTimeDomainData() yet.\n if (!cacheTestResult(testAnalyserNodeGetFloatTimeDomainDataMethodSupport, () => testAnalyserNodeGetFloatTimeDomainDataMethodSupport(nativeAnalyserNode))) {\n wrapAnalyserNodeGetFloatTimeDomainDataMethod(nativeAnalyserNode);\n }\n return nativeAnalyserNode;\n };\n};\n//# sourceMappingURL=native-analyser-node-factory.js.map","export const createNativeAudioBufferConstructor = (window) => {\n if (window === null) {\n return null;\n }\n if (window.hasOwnProperty('AudioBuffer')) {\n return window.AudioBuffer;\n }\n return null;\n};\n//# sourceMappingURL=native-audio-buffer-constructor.js.map","export const assignNativeAudioNodeAudioParamValue = (nativeAudioNode, options, audioParam) => {\n const value = options[audioParam];\n if (value !== undefined && value !== nativeAudioNode[audioParam].value) {\n nativeAudioNode[audioParam].value = value;\n }\n};\n//# sourceMappingURL=assign-native-audio-node-audio-param-value.js.map","import { createInvalidStateError } from '../factories/invalid-state-error';\nexport const wrapAudioBufferSourceNodeStartMethodConsecutiveCalls = (nativeAudioBufferSourceNode) => {\n nativeAudioBufferSourceNode.start = ((start) => {\n let isScheduled = false;\n return (when = 0, offset = 0, duration) => {\n if (isScheduled) {\n throw createInvalidStateError();\n }\n start.call(nativeAudioBufferSourceNode, when, offset, duration);\n isScheduled = true;\n };\n })(nativeAudioBufferSourceNode.start);\n};\n//# sourceMappingURL=wrap-audio-buffer-source-node-start-method-consecutive-calls.js.map","export const wrapAudioScheduledSourceNodeStartMethodNegativeParameters = (nativeAudioScheduledSourceNode) => {\n nativeAudioScheduledSourceNode.start = ((start) => {\n return (when = 0, offset = 0, duration) => {\n if ((typeof duration === 'number' && duration < 0) || offset < 0 || when < 0) {\n throw new RangeError(\"The parameters can't be negative.\");\n }\n // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet.\n start.call(nativeAudioScheduledSourceNode, when, offset, duration);\n };\n })(nativeAudioScheduledSourceNode.start);\n};\n//# sourceMappingURL=wrap-audio-scheduled-source-node-start-method-negative-parameters.js.map","export const wrapAudioScheduledSourceNodeStopMethodNegativeParameters = (nativeAudioScheduledSourceNode) => {\n nativeAudioScheduledSourceNode.stop = ((stop) => {\n return (when = 0) => {\n if (when < 0) {\n throw new RangeError(\"The parameter can't be negative.\");\n }\n stop.call(nativeAudioScheduledSourceNode, when);\n };\n })(nativeAudioScheduledSourceNode.stop);\n};\n//# sourceMappingURL=wrap-audio-scheduled-source-node-stop-method-negative-parameters.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapAudioBufferSourceNodeStartMethodConsecutiveCalls } from '../helpers/wrap-audio-buffer-source-node-start-method-consecutive-calls';\nimport { wrapAudioScheduledSourceNodeStartMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters';\nimport { wrapAudioScheduledSourceNodeStopMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters';\nexport const createNativeAudioBufferSourceNodeFactory = (addSilentConnection, cacheTestResult, testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, testAudioBufferSourceNodeStartMethodOffsetClampingSupport, testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioBufferSourceNodeStartMethodOffsetClampling, wrapAudioBufferSourceNodeStopMethodNullifiedBuffer, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls) => {\n return (nativeContext, options) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n assignNativeAudioNodeOptions(nativeAudioBufferSourceNode, options);\n assignNativeAudioNodeAudioParamValue(nativeAudioBufferSourceNode, options, 'playbackRate');\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'buffer');\n // Bug #149: Safari does not yet support the detune AudioParam.\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loop');\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loopEnd');\n assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loopStart');\n // Bug #69: Safari does allow calls to start() of an already scheduled AudioBufferSourceNode.\n if (!cacheTestResult(testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, () => testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport(nativeContext))) {\n wrapAudioBufferSourceNodeStartMethodConsecutiveCalls(nativeAudioBufferSourceNode);\n }\n // Bug #154 & #155: Safari does not handle offsets which are equal to or greater than the duration of the buffer.\n if (!cacheTestResult(testAudioBufferSourceNodeStartMethodOffsetClampingSupport, () => testAudioBufferSourceNodeStartMethodOffsetClampingSupport(nativeContext))) {\n wrapAudioBufferSourceNodeStartMethodOffsetClampling(nativeAudioBufferSourceNode);\n }\n // Bug #162: Safari does throw an error when stop() is called on an AudioBufferSourceNode which has no buffer assigned to it.\n if (!cacheTestResult(testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, () => testAudioBufferSourceNodeStopMethodNullifiedBufferSupport(nativeContext))) {\n wrapAudioBufferSourceNodeStopMethodNullifiedBuffer(nativeAudioBufferSourceNode, nativeContext);\n }\n // Bug #44: Safari does not throw a RangeError yet.\n if (!cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, () => testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeAudioBufferSourceNode);\n }\n // Bug #19: Safari does not ignore calls to stop() of an already stopped AudioBufferSourceNode.\n if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, () => testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeAudioBufferSourceNode, nativeContext);\n }\n // Bug #44: Only Firefox does not throw a RangeError yet.\n if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, () => testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeAudioBufferSourceNode);\n }\n // Bug #175: Safari will not fire an ended event if the AudioBufferSourceNode is unconnected.\n addSilentConnection(nativeContext, nativeAudioBufferSourceNode);\n return nativeAudioBufferSourceNode;\n };\n};\n//# sourceMappingURL=native-audio-buffer-source-node-factory.js.map","export const createNativeAudioContextConstructor = (window) => {\n if (window === null) {\n return null;\n }\n if (window.hasOwnProperty('AudioContext')) {\n return window.AudioContext;\n }\n return window.hasOwnProperty('webkitAudioContext') ? window.webkitAudioContext : null;\n};\n//# sourceMappingURL=native-audio-context-constructor.js.map","export const createNativeAudioDestinationNodeFactory = (createNativeGainNode, overwriteAccessors) => {\n return (nativeContext, channelCount, isNodeOfNativeOfflineAudioContext) => {\n const nativeAudioDestinationNode = nativeContext.destination;\n // Bug #132: Safari does not have the correct channelCount.\n if (nativeAudioDestinationNode.channelCount !== channelCount) {\n try {\n nativeAudioDestinationNode.channelCount = channelCount;\n }\n catch {\n // Bug #169: Safari throws an error on each attempt to change the channelCount.\n }\n }\n // Bug #83: Safari does not have the correct channelCountMode.\n if (isNodeOfNativeOfflineAudioContext && nativeAudioDestinationNode.channelCountMode !== 'explicit') {\n nativeAudioDestinationNode.channelCountMode = 'explicit';\n }\n // Bug #47: The AudioDestinationNode in Safari does not initialize the maxChannelCount property correctly.\n if (nativeAudioDestinationNode.maxChannelCount === 0) {\n Object.defineProperty(nativeAudioDestinationNode, 'maxChannelCount', {\n value: channelCount\n });\n }\n // Bug #168: No browser does yet have an AudioDestinationNode with an output.\n const gainNode = createNativeGainNode(nativeContext, {\n channelCount,\n channelCountMode: nativeAudioDestinationNode.channelCountMode,\n channelInterpretation: nativeAudioDestinationNode.channelInterpretation,\n gain: 1\n });\n overwriteAccessors(gainNode, 'channelCount', (get) => () => get.call(gainNode), (set) => (value) => {\n set.call(gainNode, value);\n try {\n nativeAudioDestinationNode.channelCount = value;\n }\n catch (err) {\n // Bug #169: Safari throws an error on each attempt to change the channelCount.\n if (value > nativeAudioDestinationNode.maxChannelCount) {\n throw err;\n }\n }\n });\n overwriteAccessors(gainNode, 'channelCountMode', (get) => () => get.call(gainNode), (set) => (value) => {\n set.call(gainNode, value);\n nativeAudioDestinationNode.channelCountMode = value;\n });\n overwriteAccessors(gainNode, 'channelInterpretation', (get) => () => get.call(gainNode), (set) => (value) => {\n set.call(gainNode, value);\n nativeAudioDestinationNode.channelInterpretation = value;\n });\n Object.defineProperty(gainNode, 'maxChannelCount', {\n get: () => nativeAudioDestinationNode.maxChannelCount\n });\n // @todo This should be disconnected when the context is closed.\n gainNode.connect(nativeAudioDestinationNode);\n return gainNode;\n };\n};\n//# sourceMappingURL=native-audio-destination-node.js.map","export const createNativeAudioWorkletNodeConstructor = (window) => {\n if (window === null) {\n return null;\n }\n return window.hasOwnProperty('AudioWorkletNode') ? window.AudioWorkletNode : null;\n};\n//# sourceMappingURL=native-audio-worklet-node-constructor.js.map","export const testClonabilityOfAudioWorkletNodeOptions = (audioWorkletNodeOptions) => {\n const { port1 } = new MessageChannel();\n try {\n // This will throw an error if the audioWorkletNodeOptions are not clonable.\n port1.postMessage(audioWorkletNodeOptions);\n }\n finally {\n port1.close();\n }\n};\n//# sourceMappingURL=test-clonability-of-audio-worklet-node-options.js.map","import { testClonabilityOfAudioWorkletNodeOptions } from '../helpers/test-clonability-of-audio-worklet-node-options';\nexport const createNativeAudioWorkletNodeFactory = (createInvalidStateError, createNativeAudioWorkletNodeFaker, createNativeGainNode, createNotSupportedError, monitorConnections) => {\n return (nativeContext, baseLatency, nativeAudioWorkletNodeConstructor, name, processorConstructor, options) => {\n if (nativeAudioWorkletNodeConstructor !== null) {\n try {\n const nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor(nativeContext, name, options);\n const patchedEventListeners = new Map();\n let onprocessorerror = null;\n Object.defineProperties(nativeAudioWorkletNode, {\n /*\n * Bug #61: Overwriting the property accessors for channelCount and channelCountMode is necessary as long as some\n * browsers have no native implementation to achieve a consistent behavior.\n */\n channelCount: {\n get: () => options.channelCount,\n set: () => {\n throw createInvalidStateError();\n }\n },\n channelCountMode: {\n get: () => 'explicit',\n set: () => {\n throw createInvalidStateError();\n }\n },\n // Bug #156: Chrome and Edge do not yet fire an ErrorEvent.\n onprocessorerror: {\n get: () => onprocessorerror,\n set: (value) => {\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNode.removeEventListener('processorerror', onprocessorerror);\n }\n onprocessorerror = typeof value === 'function' ? value : null;\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNode.addEventListener('processorerror', onprocessorerror);\n }\n }\n }\n });\n nativeAudioWorkletNode.addEventListener = ((addEventListener) => {\n return (...args) => {\n if (args[0] === 'processorerror') {\n const unpatchedEventListener = typeof args[1] === 'function'\n ? args[1]\n : typeof args[1] === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function'\n ? args[1].handleEvent\n : null;\n if (unpatchedEventListener !== null) {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n if (patchedEventListener !== undefined) {\n args[1] = patchedEventListener;\n }\n else {\n args[1] = (event) => {\n // Bug #178: Chrome and Edge do fire an event of type error.\n if (event.type === 'error') {\n Object.defineProperties(event, {\n type: { value: 'processorerror' }\n });\n unpatchedEventListener(event);\n }\n else {\n unpatchedEventListener(new ErrorEvent(args[0], { ...event }));\n }\n };\n patchedEventListeners.set(unpatchedEventListener, args[1]);\n }\n }\n }\n // Bug #178: Chrome and Edge do fire an event of type error.\n addEventListener.call(nativeAudioWorkletNode, 'error', args[1], args[2]);\n return addEventListener.call(nativeAudioWorkletNode, ...args);\n };\n })(nativeAudioWorkletNode.addEventListener);\n nativeAudioWorkletNode.removeEventListener = ((removeEventListener) => {\n return (...args) => {\n if (args[0] === 'processorerror') {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n if (patchedEventListener !== undefined) {\n patchedEventListeners.delete(args[1]);\n args[1] = patchedEventListener;\n }\n }\n // Bug #178: Chrome and Edge do fire an event of type error.\n removeEventListener.call(nativeAudioWorkletNode, 'error', args[1], args[2]);\n return removeEventListener.call(nativeAudioWorkletNode, args[0], args[1], args[2]);\n };\n })(nativeAudioWorkletNode.removeEventListener);\n /*\n * Bug #86: Chrome and Edge do not invoke the process() function if the corresponding AudioWorkletNode is unconnected but\n * has an output.\n */\n if (options.numberOfOutputs !== 0) {\n const nativeGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n nativeAudioWorkletNode.connect(nativeGainNode).connect(nativeContext.destination);\n const whenConnected = () => nativeGainNode.disconnect();\n const whenDisconnected = () => nativeGainNode.connect(nativeContext.destination);\n // @todo Disconnect the connection when the process() function of the AudioWorkletNode returns false.\n return monitorConnections(nativeAudioWorkletNode, whenConnected, whenDisconnected);\n }\n return nativeAudioWorkletNode;\n }\n catch (err) {\n // Bug #60: Chrome & Edge throw an InvalidStateError instead of a NotSupportedError.\n if (err.code === 11) {\n throw createNotSupportedError();\n }\n throw err;\n }\n }\n // Bug #61: Only Chrome & Edge have an implementation of the AudioWorkletNode yet.\n if (processorConstructor === undefined) {\n throw createNotSupportedError();\n }\n testClonabilityOfAudioWorkletNodeOptions(options);\n return createNativeAudioWorkletNodeFaker(nativeContext, baseLatency, processorConstructor, options);\n };\n};\n//# sourceMappingURL=native-audio-worklet-node-factory.js.map","export const computeBufferSize = (baseLatency, sampleRate) => {\n if (baseLatency === null) {\n return 512;\n }\n return Math.max(512, Math.min(16384, Math.pow(2, Math.round(Math.log2(baseLatency * sampleRate)))));\n};\n//# sourceMappingURL=compute-buffer-size.js.map","export const cloneAudioWorkletNodeOptions = (audioWorkletNodeOptions) => {\n return new Promise((resolve, reject) => {\n const { port1, port2 } = new MessageChannel();\n port1.onmessage = ({ data }) => {\n port1.close();\n port2.close();\n resolve(data);\n };\n port1.onmessageerror = ({ data }) => {\n port1.close();\n port2.close();\n reject(data);\n };\n // This will throw an error if the audioWorkletNodeOptions are not clonable.\n port2.postMessage(audioWorkletNodeOptions);\n });\n};\n//# sourceMappingURL=clone-audio-worklet-node-options.js.map","import { cloneAudioWorkletNodeOptions } from './clone-audio-worklet-node-options';\nexport const createAudioWorkletProcessorPromise = async (processorConstructor, audioWorkletNodeOptions) => {\n const clonedAudioWorkletNodeOptions = await cloneAudioWorkletNodeOptions(audioWorkletNodeOptions);\n return new processorConstructor(clonedAudioWorkletNodeOptions);\n};\n//# sourceMappingURL=create-audio-worklet-processor-promise.js.map","import { NODE_TO_PROCESSOR_MAPS } from '../globals';\nimport { createAudioWorkletProcessorPromise } from './create-audio-worklet-processor-promise';\nexport const createAudioWorkletProcessor = (nativeContext, nativeAudioWorkletNode, processorConstructor, audioWorkletNodeOptions) => {\n let nodeToProcessorMap = NODE_TO_PROCESSOR_MAPS.get(nativeContext);\n if (nodeToProcessorMap === undefined) {\n nodeToProcessorMap = new WeakMap();\n NODE_TO_PROCESSOR_MAPS.set(nativeContext, nodeToProcessorMap);\n }\n const audioWorkletProcessorPromise = createAudioWorkletProcessorPromise(processorConstructor, audioWorkletNodeOptions);\n nodeToProcessorMap.set(nativeAudioWorkletNode, audioWorkletProcessorPromise);\n return audioWorkletProcessorPromise;\n};\n//# sourceMappingURL=create-audio-worklet-processor.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nimport { computeBufferSize } from '../helpers/compute-buffer-size';\nimport { copyFromChannel } from '../helpers/copy-from-channel';\nimport { copyToChannel } from '../helpers/copy-to-channel';\nimport { createAudioWorkletProcessor } from '../helpers/create-audio-worklet-processor';\nimport { createNestedArrays } from '../helpers/create-nested-arrays';\nimport { ReadOnlyMap } from '../read-only-map';\nexport const createNativeAudioWorkletNodeFakerFactory = (connectMultipleOutputs, createIndexSizeError, createInvalidStateError, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, createNativeScriptProcessorNode, createNotSupportedError, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getActiveAudioWorkletNodeInputs, monitorConnections) => {\n return (nativeContext, baseLatency, processorConstructor, options) => {\n if (options.numberOfInputs === 0 && options.numberOfOutputs === 0) {\n throw createNotSupportedError();\n }\n const outputChannelCount = Array.isArray(options.outputChannelCount)\n ? options.outputChannelCount\n : Array.from(options.outputChannelCount);\n // @todo Check if any of the channelCount values is greater than the implementation's maximum number of channels.\n if (outputChannelCount.some((channelCount) => channelCount < 1)) {\n throw createNotSupportedError();\n }\n if (outputChannelCount.length !== options.numberOfOutputs) {\n throw createIndexSizeError();\n }\n // Bug #61: This is not part of the standard but required for the faker to work.\n if (options.channelCountMode !== 'explicit') {\n throw createNotSupportedError();\n }\n const numberOfInputChannels = options.channelCount * options.numberOfInputs;\n const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0);\n const numberOfParameters = processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length;\n // Bug #61: This is not part of the standard but required for the faker to work.\n if (numberOfInputChannels + numberOfParameters > 6 || numberOfOutputChannels > 6) {\n throw createNotSupportedError();\n }\n const messageChannel = new MessageChannel();\n const gainNodes = [];\n const inputChannelSplitterNodes = [];\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes.push(createNativeGainNode(nativeContext, {\n channelCount: options.channelCount,\n channelCountMode: options.channelCountMode,\n channelInterpretation: options.channelInterpretation,\n gain: 1\n }));\n inputChannelSplitterNodes.push(createNativeChannelSplitterNode(nativeContext, {\n channelCount: options.channelCount,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: options.channelCount\n }));\n }\n const constantSourceNodes = [];\n if (processorConstructor.parameterDescriptors !== undefined) {\n for (const { defaultValue, maxValue, minValue, name } of processorConstructor.parameterDescriptors) {\n const constantSourceNode = createNativeConstantSourceNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: options.parameterData[name] !== undefined\n ? options.parameterData[name]\n : defaultValue === undefined\n ? 0\n : defaultValue\n });\n Object.defineProperties(constantSourceNode.offset, {\n defaultValue: {\n get: () => (defaultValue === undefined ? 0 : defaultValue)\n },\n maxValue: {\n get: () => (maxValue === undefined ? MOST_POSITIVE_SINGLE_FLOAT : maxValue)\n },\n minValue: {\n get: () => (minValue === undefined ? MOST_NEGATIVE_SINGLE_FLOAT : minValue)\n }\n });\n constantSourceNodes.push(constantSourceNode);\n }\n }\n const inputChannelMergerNode = createNativeChannelMergerNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters)\n });\n const bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate);\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, bufferSize, numberOfInputChannels + numberOfParameters, \n // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output.\n Math.max(1, numberOfOutputChannels));\n const outputChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, {\n channelCount: Math.max(1, numberOfOutputChannels),\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: Math.max(1, numberOfOutputChannels)\n });\n const outputChannelMergerNodes = [];\n for (let i = 0; i < options.numberOfOutputs; i += 1) {\n outputChannelMergerNodes.push(createNativeChannelMergerNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: outputChannelCount[i]\n }));\n }\n for (let i = 0; i < options.numberOfInputs; i += 1) {\n gainNodes[i].connect(inputChannelSplitterNodes[i]);\n for (let j = 0; j < options.channelCount; j += 1) {\n inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j, i * options.channelCount + j);\n }\n }\n const parameterMap = new ReadOnlyMap(processorConstructor.parameterDescriptors === undefined\n ? []\n : processorConstructor.parameterDescriptors.map(({ name }, index) => {\n const constantSourceNode = constantSourceNodes[index];\n constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index);\n constantSourceNode.start(0);\n return [name, constantSourceNode.offset];\n }));\n inputChannelMergerNode.connect(scriptProcessorNode);\n let channelInterpretation = options.channelInterpretation;\n let onprocessorerror = null;\n // Bug #87: Expose at least one output to make this node connectable.\n const outputAudioNodes = options.numberOfOutputs === 0 ? [scriptProcessorNode] : outputChannelMergerNodes;\n const nativeAudioWorkletNodeFaker = {\n get bufferSize() {\n return bufferSize;\n },\n get channelCount() {\n return options.channelCount;\n },\n set channelCount(_) {\n // Bug #61: This is not part of the standard but required for the faker to work.\n throw createInvalidStateError();\n },\n get channelCountMode() {\n return options.channelCountMode;\n },\n set channelCountMode(_) {\n // Bug #61: This is not part of the standard but required for the faker to work.\n throw createInvalidStateError();\n },\n get channelInterpretation() {\n return channelInterpretation;\n },\n set channelInterpretation(value) {\n for (const gainNode of gainNodes) {\n gainNode.channelInterpretation = value;\n }\n channelInterpretation = value;\n },\n get context() {\n return scriptProcessorNode.context;\n },\n get inputs() {\n return gainNodes;\n },\n get numberOfInputs() {\n return options.numberOfInputs;\n },\n get numberOfOutputs() {\n return options.numberOfOutputs;\n },\n get onprocessorerror() {\n return onprocessorerror;\n },\n set onprocessorerror(value) {\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNodeFaker.removeEventListener('processorerror', onprocessorerror);\n }\n onprocessorerror = typeof value === 'function' ? value : null;\n if (typeof onprocessorerror === 'function') {\n nativeAudioWorkletNodeFaker.addEventListener('processorerror', onprocessorerror);\n }\n },\n get parameters() {\n return parameterMap;\n },\n get port() {\n return messageChannel.port2;\n },\n addEventListener(...args) {\n return scriptProcessorNode.addEventListener(args[0], args[1], args[2]);\n },\n connect: connectMultipleOutputs.bind(null, outputAudioNodes),\n disconnect: disconnectMultipleOutputs.bind(null, outputAudioNodes),\n dispatchEvent(...args) {\n return scriptProcessorNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args) {\n return scriptProcessorNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n const patchedEventListeners = new Map();\n messageChannel.port1.addEventListener = ((addEventListener) => {\n return (...args) => {\n if (args[0] === 'message') {\n const unpatchedEventListener = typeof args[1] === 'function'\n ? args[1]\n : typeof args[1] === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function'\n ? args[1].handleEvent\n : null;\n if (unpatchedEventListener !== null) {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n if (patchedEventListener !== undefined) {\n args[1] = patchedEventListener;\n }\n else {\n args[1] = (event) => {\n exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, () => unpatchedEventListener(event));\n };\n patchedEventListeners.set(unpatchedEventListener, args[1]);\n }\n }\n }\n return addEventListener.call(messageChannel.port1, args[0], args[1], args[2]);\n };\n })(messageChannel.port1.addEventListener);\n messageChannel.port1.removeEventListener = ((removeEventListener) => {\n return (...args) => {\n if (args[0] === 'message') {\n const patchedEventListener = patchedEventListeners.get(args[1]);\n if (patchedEventListener !== undefined) {\n patchedEventListeners.delete(args[1]);\n args[1] = patchedEventListener;\n }\n }\n return removeEventListener.call(messageChannel.port1, args[0], args[1], args[2]);\n };\n })(messageChannel.port1.removeEventListener);\n let onmessage = null;\n Object.defineProperty(messageChannel.port1, 'onmessage', {\n get: () => onmessage,\n set: (value) => {\n if (typeof onmessage === 'function') {\n messageChannel.port1.removeEventListener('message', onmessage);\n }\n onmessage = typeof value === 'function' ? value : null;\n if (typeof onmessage === 'function') {\n messageChannel.port1.addEventListener('message', onmessage);\n messageChannel.port1.start();\n }\n }\n });\n processorConstructor.prototype.port = messageChannel.port1;\n let audioWorkletProcessor = null;\n const audioWorkletProcessorPromise = createAudioWorkletProcessor(nativeContext, nativeAudioWorkletNodeFaker, processorConstructor, options);\n audioWorkletProcessorPromise.then((dWrkltPrcssr) => (audioWorkletProcessor = dWrkltPrcssr));\n const inputs = createNestedArrays(options.numberOfInputs, options.channelCount);\n const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount);\n const parameters = processorConstructor.parameterDescriptors === undefined\n ? []\n : processorConstructor.parameterDescriptors.reduce((prmtrs, { name }) => ({ ...prmtrs, [name]: new Float32Array(128) }), {});\n let isActive = true;\n const disconnectOutputsGraph = () => {\n if (options.numberOfOutputs > 0) {\n scriptProcessorNode.disconnect(outputChannelSplitterNode);\n }\n for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) {\n const outputChannelMergerNode = outputChannelMergerNodes[i];\n for (let j = 0; j < outputChannelCount[i]; j += 1) {\n outputChannelSplitterNode.disconnect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j);\n }\n outputChannelSplitterNodeOutput += outputChannelCount[i];\n }\n };\n const activeInputIndexes = new Map();\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = ({ inputBuffer, outputBuffer }) => {\n if (audioWorkletProcessor !== null) {\n const activeInputs = getActiveAudioWorkletNodeInputs(nativeAudioWorkletNodeFaker);\n for (let i = 0; i < bufferSize; i += 128) {\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < options.channelCount; k += 1) {\n copyFromChannel(inputBuffer, inputs[j], k, k, i);\n }\n }\n if (processorConstructor.parameterDescriptors !== undefined) {\n processorConstructor.parameterDescriptors.forEach(({ name }, index) => {\n copyFromChannel(inputBuffer, parameters, name, numberOfInputChannels + index, i);\n });\n }\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n // The byteLength will be 0 when the ArrayBuffer was transferred.\n if (outputs[j][k].byteLength === 0) {\n outputs[j][k] = new Float32Array(128);\n }\n }\n }\n try {\n const potentiallyEmptyInputs = inputs.map((input, index) => {\n const activeInput = activeInputs[index];\n if (activeInput.size > 0) {\n activeInputIndexes.set(index, bufferSize / 128);\n return input;\n }\n const count = activeInputIndexes.get(index);\n if (count === undefined) {\n return [];\n }\n if (input.every((channelData) => channelData.every((sample) => sample === 0))) {\n if (count === 1) {\n activeInputIndexes.delete(index);\n }\n else {\n activeInputIndexes.set(index, count - 1);\n }\n }\n return input;\n });\n const activeSourceFlag = exposeCurrentFrameAndCurrentTime(nativeContext.currentTime + i / nativeContext.sampleRate, nativeContext.sampleRate, () => audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters));\n isActive = activeSourceFlag;\n for (let j = 0, outputChannelSplitterNodeOutput = 0; j < options.numberOfOutputs; j += 1) {\n for (let k = 0; k < outputChannelCount[j]; k += 1) {\n copyToChannel(outputBuffer, outputs[j], k, outputChannelSplitterNodeOutput + k, i);\n }\n outputChannelSplitterNodeOutput += outputChannelCount[j];\n }\n }\n catch (error) {\n isActive = false;\n nativeAudioWorkletNodeFaker.dispatchEvent(new ErrorEvent('processorerror', {\n colno: error.colno,\n filename: error.filename,\n lineno: error.lineno,\n message: error.message\n }));\n }\n if (!isActive) {\n for (let j = 0; j < options.numberOfInputs; j += 1) {\n gainNodes[j].disconnect(inputChannelSplitterNodes[j]);\n for (let k = 0; k < options.channelCount; k += 1) {\n inputChannelSplitterNodes[i].disconnect(inputChannelMergerNode, k, j * options.channelCount + k);\n }\n }\n if (processorConstructor.parameterDescriptors !== undefined) {\n const length = processorConstructor.parameterDescriptors.length;\n for (let j = 0; j < length; j += 1) {\n const constantSourceNode = constantSourceNodes[j];\n constantSourceNode.disconnect(inputChannelMergerNode, 0, numberOfInputChannels + j);\n constantSourceNode.stop();\n }\n }\n inputChannelMergerNode.disconnect(scriptProcessorNode);\n scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation\n if (isConnected) {\n disconnectOutputsGraph();\n }\n else {\n disconnectFakeGraph();\n }\n break;\n }\n }\n }\n };\n let isConnected = false;\n // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output.\n const nativeGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n const connectFakeGraph = () => scriptProcessorNode.connect(nativeGainNode).connect(nativeContext.destination);\n const disconnectFakeGraph = () => {\n scriptProcessorNode.disconnect(nativeGainNode);\n nativeGainNode.disconnect();\n };\n const whenConnected = () => {\n if (isActive) {\n disconnectFakeGraph();\n if (options.numberOfOutputs > 0) {\n scriptProcessorNode.connect(outputChannelSplitterNode);\n }\n for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) {\n const outputChannelMergerNode = outputChannelMergerNodes[i];\n for (let j = 0; j < outputChannelCount[i]; j += 1) {\n outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j);\n }\n outputChannelSplitterNodeOutput += outputChannelCount[i];\n }\n }\n isConnected = true;\n };\n const whenDisconnected = () => {\n if (isActive) {\n connectFakeGraph();\n disconnectOutputsGraph();\n }\n isConnected = false;\n };\n connectFakeGraph();\n return monitorConnections(nativeAudioWorkletNodeFaker, whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=native-audio-worklet-node-faker-factory.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeBiquadFilterNode = (nativeContext, options) => {\n const nativeBiquadFilterNode = nativeContext.createBiquadFilter();\n assignNativeAudioNodeOptions(nativeBiquadFilterNode, options);\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'Q');\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'detune');\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'frequency');\n assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'gain');\n assignNativeAudioNodeOption(nativeBiquadFilterNode, options, 'type');\n return nativeBiquadFilterNode;\n};\n//# sourceMappingURL=native-biquad-filter-node.js.map","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeChannelMergerNodeFactory = (nativeAudioContextConstructor, wrapChannelMergerNode) => {\n return (nativeContext, options) => {\n const nativeChannelMergerNode = nativeContext.createChannelMerger(options.numberOfInputs);\n /*\n * Bug #20: Safari requires a connection of any kind to treat the input signal correctly.\n * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the existence of\n * the webkitAudioContext is used as a workaround here.\n */\n if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext') {\n wrapChannelMergerNode(nativeContext, nativeChannelMergerNode);\n }\n assignNativeAudioNodeOptions(nativeChannelMergerNode, options);\n return nativeChannelMergerNode;\n };\n};\n//# sourceMappingURL=native-channel-merger-node-factory.js.map","import { createInvalidStateError } from '../factories/invalid-state-error';\nexport const wrapChannelSplitterNode = (channelSplitterNode) => {\n const channelCount = channelSplitterNode.numberOfOutputs;\n // Bug #97: Safari does not throw an error when attempting to change the channelCount to something other than its initial value.\n Object.defineProperty(channelSplitterNode, 'channelCount', {\n get: () => channelCount,\n set: (value) => {\n if (value !== channelCount) {\n throw createInvalidStateError();\n }\n }\n });\n // Bug #30: Safari does not throw an error when attempting to change the channelCountMode to something other than explicit.\n Object.defineProperty(channelSplitterNode, 'channelCountMode', {\n get: () => 'explicit',\n set: (value) => {\n if (value !== 'explicit') {\n throw createInvalidStateError();\n }\n }\n });\n // Bug #32: Safari does not throw an error when attempting to change the channelInterpretation to something other than discrete.\n Object.defineProperty(channelSplitterNode, 'channelInterpretation', {\n get: () => 'discrete',\n set: (value) => {\n if (value !== 'discrete') {\n throw createInvalidStateError();\n }\n }\n });\n};\n//# sourceMappingURL=wrap-channel-splitter-node.js.map","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapChannelSplitterNode } from '../helpers/wrap-channel-splitter-node';\nexport const createNativeChannelSplitterNode = (nativeContext, options) => {\n const nativeChannelSplitterNode = nativeContext.createChannelSplitter(options.numberOfOutputs);\n // Bug #96: Safari does not have the correct channelCount.\n // Bug #29: Safari does not have the correct channelCountMode.\n // Bug #31: Safari does not have the correct channelInterpretation.\n assignNativeAudioNodeOptions(nativeChannelSplitterNode, options);\n // Bug #29, #30, #31, #32, #96 & #97: Only Chrome, Edge & Firefox partially support the spec yet.\n wrapChannelSplitterNode(nativeChannelSplitterNode);\n return nativeChannelSplitterNode;\n};\n//# sourceMappingURL=native-channel-splitter-node.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapAudioScheduledSourceNodeStartMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters';\nimport { wrapAudioScheduledSourceNodeStopMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters';\nexport const createNativeConstantSourceNodeFactory = (addSilentConnection, cacheTestResult, createNativeConstantSourceNodeFaker, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport) => {\n return (nativeContext, options) => {\n // Bug #62: Safari does not support ConstantSourceNodes.\n if (nativeContext.createConstantSource === undefined) {\n return createNativeConstantSourceNodeFaker(nativeContext, options);\n }\n const nativeConstantSourceNode = nativeContext.createConstantSource();\n assignNativeAudioNodeOptions(nativeConstantSourceNode, options);\n assignNativeAudioNodeAudioParamValue(nativeConstantSourceNode, options, 'offset');\n // Bug #44: Safari does not throw a RangeError yet.\n if (!cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, () => testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeConstantSourceNode);\n }\n // Bug #44: Only Firefox does not throw a RangeError yet.\n if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, () => testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeConstantSourceNode);\n }\n // Bug #175: Safari will not fire an ended event if the ConstantSourceNode is unconnected.\n addSilentConnection(nativeContext, nativeConstantSourceNode);\n return nativeConstantSourceNode;\n };\n};\n//# sourceMappingURL=native-constant-source-node-factory.js.map","export const interceptConnections = (original, interceptor) => {\n original.connect = interceptor.connect.bind(interceptor);\n original.disconnect = interceptor.disconnect.bind(interceptor);\n return original;\n};\n//# sourceMappingURL=intercept-connections.js.map","import { interceptConnections } from '../helpers/intercept-connections';\nexport const createNativeConstantSourceNodeFakerFactory = (addSilentConnection, createNativeAudioBufferSourceNode, createNativeGainNode, monitorConnections) => {\n return (nativeContext, { offset, ...audioNodeOptions }) => {\n const audioBuffer = nativeContext.createBuffer(1, 2, 44100);\n const audioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, {\n buffer: null,\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n playbackRate: 1\n });\n const gainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: offset });\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n const channelData = audioBuffer.getChannelData(0);\n // Bug #95: Safari does not play or loop one sample buffers.\n channelData[0] = 1;\n channelData[1] = 1;\n audioBufferSourceNode.buffer = audioBuffer;\n audioBufferSourceNode.loop = true;\n const nativeConstantSourceNodeFaker = {\n get bufferSize() {\n return undefined;\n },\n get channelCount() {\n return gainNode.channelCount;\n },\n set channelCount(value) {\n gainNode.channelCount = value;\n },\n get channelCountMode() {\n return gainNode.channelCountMode;\n },\n set channelCountMode(value) {\n gainNode.channelCountMode = value;\n },\n get channelInterpretation() {\n return gainNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n gainNode.channelInterpretation = value;\n },\n get context() {\n return gainNode.context;\n },\n get inputs() {\n return [];\n },\n get numberOfInputs() {\n return audioBufferSourceNode.numberOfInputs;\n },\n get numberOfOutputs() {\n return gainNode.numberOfOutputs;\n },\n get offset() {\n return gainNode.gain;\n },\n get onended() {\n return audioBufferSourceNode.onended;\n },\n set onended(value) {\n audioBufferSourceNode.onended = value;\n },\n addEventListener(...args) {\n return audioBufferSourceNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args) {\n return audioBufferSourceNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args) {\n return audioBufferSourceNode.removeEventListener(args[0], args[1], args[2]);\n },\n start(when = 0) {\n audioBufferSourceNode.start.call(audioBufferSourceNode, when);\n },\n stop(when = 0) {\n audioBufferSourceNode.stop.call(audioBufferSourceNode, when);\n }\n };\n const whenConnected = () => audioBufferSourceNode.connect(gainNode);\n const whenDisconnected = () => audioBufferSourceNode.disconnect(gainNode);\n // Bug #175: Safari will not fire an ended event if the AudioBufferSourceNode is unconnected.\n addSilentConnection(nativeContext, audioBufferSourceNode);\n return monitorConnections(interceptConnections(nativeConstantSourceNodeFaker, gainNode), whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=native-constant-source-node-faker-factory.js.map","import { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeConvolverNodeFactory = (createNotSupportedError, overwriteAccessors) => {\n return (nativeContext, options) => {\n const nativeConvolverNode = nativeContext.createConvolver();\n assignNativeAudioNodeOptions(nativeConvolverNode, options);\n // The normalize property needs to be set before setting the buffer.\n if (options.disableNormalization === nativeConvolverNode.normalize) {\n nativeConvolverNode.normalize = !options.disableNormalization;\n }\n assignNativeAudioNodeOption(nativeConvolverNode, options, 'buffer');\n // Bug #113: Safari does allow to set the channelCount to a value larger than 2.\n if (options.channelCount > 2) {\n throw createNotSupportedError();\n }\n overwriteAccessors(nativeConvolverNode, 'channelCount', (get) => () => get.call(nativeConvolverNode), (set) => (value) => {\n if (value > 2) {\n throw createNotSupportedError();\n }\n return set.call(nativeConvolverNode, value);\n });\n // Bug #114: Safari allows to set the channelCountMode to 'max'.\n if (options.channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n overwriteAccessors(nativeConvolverNode, 'channelCountMode', (get) => () => get.call(nativeConvolverNode), (set) => (value) => {\n if (value === 'max') {\n throw createNotSupportedError();\n }\n return set.call(nativeConvolverNode, value);\n });\n return nativeConvolverNode;\n };\n};\n//# sourceMappingURL=native-convolver-node-factory.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeDelayNode = (nativeContext, options) => {\n const nativeDelayNode = nativeContext.createDelay(options.maxDelayTime);\n assignNativeAudioNodeOptions(nativeDelayNode, options);\n assignNativeAudioNodeAudioParamValue(nativeDelayNode, options, 'delayTime');\n return nativeDelayNode;\n};\n//# sourceMappingURL=native-delay-node.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeDynamicsCompressorNodeFactory = (createNotSupportedError) => {\n return (nativeContext, options) => {\n const nativeDynamicsCompressorNode = nativeContext.createDynamicsCompressor();\n assignNativeAudioNodeOptions(nativeDynamicsCompressorNode, options);\n // Bug #108: Safari allows a channelCount of three and above.\n if (options.channelCount > 2) {\n throw createNotSupportedError();\n }\n // Bug #109: Only Chrome and Firefox disallow a channelCountMode of 'max'.\n if (options.channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'attack');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'knee');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'ratio');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'release');\n assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'threshold');\n return nativeDynamicsCompressorNode;\n };\n};\n//# sourceMappingURL=native-dynamics-compressor-node-factory.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeGainNode = (nativeContext, options) => {\n const nativeGainNode = nativeContext.createGain();\n assignNativeAudioNodeOptions(nativeGainNode, options);\n assignNativeAudioNodeAudioParamValue(nativeGainNode, options, 'gain');\n return nativeGainNode;\n};\n//# sourceMappingURL=native-gain-node.js.map","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeIIRFilterNodeFactory = (createNativeIIRFilterNodeFaker) => {\n return (nativeContext, baseLatency, options) => {\n // Bug #9: Safari does not support IIRFilterNodes.\n if (nativeContext.createIIRFilter === undefined) {\n return createNativeIIRFilterNodeFaker(nativeContext, baseLatency, options);\n }\n // @todo TypeScript defines the parameters of createIIRFilter() as arrays of numbers.\n const nativeIIRFilterNode = nativeContext.createIIRFilter(options.feedforward, options.feedback);\n assignNativeAudioNodeOptions(nativeIIRFilterNode, options);\n return nativeIIRFilterNode;\n };\n};\n//# sourceMappingURL=native-iir-filter-node-factory.js.map","import { computeBufferSize } from '../helpers/compute-buffer-size';\nimport { filterBuffer } from '../helpers/filter-buffer';\nimport { interceptConnections } from '../helpers/intercept-connections';\nfunction divide(a, b) {\n const denominator = b[0] * b[0] + b[1] * b[1];\n return [(a[0] * b[0] + a[1] * b[1]) / denominator, (a[1] * b[0] - a[0] * b[1]) / denominator];\n}\nfunction multiply(a, b) {\n return [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];\n}\nfunction evaluatePolynomial(coefficient, z) {\n let result = [0, 0];\n for (let i = coefficient.length - 1; i >= 0; i -= 1) {\n result = multiply(result, z);\n result[0] += coefficient[i];\n }\n return result;\n}\nexport const createNativeIIRFilterNodeFakerFactory = (createInvalidAccessError, createInvalidStateError, createNativeScriptProcessorNode, createNotSupportedError) => {\n return (nativeContext, baseLatency, { channelCount, channelCountMode, channelInterpretation, feedback, feedforward }) => {\n const bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate);\n const convertedFeedback = feedback instanceof Float64Array ? feedback : new Float64Array(feedback);\n const convertedFeedforward = feedforward instanceof Float64Array ? feedforward : new Float64Array(feedforward);\n const feedbackLength = convertedFeedback.length;\n const feedforwardLength = convertedFeedforward.length;\n const minLength = Math.min(feedbackLength, feedforwardLength);\n if (feedbackLength === 0 || feedbackLength > 20) {\n throw createNotSupportedError();\n }\n if (convertedFeedback[0] === 0) {\n throw createInvalidStateError();\n }\n if (feedforwardLength === 0 || feedforwardLength > 20) {\n throw createNotSupportedError();\n }\n if (convertedFeedforward[0] === 0) {\n throw createInvalidStateError();\n }\n if (convertedFeedback[0] !== 1) {\n for (let i = 0; i < feedforwardLength; i += 1) {\n convertedFeedforward[i] /= convertedFeedback[0];\n }\n for (let i = 1; i < feedbackLength; i += 1) {\n convertedFeedback[i] /= convertedFeedback[0];\n }\n }\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, bufferSize, channelCount, channelCount);\n scriptProcessorNode.channelCount = channelCount;\n scriptProcessorNode.channelCountMode = channelCountMode;\n scriptProcessorNode.channelInterpretation = channelInterpretation;\n const bufferLength = 32;\n const bufferIndexes = [];\n const xBuffers = [];\n const yBuffers = [];\n for (let i = 0; i < channelCount; i += 1) {\n bufferIndexes.push(0);\n const xBuffer = new Float32Array(bufferLength);\n const yBuffer = new Float32Array(bufferLength);\n xBuffer.fill(0);\n yBuffer.fill(0);\n xBuffers.push(xBuffer);\n yBuffers.push(yBuffer);\n }\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = (event) => {\n const inputBuffer = event.inputBuffer;\n const outputBuffer = event.outputBuffer;\n const numberOfChannels = inputBuffer.numberOfChannels;\n for (let i = 0; i < numberOfChannels; i += 1) {\n const input = inputBuffer.getChannelData(i);\n const output = outputBuffer.getChannelData(i);\n bufferIndexes[i] = filterBuffer(convertedFeedback, feedbackLength, convertedFeedforward, feedforwardLength, minLength, xBuffers[i], yBuffers[i], bufferIndexes[i], bufferLength, input, output);\n }\n };\n const nyquist = nativeContext.sampleRate / 2;\n const nativeIIRFilterNodeFaker = {\n get bufferSize() {\n return bufferSize;\n },\n get channelCount() {\n return scriptProcessorNode.channelCount;\n },\n set channelCount(value) {\n scriptProcessorNode.channelCount = value;\n },\n get channelCountMode() {\n return scriptProcessorNode.channelCountMode;\n },\n set channelCountMode(value) {\n scriptProcessorNode.channelCountMode = value;\n },\n get channelInterpretation() {\n return scriptProcessorNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n scriptProcessorNode.channelInterpretation = value;\n },\n get context() {\n return scriptProcessorNode.context;\n },\n get inputs() {\n return [scriptProcessorNode];\n },\n get numberOfInputs() {\n return scriptProcessorNode.numberOfInputs;\n },\n get numberOfOutputs() {\n return scriptProcessorNode.numberOfOutputs;\n },\n addEventListener(...args) {\n // @todo Dissallow adding an audioprocess listener.\n return scriptProcessorNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args) {\n return scriptProcessorNode.dispatchEvent(args[0]);\n },\n getFrequencyResponse(frequencyHz, magResponse, phaseResponse) {\n if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) {\n throw createInvalidAccessError();\n }\n const length = frequencyHz.length;\n for (let i = 0; i < length; i += 1) {\n const omega = -Math.PI * (frequencyHz[i] / nyquist);\n const z = [Math.cos(omega), Math.sin(omega)];\n const numerator = evaluatePolynomial(convertedFeedforward, z);\n const denominator = evaluatePolynomial(convertedFeedback, z);\n const response = divide(numerator, denominator);\n magResponse[i] = Math.sqrt(response[0] * response[0] + response[1] * response[1]);\n phaseResponse[i] = Math.atan2(response[1], response[0]);\n }\n },\n removeEventListener(...args) {\n return scriptProcessorNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n return interceptConnections(nativeIIRFilterNodeFaker, scriptProcessorNode);\n };\n};\n//# sourceMappingURL=native-iir-filter-node-faker-factory.js.map","export const createNativeMediaElementAudioSourceNode = (nativeAudioContext, options) => {\n return nativeAudioContext.createMediaElementSource(options.mediaElement);\n};\n//# sourceMappingURL=native-media-element-audio-source-node.js.map","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeMediaStreamAudioDestinationNode = (nativeAudioContext, options) => {\n const nativeMediaStreamAudioDestinationNode = nativeAudioContext.createMediaStreamDestination();\n assignNativeAudioNodeOptions(nativeMediaStreamAudioDestinationNode, options);\n // Bug #174: Safari does expose a wrong numberOfOutputs.\n if (nativeMediaStreamAudioDestinationNode.numberOfOutputs === 1) {\n Object.defineProperty(nativeMediaStreamAudioDestinationNode, 'numberOfOutputs', { get: () => 0 });\n }\n return nativeMediaStreamAudioDestinationNode;\n};\n//# sourceMappingURL=native-media-stream-audio-destination-node.js.map","export const createNativeMediaStreamAudioSourceNode = (nativeAudioContext, { mediaStream }) => {\n const audioStreamTracks = mediaStream.getAudioTracks();\n /*\n * Bug #151: Safari does not use the audio track as input anymore if it gets removed from the mediaStream after construction.\n * Bug #159: Safari picks the first audio track if the MediaStream has more than one audio track.\n */\n audioStreamTracks.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n const filteredAudioStreamTracks = audioStreamTracks.slice(0, 1);\n const nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(new MediaStream(filteredAudioStreamTracks));\n /*\n * Bug #151 & #159: The given mediaStream gets reconstructed before it gets passed to the native node which is why the accessor needs\n * to be overwritten as it would otherwise expose the reconstructed version.\n */\n Object.defineProperty(nativeMediaStreamAudioSourceNode, 'mediaStream', { value: mediaStream });\n return nativeMediaStreamAudioSourceNode;\n};\n//# sourceMappingURL=native-media-stream-audio-source-node.js.map","export const createNativeMediaStreamTrackAudioSourceNodeFactory = (createInvalidStateError, isNativeOfflineAudioContext) => {\n return (nativeAudioContext, { mediaStreamTrack }) => {\n // Bug #121: Only Firefox does yet support the MediaStreamTrackAudioSourceNode.\n if (typeof nativeAudioContext.createMediaStreamTrackSource === 'function') {\n return nativeAudioContext.createMediaStreamTrackSource(mediaStreamTrack);\n }\n const mediaStream = new MediaStream([mediaStreamTrack]);\n const nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(mediaStream);\n // Bug #120: Firefox does not throw an error if the mediaStream has no audio track.\n if (mediaStreamTrack.kind !== 'audio') {\n throw createInvalidStateError();\n }\n // Bug #172: Safari allows to create a MediaStreamAudioSourceNode with an OfflineAudioContext.\n if (isNativeOfflineAudioContext(nativeAudioContext)) {\n throw new TypeError();\n }\n return nativeMediaStreamAudioSourceNode;\n };\n};\n//# sourceMappingURL=native-media-stream-track-audio-source-node-factory.js.map","export const createNativeOfflineAudioContextConstructor = (window) => {\n if (window === null) {\n return null;\n }\n if (window.hasOwnProperty('OfflineAudioContext')) {\n return window.OfflineAudioContext;\n }\n return window.hasOwnProperty('webkitOfflineAudioContext') ? window.webkitOfflineAudioContext : null;\n};\n//# sourceMappingURL=native-offline-audio-context-constructor.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { wrapAudioScheduledSourceNodeStartMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-start-method-negative-parameters';\nimport { wrapAudioScheduledSourceNodeStopMethodNegativeParameters } from '../helpers/wrap-audio-scheduled-source-node-stop-method-negative-parameters';\nexport const createNativeOscillatorNodeFactory = (addSilentConnection, cacheTestResult, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls) => {\n return (nativeContext, options) => {\n const nativeOscillatorNode = nativeContext.createOscillator();\n assignNativeAudioNodeOptions(nativeOscillatorNode, options);\n assignNativeAudioNodeAudioParamValue(nativeOscillatorNode, options, 'detune');\n assignNativeAudioNodeAudioParamValue(nativeOscillatorNode, options, 'frequency');\n if (options.periodicWave !== undefined) {\n nativeOscillatorNode.setPeriodicWave(options.periodicWave);\n }\n else {\n assignNativeAudioNodeOption(nativeOscillatorNode, options, 'type');\n }\n // Bug #44: Only Chrome & Edge throw a RangeError yet.\n if (!cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, () => testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeOscillatorNode);\n }\n // Bug #19: Safari does not ignore calls to stop() of an already stopped AudioBufferSourceNode.\n if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, () => testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeOscillatorNode, nativeContext);\n }\n // Bug #44: Only Firefox does not throw a RangeError yet.\n if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, () => testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext))) {\n wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeOscillatorNode);\n }\n // Bug #175: Safari will not fire an ended event if the OscillatorNode is unconnected.\n addSilentConnection(nativeContext, nativeOscillatorNode);\n return nativeOscillatorNode;\n };\n};\n//# sourceMappingURL=native-oscillator-node-factory.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativePannerNodeFactory = (createNativePannerNodeFaker) => {\n return (nativeContext, options) => {\n const nativePannerNode = nativeContext.createPanner();\n // Bug #124: Safari does not support modifying the orientation and the position with AudioParams.\n if (nativePannerNode.orientationX === undefined) {\n return createNativePannerNodeFaker(nativeContext, options);\n }\n assignNativeAudioNodeOptions(nativePannerNode, options);\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationX');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationY');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationZ');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionX');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionY');\n assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionZ');\n assignNativeAudioNodeOption(nativePannerNode, options, 'coneInnerAngle');\n assignNativeAudioNodeOption(nativePannerNode, options, 'coneOuterAngle');\n assignNativeAudioNodeOption(nativePannerNode, options, 'coneOuterGain');\n assignNativeAudioNodeOption(nativePannerNode, options, 'distanceModel');\n assignNativeAudioNodeOption(nativePannerNode, options, 'maxDistance');\n assignNativeAudioNodeOption(nativePannerNode, options, 'panningModel');\n assignNativeAudioNodeOption(nativePannerNode, options, 'refDistance');\n assignNativeAudioNodeOption(nativePannerNode, options, 'rolloffFactor');\n return nativePannerNode;\n };\n};\n//# sourceMappingURL=native-panner-node-factory.js.map","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { interceptConnections } from '../helpers/intercept-connections';\nexport const createNativePannerNodeFakerFactory = (connectNativeAudioNodeToNativeAudioNode, createInvalidStateError, createNativeChannelMergerNode, createNativeGainNode, createNativeScriptProcessorNode, createNativeWaveShaperNode, createNotSupportedError, disconnectNativeAudioNodeFromNativeAudioNode, getFirstSample, monitorConnections) => {\n return (nativeContext, { coneInnerAngle, coneOuterAngle, coneOuterGain, distanceModel, maxDistance, orientationX, orientationY, orientationZ, panningModel, positionX, positionY, positionZ, refDistance, rolloffFactor, ...audioNodeOptions }) => {\n const pannerNode = nativeContext.createPanner();\n // Bug #125: Safari does not throw an error yet.\n if (audioNodeOptions.channelCount > 2) {\n throw createNotSupportedError();\n }\n // Bug #126: Safari does not throw an error yet.\n if (audioNodeOptions.channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n assignNativeAudioNodeOptions(pannerNode, audioNodeOptions);\n const SINGLE_CHANNEL_OPTIONS = {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete'\n };\n const channelMergerNode = createNativeChannelMergerNode(nativeContext, {\n ...SINGLE_CHANNEL_OPTIONS,\n channelInterpretation: 'speakers',\n numberOfInputs: 6\n });\n const inputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: 1 });\n const orientationXGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 1 });\n const orientationYGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const orientationZGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const positionXGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const positionYGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const positionZGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 6, 1);\n const waveShaperNode = createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_OPTIONS,\n curve: new Float32Array([1, 1]),\n oversample: 'none'\n });\n let lastOrientation = [orientationX, orientationY, orientationZ];\n let lastPosition = [positionX, positionY, positionZ];\n const buffer = new Float32Array(1);\n // tslint:disable-next-line:deprecation\n scriptProcessorNode.onaudioprocess = ({ inputBuffer }) => {\n const orientation = [\n getFirstSample(inputBuffer, buffer, 0),\n getFirstSample(inputBuffer, buffer, 1),\n getFirstSample(inputBuffer, buffer, 2)\n ];\n if (orientation.some((value, index) => value !== lastOrientation[index])) {\n pannerNode.setOrientation(...orientation); // tslint:disable-line:deprecation\n lastOrientation = orientation;\n }\n const positon = [\n getFirstSample(inputBuffer, buffer, 3),\n getFirstSample(inputBuffer, buffer, 4),\n getFirstSample(inputBuffer, buffer, 5)\n ];\n if (positon.some((value, index) => value !== lastPosition[index])) {\n pannerNode.setPosition(...positon); // tslint:disable-line:deprecation\n lastPosition = positon;\n }\n };\n Object.defineProperty(orientationYGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(orientationZGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(positionXGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(positionYGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(positionZGainNode.gain, 'defaultValue', { get: () => 0 });\n const nativePannerNodeFaker = {\n get bufferSize() {\n return undefined;\n },\n get channelCount() {\n return pannerNode.channelCount;\n },\n set channelCount(value) {\n // Bug #125: Safari does not throw an error yet.\n if (value > 2) {\n throw createNotSupportedError();\n }\n inputGainNode.channelCount = value;\n pannerNode.channelCount = value;\n },\n get channelCountMode() {\n return pannerNode.channelCountMode;\n },\n set channelCountMode(value) {\n // Bug #126: Safari does not throw an error yet.\n if (value === 'max') {\n throw createNotSupportedError();\n }\n inputGainNode.channelCountMode = value;\n pannerNode.channelCountMode = value;\n },\n get channelInterpretation() {\n return pannerNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n inputGainNode.channelInterpretation = value;\n pannerNode.channelInterpretation = value;\n },\n get coneInnerAngle() {\n return pannerNode.coneInnerAngle;\n },\n set coneInnerAngle(value) {\n pannerNode.coneInnerAngle = value;\n },\n get coneOuterAngle() {\n return pannerNode.coneOuterAngle;\n },\n set coneOuterAngle(value) {\n pannerNode.coneOuterAngle = value;\n },\n get coneOuterGain() {\n return pannerNode.coneOuterGain;\n },\n set coneOuterGain(value) {\n // Bug #127: Safari does not throw an InvalidStateError yet.\n if (value < 0 || value > 1) {\n throw createInvalidStateError();\n }\n pannerNode.coneOuterGain = value;\n },\n get context() {\n return pannerNode.context;\n },\n get distanceModel() {\n return pannerNode.distanceModel;\n },\n set distanceModel(value) {\n pannerNode.distanceModel = value;\n },\n get inputs() {\n return [inputGainNode];\n },\n get maxDistance() {\n return pannerNode.maxDistance;\n },\n set maxDistance(value) {\n // Bug #128: Safari does not throw an error yet.\n if (value < 0) {\n throw new RangeError();\n }\n pannerNode.maxDistance = value;\n },\n get numberOfInputs() {\n return pannerNode.numberOfInputs;\n },\n get numberOfOutputs() {\n return pannerNode.numberOfOutputs;\n },\n get orientationX() {\n return orientationXGainNode.gain;\n },\n get orientationY() {\n return orientationYGainNode.gain;\n },\n get orientationZ() {\n return orientationZGainNode.gain;\n },\n get panningModel() {\n return pannerNode.panningModel;\n },\n set panningModel(value) {\n pannerNode.panningModel = value;\n },\n get positionX() {\n return positionXGainNode.gain;\n },\n get positionY() {\n return positionYGainNode.gain;\n },\n get positionZ() {\n return positionZGainNode.gain;\n },\n get refDistance() {\n return pannerNode.refDistance;\n },\n set refDistance(value) {\n // Bug #129: Safari does not throw an error yet.\n if (value < 0) {\n throw new RangeError();\n }\n pannerNode.refDistance = value;\n },\n get rolloffFactor() {\n return pannerNode.rolloffFactor;\n },\n set rolloffFactor(value) {\n // Bug #130: Safari does not throw an error yet.\n if (value < 0) {\n throw new RangeError();\n }\n pannerNode.rolloffFactor = value;\n },\n addEventListener(...args) {\n return inputGainNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args) {\n return inputGainNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args) {\n return inputGainNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n if (coneInnerAngle !== nativePannerNodeFaker.coneInnerAngle) {\n nativePannerNodeFaker.coneInnerAngle = coneInnerAngle;\n }\n if (coneOuterAngle !== nativePannerNodeFaker.coneOuterAngle) {\n nativePannerNodeFaker.coneOuterAngle = coneOuterAngle;\n }\n if (coneOuterGain !== nativePannerNodeFaker.coneOuterGain) {\n nativePannerNodeFaker.coneOuterGain = coneOuterGain;\n }\n if (distanceModel !== nativePannerNodeFaker.distanceModel) {\n nativePannerNodeFaker.distanceModel = distanceModel;\n }\n if (maxDistance !== nativePannerNodeFaker.maxDistance) {\n nativePannerNodeFaker.maxDistance = maxDistance;\n }\n if (orientationX !== nativePannerNodeFaker.orientationX.value) {\n nativePannerNodeFaker.orientationX.value = orientationX;\n }\n if (orientationY !== nativePannerNodeFaker.orientationY.value) {\n nativePannerNodeFaker.orientationY.value = orientationY;\n }\n if (orientationZ !== nativePannerNodeFaker.orientationZ.value) {\n nativePannerNodeFaker.orientationZ.value = orientationZ;\n }\n if (panningModel !== nativePannerNodeFaker.panningModel) {\n nativePannerNodeFaker.panningModel = panningModel;\n }\n if (positionX !== nativePannerNodeFaker.positionX.value) {\n nativePannerNodeFaker.positionX.value = positionX;\n }\n if (positionY !== nativePannerNodeFaker.positionY.value) {\n nativePannerNodeFaker.positionY.value = positionY;\n }\n if (positionZ !== nativePannerNodeFaker.positionZ.value) {\n nativePannerNodeFaker.positionZ.value = positionZ;\n }\n if (refDistance !== nativePannerNodeFaker.refDistance) {\n nativePannerNodeFaker.refDistance = refDistance;\n }\n if (rolloffFactor !== nativePannerNodeFaker.rolloffFactor) {\n nativePannerNodeFaker.rolloffFactor = rolloffFactor;\n }\n if (lastOrientation[0] !== 1 || lastOrientation[1] !== 0 || lastOrientation[2] !== 0) {\n pannerNode.setOrientation(...lastOrientation); // tslint:disable-line:deprecation\n }\n if (lastPosition[0] !== 0 || lastPosition[1] !== 0 || lastPosition[2] !== 0) {\n pannerNode.setPosition(...lastPosition); // tslint:disable-line:deprecation\n }\n const whenConnected = () => {\n inputGainNode.connect(pannerNode);\n // Bug #119: Safari does not fully support the WaveShaperNode.\n connectNativeAudioNodeToNativeAudioNode(inputGainNode, waveShaperNode, 0, 0);\n waveShaperNode.connect(orientationXGainNode).connect(channelMergerNode, 0, 0);\n waveShaperNode.connect(orientationYGainNode).connect(channelMergerNode, 0, 1);\n waveShaperNode.connect(orientationZGainNode).connect(channelMergerNode, 0, 2);\n waveShaperNode.connect(positionXGainNode).connect(channelMergerNode, 0, 3);\n waveShaperNode.connect(positionYGainNode).connect(channelMergerNode, 0, 4);\n waveShaperNode.connect(positionZGainNode).connect(channelMergerNode, 0, 5);\n channelMergerNode.connect(scriptProcessorNode).connect(nativeContext.destination);\n };\n const whenDisconnected = () => {\n inputGainNode.disconnect(pannerNode);\n // Bug #119: Safari does not fully support the WaveShaperNode.\n disconnectNativeAudioNodeFromNativeAudioNode(inputGainNode, waveShaperNode, 0, 0);\n waveShaperNode.disconnect(orientationXGainNode);\n orientationXGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(orientationYGainNode);\n orientationYGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(orientationZGainNode);\n orientationZGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(positionXGainNode);\n positionXGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(positionYGainNode);\n positionYGainNode.disconnect(channelMergerNode);\n waveShaperNode.disconnect(positionZGainNode);\n positionZGainNode.disconnect(channelMergerNode);\n channelMergerNode.disconnect(scriptProcessorNode);\n scriptProcessorNode.disconnect(nativeContext.destination);\n };\n return monitorConnections(interceptConnections(nativePannerNodeFaker, pannerNode), whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=native-panner-node-faker-factory.js.map","export const createNativePeriodicWaveFactory = (createIndexSizeError) => {\n return (nativeContext, { disableNormalization, imag, real }) => {\n // Bug #180: Safari does not allow to use ordinary arrays.\n const convertedImag = imag instanceof Float32Array ? imag : new Float32Array(imag);\n const convertedReal = real instanceof Float32Array ? real : new Float32Array(real);\n const nativePeriodicWave = nativeContext.createPeriodicWave(convertedReal, convertedImag, { disableNormalization });\n // Bug #181: Safari does not throw an IndexSizeError so far if the given arrays have less than two values.\n if (Array.from(imag).length < 2) {\n throw createIndexSizeError();\n }\n return nativePeriodicWave;\n };\n};\n//# sourceMappingURL=native-periodic-wave-factory.js.map","export const createNativeScriptProcessorNode = (nativeContext, bufferSize, numberOfInputChannels, numberOfOutputChannels) => {\n return nativeContext.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels); // tslint:disable-line deprecation\n};\n//# sourceMappingURL=native-script-processor-node.js.map","import { assignNativeAudioNodeAudioParamValue } from '../helpers/assign-native-audio-node-audio-param-value';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeStereoPannerNodeFactory = (createNativeStereoPannerNodeFaker, createNotSupportedError) => {\n return (nativeContext, options) => {\n const channelCountMode = options.channelCountMode;\n /*\n * Bug #105: The channelCountMode of 'clamped-max' should be supported. However it is not possible to write a polyfill for Safari\n * which supports it and therefore it can't be supported at all.\n */\n if (channelCountMode === 'clamped-max') {\n throw createNotSupportedError();\n }\n // Bug #105: Safari does not support the StereoPannerNode.\n if (nativeContext.createStereoPanner === undefined) {\n return createNativeStereoPannerNodeFaker(nativeContext, options);\n }\n const nativeStereoPannerNode = nativeContext.createStereoPanner();\n assignNativeAudioNodeOptions(nativeStereoPannerNode, options);\n assignNativeAudioNodeAudioParamValue(nativeStereoPannerNode, options, 'pan');\n /*\n * Bug #105: The channelCountMode of 'clamped-max' should be supported. However it is not possible to write a polyfill for Safari\n * which supports it and therefore it can't be supported at all.\n */\n Object.defineProperty(nativeStereoPannerNode, 'channelCountMode', {\n get: () => channelCountMode,\n set: (value) => {\n if (value !== channelCountMode) {\n throw createNotSupportedError();\n }\n }\n });\n return nativeStereoPannerNode;\n };\n};\n//# sourceMappingURL=native-stereo-panner-node-factory.js.map","import { interceptConnections } from '../helpers/intercept-connections';\nexport const createNativeStereoPannerNodeFakerFactory = (createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeGainNode, createNativeWaveShaperNode, createNotSupportedError, monitorConnections) => {\n // The curve has a size of 14bit plus 1 value to have an exact representation for zero. This value has been determined experimentally.\n const CURVE_SIZE = 16385;\n const DC_CURVE = new Float32Array([1, 1]);\n const HALF_PI = Math.PI / 2;\n const SINGLE_CHANNEL_OPTIONS = { channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'discrete' };\n const SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS = { ...SINGLE_CHANNEL_OPTIONS, oversample: 'none' };\n const buildInternalGraphForMono = (nativeContext, inputGainNode, panGainNode, channelMergerNode) => {\n const leftWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const rightWaveShaperCurve = new Float32Array(CURVE_SIZE);\n for (let i = 0; i < CURVE_SIZE; i += 1) {\n const x = (i / (CURVE_SIZE - 1)) * HALF_PI;\n leftWaveShaperCurve[i] = Math.cos(x);\n rightWaveShaperCurve[i] = Math.sin(x);\n }\n const leftGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const leftWaveShaperNode = (createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: leftWaveShaperCurve }));\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const panWaveShaperNode = (createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: DC_CURVE }));\n const rightGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const rightWaveShaperNode = (createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: rightWaveShaperCurve }));\n return {\n connectGraph() {\n inputGainNode.connect(leftGainNode);\n inputGainNode.connect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n inputGainNode.connect(rightGainNode);\n panWaveShaperNode.connect(panGainNode);\n panGainNode.connect(leftWaveShaperNode.inputs === undefined ? leftWaveShaperNode : leftWaveShaperNode.inputs[0]);\n panGainNode.connect(rightWaveShaperNode.inputs === undefined ? rightWaveShaperNode : rightWaveShaperNode.inputs[0]);\n leftWaveShaperNode.connect(leftGainNode.gain);\n rightWaveShaperNode.connect(rightGainNode.gain);\n leftGainNode.connect(channelMergerNode, 0, 0);\n rightGainNode.connect(channelMergerNode, 0, 1);\n },\n disconnectGraph() {\n inputGainNode.disconnect(leftGainNode);\n inputGainNode.disconnect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n inputGainNode.disconnect(rightGainNode);\n panWaveShaperNode.disconnect(panGainNode);\n panGainNode.disconnect(leftWaveShaperNode.inputs === undefined ? leftWaveShaperNode : leftWaveShaperNode.inputs[0]);\n panGainNode.disconnect(rightWaveShaperNode.inputs === undefined ? rightWaveShaperNode : rightWaveShaperNode.inputs[0]);\n leftWaveShaperNode.disconnect(leftGainNode.gain);\n rightWaveShaperNode.disconnect(rightGainNode.gain);\n leftGainNode.disconnect(channelMergerNode, 0, 0);\n rightGainNode.disconnect(channelMergerNode, 0, 1);\n }\n };\n };\n const buildInternalGraphForStereo = (nativeContext, inputGainNode, panGainNode, channelMergerNode) => {\n const leftInputForLeftOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const leftInputForRightOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const rightInputForLeftOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const rightInputForRightOutputWaveShaperCurve = new Float32Array(CURVE_SIZE);\n const centerIndex = Math.floor(CURVE_SIZE / 2);\n for (let i = 0; i < CURVE_SIZE; i += 1) {\n if (i > centerIndex) {\n const x = ((i - centerIndex) / (CURVE_SIZE - 1 - centerIndex)) * HALF_PI;\n leftInputForLeftOutputWaveShaperCurve[i] = Math.cos(x);\n leftInputForRightOutputWaveShaperCurve[i] = Math.sin(x);\n rightInputForLeftOutputWaveShaperCurve[i] = 0;\n rightInputForRightOutputWaveShaperCurve[i] = 1;\n }\n else {\n const x = (i / (CURVE_SIZE - 1 - centerIndex)) * HALF_PI;\n leftInputForLeftOutputWaveShaperCurve[i] = 1;\n leftInputForRightOutputWaveShaperCurve[i] = 0;\n rightInputForLeftOutputWaveShaperCurve[i] = Math.cos(x);\n rightInputForRightOutputWaveShaperCurve[i] = Math.sin(x);\n }\n }\n const channelSplitterNode = createNativeChannelSplitterNode(nativeContext, {\n channelCount: 2,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n numberOfOutputs: 2\n });\n const leftInputForLeftOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const leftInputForLeftOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: leftInputForLeftOutputWaveShaperCurve\n });\n const leftInputForRightOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const leftInputForRightOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: leftInputForRightOutputWaveShaperCurve\n });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const panWaveShaperNode = (createNativeWaveShaperNode(nativeContext, { ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS, curve: DC_CURVE }));\n const rightInputForLeftOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const rightInputForLeftOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: rightInputForLeftOutputWaveShaperCurve\n });\n const rightInputForRightOutputGainNode = createNativeGainNode(nativeContext, { ...SINGLE_CHANNEL_OPTIONS, gain: 0 });\n // Bug #119: Safari does not fully support the WaveShaperNode.\n const rightInputForRightOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, {\n ...SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS,\n curve: rightInputForRightOutputWaveShaperCurve\n });\n return {\n connectGraph() {\n inputGainNode.connect(channelSplitterNode);\n inputGainNode.connect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n channelSplitterNode.connect(leftInputForLeftOutputGainNode, 0);\n channelSplitterNode.connect(leftInputForRightOutputGainNode, 0);\n channelSplitterNode.connect(rightInputForLeftOutputGainNode, 1);\n channelSplitterNode.connect(rightInputForRightOutputGainNode, 1);\n panWaveShaperNode.connect(panGainNode);\n panGainNode.connect(leftInputForLeftOutputWaveShaperNode.inputs === undefined\n ? leftInputForLeftOutputWaveShaperNode\n : leftInputForLeftOutputWaveShaperNode.inputs[0]);\n panGainNode.connect(leftInputForRightOutputWaveShaperNode.inputs === undefined\n ? leftInputForRightOutputWaveShaperNode\n : leftInputForRightOutputWaveShaperNode.inputs[0]);\n panGainNode.connect(rightInputForLeftOutputWaveShaperNode.inputs === undefined\n ? rightInputForLeftOutputWaveShaperNode\n : rightInputForLeftOutputWaveShaperNode.inputs[0]);\n panGainNode.connect(rightInputForRightOutputWaveShaperNode.inputs === undefined\n ? rightInputForRightOutputWaveShaperNode\n : rightInputForRightOutputWaveShaperNode.inputs[0]);\n leftInputForLeftOutputWaveShaperNode.connect(leftInputForLeftOutputGainNode.gain);\n leftInputForRightOutputWaveShaperNode.connect(leftInputForRightOutputGainNode.gain);\n rightInputForLeftOutputWaveShaperNode.connect(rightInputForLeftOutputGainNode.gain);\n rightInputForRightOutputWaveShaperNode.connect(rightInputForRightOutputGainNode.gain);\n leftInputForLeftOutputGainNode.connect(channelMergerNode, 0, 0);\n rightInputForLeftOutputGainNode.connect(channelMergerNode, 0, 0);\n leftInputForRightOutputGainNode.connect(channelMergerNode, 0, 1);\n rightInputForRightOutputGainNode.connect(channelMergerNode, 0, 1);\n },\n disconnectGraph() {\n inputGainNode.disconnect(channelSplitterNode);\n inputGainNode.disconnect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]);\n channelSplitterNode.disconnect(leftInputForLeftOutputGainNode, 0);\n channelSplitterNode.disconnect(leftInputForRightOutputGainNode, 0);\n channelSplitterNode.disconnect(rightInputForLeftOutputGainNode, 1);\n channelSplitterNode.disconnect(rightInputForRightOutputGainNode, 1);\n panWaveShaperNode.disconnect(panGainNode);\n panGainNode.disconnect(leftInputForLeftOutputWaveShaperNode.inputs === undefined\n ? leftInputForLeftOutputWaveShaperNode\n : leftInputForLeftOutputWaveShaperNode.inputs[0]);\n panGainNode.disconnect(leftInputForRightOutputWaveShaperNode.inputs === undefined\n ? leftInputForRightOutputWaveShaperNode\n : leftInputForRightOutputWaveShaperNode.inputs[0]);\n panGainNode.disconnect(rightInputForLeftOutputWaveShaperNode.inputs === undefined\n ? rightInputForLeftOutputWaveShaperNode\n : rightInputForLeftOutputWaveShaperNode.inputs[0]);\n panGainNode.disconnect(rightInputForRightOutputWaveShaperNode.inputs === undefined\n ? rightInputForRightOutputWaveShaperNode\n : rightInputForRightOutputWaveShaperNode.inputs[0]);\n leftInputForLeftOutputWaveShaperNode.disconnect(leftInputForLeftOutputGainNode.gain);\n leftInputForRightOutputWaveShaperNode.disconnect(leftInputForRightOutputGainNode.gain);\n rightInputForLeftOutputWaveShaperNode.disconnect(rightInputForLeftOutputGainNode.gain);\n rightInputForRightOutputWaveShaperNode.disconnect(rightInputForRightOutputGainNode.gain);\n leftInputForLeftOutputGainNode.disconnect(channelMergerNode, 0, 0);\n rightInputForLeftOutputGainNode.disconnect(channelMergerNode, 0, 0);\n leftInputForRightOutputGainNode.disconnect(channelMergerNode, 0, 1);\n rightInputForRightOutputGainNode.disconnect(channelMergerNode, 0, 1);\n }\n };\n };\n const buildInternalGraph = (nativeContext, channelCount, inputGainNode, panGainNode, channelMergerNode) => {\n if (channelCount === 1) {\n return buildInternalGraphForMono(nativeContext, inputGainNode, panGainNode, channelMergerNode);\n }\n if (channelCount === 2) {\n return buildInternalGraphForStereo(nativeContext, inputGainNode, panGainNode, channelMergerNode);\n }\n throw createNotSupportedError();\n };\n return (nativeContext, { channelCount, channelCountMode, pan, ...audioNodeOptions }) => {\n if (channelCountMode === 'max') {\n throw createNotSupportedError();\n }\n const channelMergerNode = createNativeChannelMergerNode(nativeContext, {\n ...audioNodeOptions,\n channelCount: 1,\n channelCountMode,\n numberOfInputs: 2\n });\n const inputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, channelCount, channelCountMode, gain: 1 });\n const panGainNode = createNativeGainNode(nativeContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: pan\n });\n let { connectGraph, disconnectGraph } = buildInternalGraph(nativeContext, channelCount, inputGainNode, panGainNode, channelMergerNode);\n Object.defineProperty(panGainNode.gain, 'defaultValue', { get: () => 0 });\n Object.defineProperty(panGainNode.gain, 'maxValue', { get: () => 1 });\n Object.defineProperty(panGainNode.gain, 'minValue', { get: () => -1 });\n const nativeStereoPannerNodeFakerFactory = {\n get bufferSize() {\n return undefined;\n },\n get channelCount() {\n return inputGainNode.channelCount;\n },\n set channelCount(value) {\n if (inputGainNode.channelCount !== value) {\n if (isConnected) {\n disconnectGraph();\n }\n ({ connectGraph, disconnectGraph } = buildInternalGraph(nativeContext, value, inputGainNode, panGainNode, channelMergerNode));\n if (isConnected) {\n connectGraph();\n }\n }\n inputGainNode.channelCount = value;\n },\n get channelCountMode() {\n return inputGainNode.channelCountMode;\n },\n set channelCountMode(value) {\n if (value === 'clamped-max' || value === 'max') {\n throw createNotSupportedError();\n }\n inputGainNode.channelCountMode = value;\n },\n get channelInterpretation() {\n return inputGainNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n inputGainNode.channelInterpretation = value;\n },\n get context() {\n return inputGainNode.context;\n },\n get inputs() {\n return [inputGainNode];\n },\n get numberOfInputs() {\n return inputGainNode.numberOfInputs;\n },\n get numberOfOutputs() {\n return inputGainNode.numberOfOutputs;\n },\n get pan() {\n return panGainNode.gain;\n },\n addEventListener(...args) {\n return inputGainNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args) {\n return inputGainNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args) {\n return inputGainNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n let isConnected = false;\n const whenConnected = () => {\n connectGraph();\n isConnected = true;\n };\n const whenDisconnected = () => {\n disconnectGraph();\n isConnected = false;\n };\n return monitorConnections(interceptConnections(nativeStereoPannerNodeFakerFactory, channelMergerNode), whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=native-stereo-panner-node-faker-factory.js.map","import { assignNativeAudioNodeOption } from '../helpers/assign-native-audio-node-option';\nimport { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nexport const createNativeWaveShaperNodeFactory = (createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeWaveShaperNodeFaker, isDCCurve, monitorConnections, nativeAudioContextConstructor, overwriteAccessors) => {\n return (nativeContext, options) => {\n const nativeWaveShaperNode = nativeContext.createWaveShaper();\n /*\n * Bug #119: Safari does not correctly map the values.\n * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the existence of\n * the webkitAudioContext is used as a workaround here. Testing for the automationRate property is necessary because this workaround\n * isn't necessary anymore since v14.0.2 of Safari.\n */\n if (nativeAudioContextConstructor !== null &&\n nativeAudioContextConstructor.name === 'webkitAudioContext' &&\n nativeContext.createGain().gain.automationRate === undefined) {\n return createNativeWaveShaperNodeFaker(nativeContext, options);\n }\n assignNativeAudioNodeOptions(nativeWaveShaperNode, options);\n const curve = options.curve === null || options.curve instanceof Float32Array ? options.curve : new Float32Array(options.curve);\n // Bug #104: Chrome and Edge will throw an InvalidAccessError when the curve has less than two samples.\n if (curve !== null && curve.length < 2) {\n throw createInvalidStateError();\n }\n // Only values of type Float32Array can be assigned to the curve property.\n assignNativeAudioNodeOption(nativeWaveShaperNode, { curve }, 'curve');\n assignNativeAudioNodeOption(nativeWaveShaperNode, options, 'oversample');\n let disconnectNativeAudioBufferSourceNode = null;\n let isConnected = false;\n overwriteAccessors(nativeWaveShaperNode, 'curve', (get) => () => get.call(nativeWaveShaperNode), (set) => (value) => {\n set.call(nativeWaveShaperNode, value);\n if (isConnected) {\n if (isDCCurve(value) && disconnectNativeAudioBufferSourceNode === null) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, nativeWaveShaperNode);\n }\n else if (!isDCCurve(value) && disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n }\n return value;\n });\n const whenConnected = () => {\n isConnected = true;\n if (isDCCurve(nativeWaveShaperNode.curve)) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, nativeWaveShaperNode);\n }\n };\n const whenDisconnected = () => {\n isConnected = false;\n if (disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n };\n return monitorConnections(nativeWaveShaperNode, whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=native-wave-shaper-node-factory.js.map","import { assignNativeAudioNodeOptions } from '../helpers/assign-native-audio-node-options';\nimport { interceptConnections } from '../helpers/intercept-connections';\nexport const createNativeWaveShaperNodeFakerFactory = (createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeGainNode, isDCCurve, monitorConnections) => {\n return (nativeContext, { curve, oversample, ...audioNodeOptions }) => {\n const negativeWaveShaperNode = nativeContext.createWaveShaper();\n const positiveWaveShaperNode = nativeContext.createWaveShaper();\n assignNativeAudioNodeOptions(negativeWaveShaperNode, audioNodeOptions);\n assignNativeAudioNodeOptions(positiveWaveShaperNode, audioNodeOptions);\n const inputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: 1 });\n const invertGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: -1 });\n const outputGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: 1 });\n const revertGainNode = createNativeGainNode(nativeContext, { ...audioNodeOptions, gain: -1 });\n let disconnectNativeAudioBufferSourceNode = null;\n let isConnected = false;\n let unmodifiedCurve = null;\n const nativeWaveShaperNodeFaker = {\n get bufferSize() {\n return undefined;\n },\n get channelCount() {\n return negativeWaveShaperNode.channelCount;\n },\n set channelCount(value) {\n inputGainNode.channelCount = value;\n invertGainNode.channelCount = value;\n negativeWaveShaperNode.channelCount = value;\n outputGainNode.channelCount = value;\n positiveWaveShaperNode.channelCount = value;\n revertGainNode.channelCount = value;\n },\n get channelCountMode() {\n return negativeWaveShaperNode.channelCountMode;\n },\n set channelCountMode(value) {\n inputGainNode.channelCountMode = value;\n invertGainNode.channelCountMode = value;\n negativeWaveShaperNode.channelCountMode = value;\n outputGainNode.channelCountMode = value;\n positiveWaveShaperNode.channelCountMode = value;\n revertGainNode.channelCountMode = value;\n },\n get channelInterpretation() {\n return negativeWaveShaperNode.channelInterpretation;\n },\n set channelInterpretation(value) {\n inputGainNode.channelInterpretation = value;\n invertGainNode.channelInterpretation = value;\n negativeWaveShaperNode.channelInterpretation = value;\n outputGainNode.channelInterpretation = value;\n positiveWaveShaperNode.channelInterpretation = value;\n revertGainNode.channelInterpretation = value;\n },\n get context() {\n return negativeWaveShaperNode.context;\n },\n get curve() {\n return unmodifiedCurve;\n },\n set curve(value) {\n // Bug #102: Safari does not throw an InvalidStateError when the curve has less than two samples.\n if (value !== null && value.length < 2) {\n throw createInvalidStateError();\n }\n if (value === null) {\n negativeWaveShaperNode.curve = value;\n positiveWaveShaperNode.curve = value;\n }\n else {\n const curveLength = value.length;\n const negativeCurve = new Float32Array(curveLength + 2 - (curveLength % 2));\n const positiveCurve = new Float32Array(curveLength + 2 - (curveLength % 2));\n negativeCurve[0] = value[0];\n positiveCurve[0] = -value[curveLength - 1];\n const length = Math.ceil((curveLength + 1) / 2);\n const centerIndex = (curveLength + 1) / 2 - 1;\n for (let i = 1; i < length; i += 1) {\n const theoreticIndex = (i / length) * centerIndex;\n const lowerIndex = Math.floor(theoreticIndex);\n const upperIndex = Math.ceil(theoreticIndex);\n negativeCurve[i] =\n lowerIndex === upperIndex\n ? value[lowerIndex]\n : (1 - (theoreticIndex - lowerIndex)) * value[lowerIndex] +\n (1 - (upperIndex - theoreticIndex)) * value[upperIndex];\n positiveCurve[i] =\n lowerIndex === upperIndex\n ? -value[curveLength - 1 - lowerIndex]\n : -((1 - (theoreticIndex - lowerIndex)) * value[curveLength - 1 - lowerIndex]) -\n (1 - (upperIndex - theoreticIndex)) * value[curveLength - 1 - upperIndex];\n }\n negativeCurve[length] = curveLength % 2 === 1 ? value[length - 1] : (value[length - 2] + value[length - 1]) / 2;\n negativeWaveShaperNode.curve = negativeCurve;\n positiveWaveShaperNode.curve = positiveCurve;\n }\n unmodifiedCurve = value;\n if (isConnected) {\n if (isDCCurve(unmodifiedCurve) && disconnectNativeAudioBufferSourceNode === null) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, inputGainNode);\n }\n else if (disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n }\n },\n get inputs() {\n return [inputGainNode];\n },\n get numberOfInputs() {\n return negativeWaveShaperNode.numberOfInputs;\n },\n get numberOfOutputs() {\n return negativeWaveShaperNode.numberOfOutputs;\n },\n get oversample() {\n return negativeWaveShaperNode.oversample;\n },\n set oversample(value) {\n negativeWaveShaperNode.oversample = value;\n positiveWaveShaperNode.oversample = value;\n },\n addEventListener(...args) {\n return inputGainNode.addEventListener(args[0], args[1], args[2]);\n },\n dispatchEvent(...args) {\n return inputGainNode.dispatchEvent(args[0]);\n },\n removeEventListener(...args) {\n return inputGainNode.removeEventListener(args[0], args[1], args[2]);\n }\n };\n if (curve !== null) {\n // Only values of type Float32Array can be assigned to the curve property.\n nativeWaveShaperNodeFaker.curve = curve instanceof Float32Array ? curve : new Float32Array(curve);\n }\n if (oversample !== nativeWaveShaperNodeFaker.oversample) {\n nativeWaveShaperNodeFaker.oversample = oversample;\n }\n const whenConnected = () => {\n inputGainNode.connect(negativeWaveShaperNode).connect(outputGainNode);\n inputGainNode.connect(invertGainNode).connect(positiveWaveShaperNode).connect(revertGainNode).connect(outputGainNode);\n isConnected = true;\n if (isDCCurve(unmodifiedCurve)) {\n disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, inputGainNode);\n }\n };\n const whenDisconnected = () => {\n inputGainNode.disconnect(negativeWaveShaperNode);\n negativeWaveShaperNode.disconnect(outputGainNode);\n inputGainNode.disconnect(invertGainNode);\n invertGainNode.disconnect(positiveWaveShaperNode);\n positiveWaveShaperNode.disconnect(revertGainNode);\n revertGainNode.disconnect(outputGainNode);\n isConnected = false;\n if (disconnectNativeAudioBufferSourceNode !== null) {\n disconnectNativeAudioBufferSourceNode();\n disconnectNativeAudioBufferSourceNode = null;\n }\n };\n return monitorConnections(interceptConnections(nativeWaveShaperNodeFaker, outputGainNode), whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=native-wave-shaper-node-faker-factory.js.map","export const createNotSupportedError = () => new DOMException('', 'NotSupportedError');\n//# sourceMappingURL=not-supported-error.js.map","import { deactivateAudioGraph } from '../helpers/deactivate-audio-graph';\nimport { testPromiseSupport } from '../helpers/test-promise-support';\nconst DEFAULT_OPTIONS = {\n numberOfChannels: 1\n};\nexport const createOfflineAudioContextConstructor = (baseAudioContextConstructor, cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, startRendering) => {\n return class OfflineAudioContext extends baseAudioContextConstructor {\n constructor(a, b, c) {\n let options;\n if (typeof a === 'number' && b !== undefined && c !== undefined) {\n options = { length: b, numberOfChannels: a, sampleRate: c };\n }\n else if (typeof a === 'object') {\n options = a;\n }\n else {\n throw new Error('The given parameters are not valid.');\n }\n const { length, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS, ...options };\n const nativeOfflineAudioContext = createNativeOfflineAudioContext(numberOfChannels, length, sampleRate);\n // #21 Safari does not support promises and therefore would fire the statechange event before the promise can be resolved.\n if (!cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {\n nativeOfflineAudioContext.addEventListener('statechange', (() => {\n let i = 0;\n const delayStateChangeEvent = (event) => {\n if (this._state === 'running') {\n if (i > 0) {\n nativeOfflineAudioContext.removeEventListener('statechange', delayStateChangeEvent);\n event.stopImmediatePropagation();\n this._waitForThePromiseToSettle(event);\n }\n else {\n i += 1;\n }\n }\n };\n return delayStateChangeEvent;\n })());\n }\n super(nativeOfflineAudioContext, numberOfChannels);\n this._length = length;\n this._nativeOfflineAudioContext = nativeOfflineAudioContext;\n this._state = null;\n }\n get length() {\n // Bug #17: Safari does not yet expose the length.\n if (this._nativeOfflineAudioContext.length === undefined) {\n return this._length;\n }\n return this._nativeOfflineAudioContext.length;\n }\n get state() {\n return this._state === null ? this._nativeOfflineAudioContext.state : this._state;\n }\n startRendering() {\n /*\n * Bug #9 & #59: It is theoretically possible that startRendering() will first render a partialOfflineAudioContext. Therefore\n * the state of the nativeOfflineAudioContext might no transition to running immediately.\n */\n if (this._state === 'running') {\n return Promise.reject(createInvalidStateError());\n }\n this._state = 'running';\n return startRendering(this.destination, this._nativeOfflineAudioContext).finally(() => {\n this._state = null;\n deactivateAudioGraph(this);\n });\n }\n _waitForThePromiseToSettle(event) {\n if (this._state === null) {\n this._nativeOfflineAudioContext.dispatchEvent(event);\n }\n else {\n setTimeout(() => this._waitForThePromiseToSettle(event));\n }\n }\n };\n};\n//# sourceMappingURL=offline-audio-context-constructor.js.map","import { isActiveAudioNode } from '../helpers/is-active-audio-node';\nimport { setInternalStateToActive } from '../helpers/set-internal-state-to-active';\nimport { setInternalStateToPassive } from '../helpers/set-internal-state-to-passive';\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n detune: 0,\n frequency: 440,\n periodicWave: undefined,\n type: 'sine'\n};\nexport const createOscillatorNodeConstructor = (audioNodeConstructor, createAudioParam, createNativeOscillatorNode, createOscillatorNodeRenderer, getNativeContext, isNativeOfflineAudioContext, wrapEventListener) => {\n return class OscillatorNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeOscillatorNode = createNativeOscillatorNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const oscillatorNodeRenderer = (isOffline ? createOscillatorNodeRenderer() : null);\n const nyquist = context.sampleRate / 2;\n super(context, false, nativeOscillatorNode, oscillatorNodeRenderer);\n // Bug #81: Firefox & Safari do not export the correct values for maxValue and minValue.\n this._detune = createAudioParam(this, isOffline, nativeOscillatorNode.detune, 153600, -153600);\n // Bug #76: Safari does not export the correct values for maxValue and minValue.\n this._frequency = createAudioParam(this, isOffline, nativeOscillatorNode.frequency, nyquist, -nyquist);\n this._nativeOscillatorNode = nativeOscillatorNode;\n this._onended = null;\n this._oscillatorNodeRenderer = oscillatorNodeRenderer;\n if (this._oscillatorNodeRenderer !== null && mergedOptions.periodicWave !== undefined) {\n this._oscillatorNodeRenderer.periodicWave =\n mergedOptions.periodicWave;\n }\n }\n get detune() {\n return this._detune;\n }\n get frequency() {\n return this._frequency;\n }\n get onended() {\n return this._onended;\n }\n set onended(value) {\n const wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null;\n this._nativeOscillatorNode.onended = wrappedListener;\n const nativeOnEnded = this._nativeOscillatorNode.onended;\n this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;\n }\n get type() {\n return this._nativeOscillatorNode.type;\n }\n set type(value) {\n this._nativeOscillatorNode.type = value;\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.periodicWave = null;\n }\n }\n setPeriodicWave(periodicWave) {\n this._nativeOscillatorNode.setPeriodicWave(periodicWave);\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.periodicWave = periodicWave;\n }\n }\n start(when = 0) {\n this._nativeOscillatorNode.start(when);\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.start = when;\n }\n if (this.context.state !== 'closed') {\n setInternalStateToActive(this);\n const resetInternalStateToPassive = () => {\n this._nativeOscillatorNode.removeEventListener('ended', resetInternalStateToPassive);\n if (isActiveAudioNode(this)) {\n setInternalStateToPassive(this);\n }\n };\n this._nativeOscillatorNode.addEventListener('ended', resetInternalStateToPassive);\n }\n }\n stop(when = 0) {\n this._nativeOscillatorNode.stop(when);\n if (this._oscillatorNodeRenderer !== null) {\n this._oscillatorNodeRenderer.stop = when;\n }\n }\n };\n};\n//# sourceMappingURL=oscillator-node-constructor.js.map","import { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createOscillatorNodeRendererFactory = (connectAudioParam, createNativeOscillatorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeOscillatorNodes = new WeakMap();\n let periodicWave = null;\n let start = null;\n let stop = null;\n const createOscillatorNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeOscillatorNode = getNativeAudioNode(proxy);\n // If the initially used nativeOscillatorNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeOscillatorNodeIsOwnedByContext = isOwnedByContext(nativeOscillatorNode, nativeOfflineAudioContext);\n if (!nativeOscillatorNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeOscillatorNode.channelCount,\n channelCountMode: nativeOscillatorNode.channelCountMode,\n channelInterpretation: nativeOscillatorNode.channelInterpretation,\n detune: nativeOscillatorNode.detune.value,\n frequency: nativeOscillatorNode.frequency.value,\n periodicWave: periodicWave === null ? undefined : periodicWave,\n type: nativeOscillatorNode.type\n };\n nativeOscillatorNode = createNativeOscillatorNode(nativeOfflineAudioContext, options);\n if (start !== null) {\n nativeOscillatorNode.start(start);\n }\n if (stop !== null) {\n nativeOscillatorNode.stop(stop);\n }\n }\n renderedNativeOscillatorNodes.set(nativeOfflineAudioContext, nativeOscillatorNode);\n if (!nativeOscillatorNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.detune, nativeOscillatorNode.detune);\n await renderAutomation(nativeOfflineAudioContext, proxy.frequency, nativeOscillatorNode.frequency);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.detune, nativeOscillatorNode.detune);\n await connectAudioParam(nativeOfflineAudioContext, proxy.frequency, nativeOscillatorNode.frequency);\n }\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeOscillatorNode);\n return nativeOscillatorNode;\n };\n return {\n set periodicWave(value) {\n periodicWave = value;\n },\n set start(value) {\n start = value;\n },\n set stop(value) {\n stop = value;\n },\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeOscillatorNode = renderedNativeOscillatorNodes.get(nativeOfflineAudioContext);\n if (renderedNativeOscillatorNode !== undefined) {\n return Promise.resolve(renderedNativeOscillatorNode);\n }\n return createOscillatorNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=oscillator-node-renderer-factory.js.map","import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';\nconst DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'clamped-max',\n channelInterpretation: 'speakers',\n coneInnerAngle: 360,\n coneOuterAngle: 360,\n coneOuterGain: 0,\n distanceModel: 'inverse',\n maxDistance: 10000,\n orientationX: 1,\n orientationY: 0,\n orientationZ: 0,\n panningModel: 'equalpower',\n positionX: 0,\n positionY: 0,\n positionZ: 0,\n refDistance: 1,\n rolloffFactor: 1\n};\nexport const createPannerNodeConstructor = (audioNodeConstructor, createAudioParam, createNativePannerNode, createPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class PannerNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativePannerNode = createNativePannerNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const pannerNodeRenderer = (isOffline ? createPannerNodeRenderer() : null);\n super(context, false, nativePannerNode, pannerNodeRenderer);\n this._nativePannerNode = nativePannerNode;\n // Bug #74: Safari does not export the correct values for maxValue and minValue.\n this._orientationX = createAudioParam(this, isOffline, nativePannerNode.orientationX, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n this._orientationY = createAudioParam(this, isOffline, nativePannerNode.orientationY, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n this._orientationZ = createAudioParam(this, isOffline, nativePannerNode.orientationZ, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n this._positionX = createAudioParam(this, isOffline, nativePannerNode.positionX, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n this._positionY = createAudioParam(this, isOffline, nativePannerNode.positionY, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n this._positionZ = createAudioParam(this, isOffline, nativePannerNode.positionZ, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n get coneInnerAngle() {\n return this._nativePannerNode.coneInnerAngle;\n }\n set coneInnerAngle(value) {\n this._nativePannerNode.coneInnerAngle = value;\n }\n get coneOuterAngle() {\n return this._nativePannerNode.coneOuterAngle;\n }\n set coneOuterAngle(value) {\n this._nativePannerNode.coneOuterAngle = value;\n }\n get coneOuterGain() {\n return this._nativePannerNode.coneOuterGain;\n }\n set coneOuterGain(value) {\n this._nativePannerNode.coneOuterGain = value;\n }\n get distanceModel() {\n return this._nativePannerNode.distanceModel;\n }\n set distanceModel(value) {\n this._nativePannerNode.distanceModel = value;\n }\n get maxDistance() {\n return this._nativePannerNode.maxDistance;\n }\n set maxDistance(value) {\n this._nativePannerNode.maxDistance = value;\n }\n get orientationX() {\n return this._orientationX;\n }\n get orientationY() {\n return this._orientationY;\n }\n get orientationZ() {\n return this._orientationZ;\n }\n get panningModel() {\n return this._nativePannerNode.panningModel;\n }\n set panningModel(value) {\n this._nativePannerNode.panningModel = value;\n }\n get positionX() {\n return this._positionX;\n }\n get positionY() {\n return this._positionY;\n }\n get positionZ() {\n return this._positionZ;\n }\n get refDistance() {\n return this._nativePannerNode.refDistance;\n }\n set refDistance(value) {\n this._nativePannerNode.refDistance = value;\n }\n get rolloffFactor() {\n return this._nativePannerNode.rolloffFactor;\n }\n set rolloffFactor(value) {\n this._nativePannerNode.rolloffFactor = value;\n }\n };\n};\n//# sourceMappingURL=panner-node-constructor.js.map","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createPannerNodeRendererFactory = (connectAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeGainNode, createNativePannerNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext) => {\n return () => {\n const renderedNativeAudioNodes = new WeakMap();\n let renderedBufferPromise = null;\n const createAudioNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeGainNode = null;\n let nativePannerNode = getNativeAudioNode(proxy);\n const commonAudioNodeOptions = {\n channelCount: nativePannerNode.channelCount,\n channelCountMode: nativePannerNode.channelCountMode,\n channelInterpretation: nativePannerNode.channelInterpretation\n };\n const commonNativePannerNodeOptions = {\n ...commonAudioNodeOptions,\n coneInnerAngle: nativePannerNode.coneInnerAngle,\n coneOuterAngle: nativePannerNode.coneOuterAngle,\n coneOuterGain: nativePannerNode.coneOuterGain,\n distanceModel: nativePannerNode.distanceModel,\n maxDistance: nativePannerNode.maxDistance,\n panningModel: nativePannerNode.panningModel,\n refDistance: nativePannerNode.refDistance,\n rolloffFactor: nativePannerNode.rolloffFactor\n };\n // If the initially used nativePannerNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativePannerNodeIsOwnedByContext = isOwnedByContext(nativePannerNode, nativeOfflineAudioContext);\n // Bug #124: Safari does not support modifying the orientation and the position with AudioParams.\n if ('bufferSize' in nativePannerNode) {\n nativeGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 1 });\n }\n else if (!nativePannerNodeIsOwnedByContext) {\n const options = {\n ...commonNativePannerNodeOptions,\n orientationX: nativePannerNode.orientationX.value,\n orientationY: nativePannerNode.orientationY.value,\n orientationZ: nativePannerNode.orientationZ.value,\n positionX: nativePannerNode.positionX.value,\n positionY: nativePannerNode.positionY.value,\n positionZ: nativePannerNode.positionZ.value\n };\n nativePannerNode = createNativePannerNode(nativeOfflineAudioContext, options);\n }\n renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeGainNode === null ? nativePannerNode : nativeGainNode);\n if (nativeGainNode !== null) {\n if (renderedBufferPromise === null) {\n if (nativeOfflineAudioContextConstructor === null) {\n throw new Error('Missing the native OfflineAudioContext constructor.');\n }\n const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(6, \n // Bug #17: Safari does not yet expose the length.\n proxy.context.length, nativeOfflineAudioContext.sampleRate);\n const nativeChannelMergerNode = createNativeChannelMergerNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n numberOfInputs: 6\n });\n nativeChannelMergerNode.connect(partialOfflineAudioContext.destination);\n renderedBufferPromise = (async () => {\n const nativeConstantSourceNodes = await Promise.all([\n proxy.orientationX,\n proxy.orientationY,\n proxy.orientationZ,\n proxy.positionX,\n proxy.positionY,\n proxy.positionZ\n ].map(async (audioParam, index) => {\n const nativeConstantSourceNode = createNativeConstantSourceNode(partialOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n offset: index === 0 ? 1 : 0\n });\n await renderAutomation(partialOfflineAudioContext, audioParam, nativeConstantSourceNode.offset);\n return nativeConstantSourceNode;\n }));\n for (let i = 0; i < 6; i += 1) {\n nativeConstantSourceNodes[i].connect(nativeChannelMergerNode, 0, i);\n nativeConstantSourceNodes[i].start(0);\n }\n return renderNativeOfflineAudioContext(partialOfflineAudioContext);\n })();\n }\n const renderedBuffer = await renderedBufferPromise;\n const inputGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 1 });\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, inputGainNode);\n const channelDatas = [];\n for (let i = 0; i < renderedBuffer.numberOfChannels; i += 1) {\n channelDatas.push(renderedBuffer.getChannelData(i));\n }\n let lastOrientation = [channelDatas[0][0], channelDatas[1][0], channelDatas[2][0]];\n let lastPosition = [channelDatas[3][0], channelDatas[4][0], channelDatas[5][0]];\n let gateGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 1 });\n let partialPannerNode = createNativePannerNode(nativeOfflineAudioContext, {\n ...commonNativePannerNodeOptions,\n orientationX: lastOrientation[0],\n orientationY: lastOrientation[1],\n orientationZ: lastOrientation[2],\n positionX: lastPosition[0],\n positionY: lastPosition[1],\n positionZ: lastPosition[2]\n });\n inputGainNode.connect(gateGainNode).connect(partialPannerNode.inputs[0]);\n partialPannerNode.connect(nativeGainNode);\n for (let i = 128; i < renderedBuffer.length; i += 128) {\n const orientation = [channelDatas[0][i], channelDatas[1][i], channelDatas[2][i]];\n const positon = [channelDatas[3][i], channelDatas[4][i], channelDatas[5][i]];\n if (orientation.some((value, index) => value !== lastOrientation[index]) ||\n positon.some((value, index) => value !== lastPosition[index])) {\n lastOrientation = orientation;\n lastPosition = positon;\n const currentTime = i / nativeOfflineAudioContext.sampleRate;\n gateGainNode.gain.setValueAtTime(0, currentTime);\n gateGainNode = createNativeGainNode(nativeOfflineAudioContext, { ...commonAudioNodeOptions, gain: 0 });\n partialPannerNode = createNativePannerNode(nativeOfflineAudioContext, {\n ...commonNativePannerNodeOptions,\n orientationX: lastOrientation[0],\n orientationY: lastOrientation[1],\n orientationZ: lastOrientation[2],\n positionX: lastPosition[0],\n positionY: lastPosition[1],\n positionZ: lastPosition[2]\n });\n gateGainNode.gain.setValueAtTime(1, currentTime);\n inputGainNode.connect(gateGainNode).connect(partialPannerNode.inputs[0]);\n partialPannerNode.connect(nativeGainNode);\n }\n }\n return nativeGainNode;\n }\n if (!nativePannerNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.orientationX, nativePannerNode.orientationX);\n await renderAutomation(nativeOfflineAudioContext, proxy.orientationY, nativePannerNode.orientationY);\n await renderAutomation(nativeOfflineAudioContext, proxy.orientationZ, nativePannerNode.orientationZ);\n await renderAutomation(nativeOfflineAudioContext, proxy.positionX, nativePannerNode.positionX);\n await renderAutomation(nativeOfflineAudioContext, proxy.positionY, nativePannerNode.positionY);\n await renderAutomation(nativeOfflineAudioContext, proxy.positionZ, nativePannerNode.positionZ);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.orientationX, nativePannerNode.orientationX);\n await connectAudioParam(nativeOfflineAudioContext, proxy.orientationY, nativePannerNode.orientationY);\n await connectAudioParam(nativeOfflineAudioContext, proxy.orientationZ, nativePannerNode.orientationZ);\n await connectAudioParam(nativeOfflineAudioContext, proxy.positionX, nativePannerNode.positionX);\n await connectAudioParam(nativeOfflineAudioContext, proxy.positionY, nativePannerNode.positionY);\n await connectAudioParam(nativeOfflineAudioContext, proxy.positionZ, nativePannerNode.positionZ);\n }\n if (isNativeAudioNodeFaker(nativePannerNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativePannerNode.inputs[0]);\n }\n else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativePannerNode);\n }\n return nativePannerNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeGainNodeOrNativePannerNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);\n if (renderedNativeGainNodeOrNativePannerNode !== undefined) {\n return Promise.resolve(renderedNativeGainNodeOrNativePannerNode);\n }\n return createAudioNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=panner-node-renderer-factory.js.map","const DEFAULT_OPTIONS = {\n disableNormalization: false\n};\nexport const createPeriodicWaveConstructor = (createNativePeriodicWave, getNativeContext, periodicWaveStore, sanitizePeriodicWaveOptions) => {\n return class PeriodicWave {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = sanitizePeriodicWaveOptions({ ...DEFAULT_OPTIONS, ...options });\n const periodicWave = createNativePeriodicWave(nativeContext, mergedOptions);\n periodicWaveStore.add(periodicWave);\n // This does violate all good pratices but it is used here to simplify the handling of periodic waves.\n return periodicWave;\n }\n static [Symbol.hasInstance](instance) {\n return ((instance !== null && typeof instance === 'object' && Object.getPrototypeOf(instance) === PeriodicWave.prototype) ||\n periodicWaveStore.has(instance));\n }\n };\n};\n//# sourceMappingURL=periodic-wave-constructor.js.map","export const createRenderAutomation = (getAudioParamRenderer, renderInputsOfAudioParam) => {\n return (nativeOfflineAudioContext, audioParam, nativeAudioParam) => {\n const audioParamRenderer = getAudioParamRenderer(audioParam);\n audioParamRenderer.replay(nativeAudioParam);\n return renderInputsOfAudioParam(audioParam, nativeOfflineAudioContext, nativeAudioParam);\n };\n};\n//# sourceMappingURL=render-automation.js.map","export const createRenderInputsOfAudioNode = (getAudioNodeConnections, getAudioNodeRenderer, isPartOfACycle) => {\n return async (audioNode, nativeOfflineAudioContext, nativeAudioNode) => {\n const audioNodeConnections = getAudioNodeConnections(audioNode);\n await Promise.all(audioNodeConnections.activeInputs\n .map((connections, input) => Array.from(connections).map(async ([source, output]) => {\n const audioNodeRenderer = getAudioNodeRenderer(source);\n const renderedNativeAudioNode = await audioNodeRenderer.render(source, nativeOfflineAudioContext);\n const destination = audioNode.context.destination;\n if (!isPartOfACycle(source) && (audioNode !== destination || !isPartOfACycle(audioNode))) {\n renderedNativeAudioNode.connect(nativeAudioNode, output, input);\n }\n }))\n .reduce((allRenderingPromises, renderingPromises) => [...allRenderingPromises, ...renderingPromises], []));\n };\n};\n//# sourceMappingURL=render-inputs-of-audio-node.js.map","export const createRenderInputsOfAudioParam = (getAudioNodeRenderer, getAudioParamConnections, isPartOfACycle) => {\n return async (audioParam, nativeOfflineAudioContext, nativeAudioParam) => {\n const audioParamConnections = getAudioParamConnections(audioParam);\n await Promise.all(Array.from(audioParamConnections.activeInputs).map(async ([source, output]) => {\n const audioNodeRenderer = getAudioNodeRenderer(source);\n const renderedNativeAudioNode = await audioNodeRenderer.render(source, nativeOfflineAudioContext);\n if (!isPartOfACycle(source)) {\n renderedNativeAudioNode.connect(nativeAudioParam, output);\n }\n }));\n };\n};\n//# sourceMappingURL=render-inputs-of-audio-param.js.map","import { testPromiseSupport } from '../helpers/test-promise-support';\nexport const createRenderNativeOfflineAudioContext = (cacheTestResult, createNativeGainNode, createNativeScriptProcessorNode, testOfflineAudioContextCurrentTimeSupport) => {\n return (nativeOfflineAudioContext) => {\n // Bug #21: Safari does not support promises yet.\n if (cacheTestResult(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {\n // Bug #158: Chrome and Edge do not advance currentTime if it is not accessed while rendering the audio.\n return Promise.resolve(cacheTestResult(testOfflineAudioContextCurrentTimeSupport, testOfflineAudioContextCurrentTimeSupport)).then((isOfflineAudioContextCurrentTimeSupported) => {\n if (!isOfflineAudioContextCurrentTimeSupported) {\n const scriptProcessorNode = createNativeScriptProcessorNode(nativeOfflineAudioContext, 512, 0, 1);\n nativeOfflineAudioContext.oncomplete = () => {\n scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation\n scriptProcessorNode.disconnect();\n };\n scriptProcessorNode.onaudioprocess = () => nativeOfflineAudioContext.currentTime; // tslint:disable-line:deprecation\n scriptProcessorNode.connect(nativeOfflineAudioContext.destination);\n }\n return nativeOfflineAudioContext.startRendering();\n });\n }\n return new Promise((resolve) => {\n // Bug #48: Safari does not render an OfflineAudioContext without any connected node.\n const gainNode = createNativeGainNode(nativeOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n nativeOfflineAudioContext.oncomplete = (event) => {\n gainNode.disconnect();\n resolve(event.renderedBuffer);\n };\n gainNode.connect(nativeOfflineAudioContext.destination);\n nativeOfflineAudioContext.startRendering();\n });\n };\n};\n//# sourceMappingURL=render-native-offline-audio-context.js.map","export const createSetActiveAudioWorkletNodeInputs = (activeAudioWorkletNodeInputsStore) => {\n return (nativeAudioWorkletNode, activeInputs) => {\n activeAudioWorkletNodeInputsStore.set(nativeAudioWorkletNode, activeInputs);\n };\n};\n//# sourceMappingURL=set-active-audio-worklet-node-inputs.js.map","export const createSetAudioNodeTailTime = (audioNodeTailTimeStore) => {\n return (audioNode, tailTime) => audioNodeTailTimeStore.set(audioNode, tailTime);\n};\n//# sourceMappingURL=set-audio-node-tail-time.js.map","import { wrapAudioBufferGetChannelDataMethod } from '../helpers/wrap-audio-buffer-get-channel-data-method';\nexport const createStartRendering = (audioBufferStore, cacheTestResult, getAudioNodeRenderer, getUnrenderedAudioWorkletNodes, renderNativeOfflineAudioContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds) => {\n return (destination, nativeOfflineAudioContext) => getAudioNodeRenderer(destination)\n .render(destination, nativeOfflineAudioContext)\n /*\n * Bug #86 & #87: Invoking the renderer of an AudioWorkletNode might be necessary if it has no direct or indirect connection to the\n * destination.\n */\n .then(() => Promise.all(Array.from(getUnrenderedAudioWorkletNodes(nativeOfflineAudioContext)).map((audioWorkletNode) => getAudioNodeRenderer(audioWorkletNode).render(audioWorkletNode, nativeOfflineAudioContext))))\n .then(() => renderNativeOfflineAudioContext(nativeOfflineAudioContext))\n .then((audioBuffer) => {\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value.\n if (typeof audioBuffer.copyFromChannel !== 'function') {\n wrapAudioBufferCopyChannelMethods(audioBuffer);\n wrapAudioBufferGetChannelDataMethod(audioBuffer);\n // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds.\n }\n else if (!cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () => testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer))) {\n wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer);\n }\n audioBufferStore.add(audioBuffer);\n return audioBuffer;\n });\n};\n//# sourceMappingURL=start-rendering.js.map","const DEFAULT_OPTIONS = {\n channelCount: 2,\n /*\n * Bug #105: The channelCountMode should be 'clamped-max' according to the spec but is set to 'explicit' to achieve consistent\n * behavior.\n */\n channelCountMode: 'explicit',\n channelInterpretation: 'speakers',\n pan: 0\n};\nexport const createStereoPannerNodeConstructor = (audioNodeConstructor, createAudioParam, createNativeStereoPannerNode, createStereoPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext) => {\n return class StereoPannerNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeStereoPannerNode = createNativeStereoPannerNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const stereoPannerNodeRenderer = (isOffline ? createStereoPannerNodeRenderer() : null);\n super(context, false, nativeStereoPannerNode, stereoPannerNodeRenderer);\n this._pan = createAudioParam(this, isOffline, nativeStereoPannerNode.pan);\n }\n get pan() {\n return this._pan;\n }\n };\n};\n//# sourceMappingURL=stereo-panner-node-constructor.js.map","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createStereoPannerNodeRendererFactory = (connectAudioParam, createNativeStereoPannerNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeStereoPannerNodes = new WeakMap();\n const createStereoPannerNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeStereoPannerNode = getNativeAudioNode(proxy);\n /*\n * If the initially used nativeStereoPannerNode was not constructed on the same OfflineAudioContext it needs to be created\n * again.\n */\n const nativeStereoPannerNodeIsOwnedByContext = isOwnedByContext(nativeStereoPannerNode, nativeOfflineAudioContext);\n if (!nativeStereoPannerNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeStereoPannerNode.channelCount,\n channelCountMode: nativeStereoPannerNode.channelCountMode,\n channelInterpretation: nativeStereoPannerNode.channelInterpretation,\n pan: nativeStereoPannerNode.pan.value\n };\n nativeStereoPannerNode = createNativeStereoPannerNode(nativeOfflineAudioContext, options);\n }\n renderedNativeStereoPannerNodes.set(nativeOfflineAudioContext, nativeStereoPannerNode);\n if (!nativeStereoPannerNodeIsOwnedByContext) {\n await renderAutomation(nativeOfflineAudioContext, proxy.pan, nativeStereoPannerNode.pan);\n }\n else {\n await connectAudioParam(nativeOfflineAudioContext, proxy.pan, nativeStereoPannerNode.pan);\n }\n if (isNativeAudioNodeFaker(nativeStereoPannerNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeStereoPannerNode.inputs[0]);\n }\n else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeStereoPannerNode);\n }\n return nativeStereoPannerNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeStereoPannerNode = renderedNativeStereoPannerNodes.get(nativeOfflineAudioContext);\n if (renderedNativeStereoPannerNode !== undefined) {\n return Promise.resolve(renderedNativeStereoPannerNode);\n }\n return createStereoPannerNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=stereo-panner-node-renderer-factory.js.map","// Bug #33: Safari exposes an AudioBuffer but it can't be used as a constructor.\nexport const createTestAudioBufferConstructorSupport = (nativeAudioBufferConstructor) => {\n return () => {\n if (nativeAudioBufferConstructor === null) {\n return false;\n }\n try {\n new nativeAudioBufferConstructor({ length: 1, sampleRate: 44100 }); // tslint:disable-line:no-unused-expression\n }\n catch {\n return false;\n }\n return true;\n };\n};\n//# sourceMappingURL=test-audio-buffer-constructor-support.js.map","// Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument.\nexport const createTestAudioWorkletProcessorPostMessageSupport = (nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor) => {\n return async () => {\n // Bug #61: If there is no native AudioWorkletNode it gets faked and therefore it is no problem if the it doesn't exist.\n if (nativeAudioWorkletNodeConstructor === null) {\n return true;\n }\n if (nativeOfflineAudioContextConstructor === null) {\n return false;\n }\n const blob = new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor(\"a\",A)'], {\n type: 'application/javascript; charset=utf-8'\n });\n // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz.\n const offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 128, 44100);\n const url = URL.createObjectURL(blob);\n let isEmittingMessageEvents = false;\n let isEmittingProcessorErrorEvents = false;\n try {\n await offlineAudioContext.audioWorklet.addModule(url);\n const audioWorkletNode = new nativeAudioWorkletNodeConstructor(offlineAudioContext, 'a', { numberOfOutputs: 0 });\n const oscillator = offlineAudioContext.createOscillator();\n audioWorkletNode.port.onmessage = () => (isEmittingMessageEvents = true);\n audioWorkletNode.onprocessorerror = () => (isEmittingProcessorErrorEvents = true);\n oscillator.connect(audioWorkletNode);\n oscillator.start(0);\n await offlineAudioContext.startRendering();\n }\n catch {\n // Ignore errors.\n }\n finally {\n URL.revokeObjectURL(url);\n }\n return isEmittingMessageEvents && !isEmittingProcessorErrorEvents;\n };\n};\n//# sourceMappingURL=test-audio-worklet-processor-post-message-support.js.map","export const createTestOfflineAudioContextCurrentTimeSupport = (createNativeGainNode, nativeOfflineAudioContextConstructor) => {\n return () => {\n if (nativeOfflineAudioContextConstructor === null) {\n return Promise.resolve(false);\n }\n const nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100);\n // Bug #48: Safari does not render an OfflineAudioContext without any connected node.\n const gainNode = createNativeGainNode(nativeOfflineAudioContext, {\n channelCount: 1,\n channelCountMode: 'explicit',\n channelInterpretation: 'discrete',\n gain: 0\n });\n // Bug #21: Safari does not support promises yet.\n return new Promise((resolve) => {\n nativeOfflineAudioContext.oncomplete = () => {\n gainNode.disconnect();\n resolve(nativeOfflineAudioContext.currentTime !== 0);\n };\n nativeOfflineAudioContext.startRendering();\n });\n };\n};\n//# sourceMappingURL=test-offline-audio-context-current-time-support.js.map","export const createUnknownError = () => new DOMException('', 'UnknownError');\n//# sourceMappingURL=unknown-error.js.map","const DEFAULT_OPTIONS = {\n channelCount: 2,\n channelCountMode: 'max',\n channelInterpretation: 'speakers',\n curve: null,\n oversample: 'none'\n};\nexport const createWaveShaperNodeConstructor = (audioNodeConstructor, createInvalidStateError, createNativeWaveShaperNode, createWaveShaperNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) => {\n return class WaveShaperNode extends audioNodeConstructor {\n constructor(context, options) {\n const nativeContext = getNativeContext(context);\n const mergedOptions = { ...DEFAULT_OPTIONS, ...options };\n const nativeWaveShaperNode = createNativeWaveShaperNode(nativeContext, mergedOptions);\n const isOffline = isNativeOfflineAudioContext(nativeContext);\n const waveShaperNodeRenderer = (isOffline ? createWaveShaperNodeRenderer() : null);\n // @todo Add a mechanism to only switch a WaveShaperNode to active while it is connected.\n super(context, true, nativeWaveShaperNode, waveShaperNodeRenderer);\n this._isCurveNullified = false;\n this._nativeWaveShaperNode = nativeWaveShaperNode;\n // @todo Determine a meaningful tail-time instead of just using one second.\n setAudioNodeTailTime(this, 1);\n }\n get curve() {\n if (this._isCurveNullified) {\n return null;\n }\n return this._nativeWaveShaperNode.curve;\n }\n set curve(value) {\n // Bug #103: Safari does not allow to set the curve to null.\n if (value === null) {\n this._isCurveNullified = true;\n this._nativeWaveShaperNode.curve = new Float32Array([0, 0]);\n }\n else {\n // Bug #102: Safari does not throw an InvalidStateError when the curve has less than two samples.\n // Bug #104: Chrome and Edge will throw an InvalidAccessError when the curve has less than two samples.\n if (value.length < 2) {\n throw createInvalidStateError();\n }\n this._isCurveNullified = false;\n this._nativeWaveShaperNode.curve = value;\n }\n }\n get oversample() {\n return this._nativeWaveShaperNode.oversample;\n }\n set oversample(value) {\n this._nativeWaveShaperNode.oversample = value;\n }\n };\n};\n//# sourceMappingURL=wave-shaper-node-constructor.js.map","import { isNativeAudioNodeFaker } from '../guards/native-audio-node-faker';\nimport { isOwnedByContext } from '../helpers/is-owned-by-context';\nexport const createWaveShaperNodeRendererFactory = (createNativeWaveShaperNode, getNativeAudioNode, renderInputsOfAudioNode) => {\n return () => {\n const renderedNativeWaveShaperNodes = new WeakMap();\n const createWaveShaperNode = async (proxy, nativeOfflineAudioContext) => {\n let nativeWaveShaperNode = getNativeAudioNode(proxy);\n // If the initially used nativeWaveShaperNode was not constructed on the same OfflineAudioContext it needs to be created again.\n const nativeWaveShaperNodeIsOwnedByContext = isOwnedByContext(nativeWaveShaperNode, nativeOfflineAudioContext);\n if (!nativeWaveShaperNodeIsOwnedByContext) {\n const options = {\n channelCount: nativeWaveShaperNode.channelCount,\n channelCountMode: nativeWaveShaperNode.channelCountMode,\n channelInterpretation: nativeWaveShaperNode.channelInterpretation,\n curve: nativeWaveShaperNode.curve,\n oversample: nativeWaveShaperNode.oversample\n };\n nativeWaveShaperNode = createNativeWaveShaperNode(nativeOfflineAudioContext, options);\n }\n renderedNativeWaveShaperNodes.set(nativeOfflineAudioContext, nativeWaveShaperNode);\n if (isNativeAudioNodeFaker(nativeWaveShaperNode)) {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeWaveShaperNode.inputs[0]);\n }\n else {\n await renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeWaveShaperNode);\n }\n return nativeWaveShaperNode;\n };\n return {\n render(proxy, nativeOfflineAudioContext) {\n const renderedNativeWaveShaperNode = renderedNativeWaveShaperNodes.get(nativeOfflineAudioContext);\n if (renderedNativeWaveShaperNode !== undefined) {\n return Promise.resolve(renderedNativeWaveShaperNode);\n }\n return createWaveShaperNode(proxy, nativeOfflineAudioContext);\n }\n };\n };\n};\n//# sourceMappingURL=wave-shaper-node-renderer-factory.js.map","export const createWindow = () => (typeof window === 'undefined' ? null : window);\n//# sourceMappingURL=window.js.map","export const createWrapAudioBufferCopyChannelMethods = (convertNumberToUnsignedLong, createIndexSizeError) => {\n return (audioBuffer) => {\n audioBuffer.copyFromChannel = (destination, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n if (channelNumber >= audioBuffer.numberOfChannels) {\n throw createIndexSizeError();\n }\n const audioBufferLength = audioBuffer.length;\n const channelData = audioBuffer.getChannelData(channelNumber);\n const destinationLength = destination.length;\n for (let i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < destinationLength; i += 1) {\n destination[i] = channelData[i + bufferOffset];\n }\n };\n audioBuffer.copyToChannel = (source, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n if (channelNumber >= audioBuffer.numberOfChannels) {\n throw createIndexSizeError();\n }\n const audioBufferLength = audioBuffer.length;\n const channelData = audioBuffer.getChannelData(channelNumber);\n const sourceLength = source.length;\n for (let i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < sourceLength; i += 1) {\n channelData[i + bufferOffset] = source[i];\n }\n };\n };\n};\n//# sourceMappingURL=wrap-audio-buffer-copy-channel-methods.js.map","export const createWrapAudioBufferCopyChannelMethodsOutOfBounds = (convertNumberToUnsignedLong) => {\n return (audioBuffer) => {\n audioBuffer.copyFromChannel = ((copyFromChannel) => {\n return (destination, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n if (bufferOffset < audioBuffer.length) {\n return copyFromChannel.call(audioBuffer, destination, channelNumber, bufferOffset);\n }\n };\n })(audioBuffer.copyFromChannel);\n audioBuffer.copyToChannel = ((copyToChannel) => {\n return (source, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {\n const bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber);\n const channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber);\n if (bufferOffset < audioBuffer.length) {\n return copyToChannel.call(audioBuffer, source, channelNumber, bufferOffset);\n }\n };\n })(audioBuffer.copyToChannel);\n };\n};\n//# sourceMappingURL=wrap-audio-buffer-copy-channel-methods-out-of-bounds.js.map","export const createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer = (overwriteAccessors) => {\n return (nativeAudioBufferSourceNode, nativeContext) => {\n const nullifiedBuffer = nativeContext.createBuffer(1, 1, 44100);\n if (nativeAudioBufferSourceNode.buffer === null) {\n nativeAudioBufferSourceNode.buffer = nullifiedBuffer;\n }\n overwriteAccessors(nativeAudioBufferSourceNode, 'buffer', (get) => () => {\n const value = get.call(nativeAudioBufferSourceNode);\n return value === nullifiedBuffer ? null : value;\n }, (set) => (value) => {\n return set.call(nativeAudioBufferSourceNode, value === null ? nullifiedBuffer : value);\n });\n };\n};\n//# sourceMappingURL=wrap-audio-buffer-source-node-stop-method-nullified-buffer.js.map","export const createWrapChannelMergerNode = (createInvalidStateError, monitorConnections) => {\n return (nativeContext, channelMergerNode) => {\n // Bug #15: Safari does not return the default properties.\n channelMergerNode.channelCount = 1;\n channelMergerNode.channelCountMode = 'explicit';\n // Bug #16: Safari does not throw an error when setting a different channelCount or channelCountMode.\n Object.defineProperty(channelMergerNode, 'channelCount', {\n get: () => 1,\n set: () => {\n throw createInvalidStateError();\n }\n });\n Object.defineProperty(channelMergerNode, 'channelCountMode', {\n get: () => 'explicit',\n set: () => {\n throw createInvalidStateError();\n }\n });\n // Bug #20: Safari requires a connection of any kind to treat the input signal correctly.\n const audioBufferSourceNode = nativeContext.createBufferSource();\n const whenConnected = () => {\n const length = channelMergerNode.numberOfInputs;\n for (let i = 0; i < length; i += 1) {\n audioBufferSourceNode.connect(channelMergerNode, 0, i);\n }\n };\n const whenDisconnected = () => audioBufferSourceNode.disconnect(channelMergerNode);\n monitorConnections(channelMergerNode, whenConnected, whenDisconnected);\n };\n};\n//# sourceMappingURL=wrap-channel-merger-node.js.map","export const getFirstSample = (audioBuffer, buffer, channelNumber) => {\n // Bug #5: Safari does not support copyFromChannel() and copyToChannel().\n if (audioBuffer.copyFromChannel === undefined) {\n return audioBuffer.getChannelData(channelNumber)[0];\n }\n audioBuffer.copyFromChannel(buffer, channelNumber);\n return buffer[0];\n};\n//# sourceMappingURL=get-first-sample.js.map","export const isDCCurve = (curve) => {\n if (curve === null) {\n return false;\n }\n const length = curve.length;\n if (length % 2 !== 0) {\n return curve[Math.floor(length / 2)] !== 0;\n }\n return curve[length / 2 - 1] + curve[length / 2] !== 0;\n};\n//# sourceMappingURL=is-dc-curve.js.map","export const overwriteAccessors = (object, property, createGetter, createSetter) => {\n let prototype = object;\n while (!prototype.hasOwnProperty(property)) {\n prototype = Object.getPrototypeOf(prototype);\n }\n const { get, set } = Object.getOwnPropertyDescriptor(prototype, property);\n Object.defineProperty(object, property, { get: createGetter(get), set: createSetter(set) });\n};\n//# sourceMappingURL=overwrite-accessors.js.map","export const sanitizeAudioWorkletNodeOptions = (options) => {\n return {\n ...options,\n outputChannelCount: options.outputChannelCount !== undefined\n ? options.outputChannelCount\n : options.numberOfInputs === 1 && options.numberOfOutputs === 1\n ? /*\n * Bug #61: This should be the computedNumberOfChannels, but unfortunately that is almost impossible to fake. That's why\n * the channelCountMode is required to be 'explicit' as long as there is not a native implementation in every browser. That\n * makes sure the computedNumberOfChannels is equivilant to the channelCount which makes it much easier to compute.\n */\n [options.channelCount]\n : Array.from({ length: options.numberOfOutputs }, () => 1)\n };\n};\n//# sourceMappingURL=sanitize-audio-worklet-node-options.js.map","export const sanitizeChannelSplitterOptions = (options) => {\n return { ...options, channelCount: options.numberOfOutputs };\n};\n//# sourceMappingURL=sanitize-channel-splitter-options.js.map","export const sanitizePeriodicWaveOptions = (options) => {\n const { imag, real } = options;\n if (imag === undefined) {\n if (real === undefined) {\n return { ...options, imag: [0, 0], real: [0, 0] };\n }\n return { ...options, imag: Array.from(real, () => 0), real };\n }\n if (real === undefined) {\n return { ...options, imag, real: Array.from(imag, () => 0) };\n }\n return { ...options, imag, real };\n};\n//# sourceMappingURL=sanitize-periodic-wave-options.js.map","export const setValueAtTimeUntilPossible = (audioParam, value, startTime) => {\n try {\n audioParam.setValueAtTime(value, startTime);\n }\n catch (err) {\n if (err.code !== 9) {\n throw err;\n }\n setValueAtTimeUntilPossible(audioParam, value, startTime + 1e-7);\n }\n};\n//# sourceMappingURL=set-value-at-time-until-possible.js.map","export const testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport = (nativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n nativeAudioBufferSourceNode.start();\n try {\n nativeAudioBufferSourceNode.start();\n }\n catch {\n return true;\n }\n return false;\n};\n//# sourceMappingURL=test-audio-buffer-source-node-start-method-consecutive-calls-support.js.map","export const testAudioBufferSourceNodeStartMethodOffsetClampingSupport = (nativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n const nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100);\n nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;\n try {\n nativeAudioBufferSourceNode.start(0, 1);\n }\n catch {\n return false;\n }\n return true;\n};\n//# sourceMappingURL=test-audio-buffer-source-node-start-method-offset-clamping-support.js.map","export const testAudioBufferSourceNodeStopMethodNullifiedBufferSupport = (nativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n nativeAudioBufferSourceNode.start();\n try {\n nativeAudioBufferSourceNode.stop();\n }\n catch {\n return false;\n }\n return true;\n};\n//# sourceMappingURL=test-audio-buffer-source-node-stop-method-nullified-buffer-support.js.map","export const testAudioScheduledSourceNodeStartMethodNegativeParametersSupport = (nativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createOscillator();\n try {\n nativeAudioBufferSourceNode.start(-1);\n }\n catch (err) {\n return err instanceof RangeError;\n }\n return false;\n};\n//# sourceMappingURL=test-audio-scheduled-source-node-start-method-negative-parameters-support.js.map","export const testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport = (nativeContext) => {\n const nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100);\n const nativeAudioBufferSourceNode = nativeContext.createBufferSource();\n nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;\n nativeAudioBufferSourceNode.start();\n nativeAudioBufferSourceNode.stop();\n try {\n nativeAudioBufferSourceNode.stop();\n return true;\n }\n catch {\n return false;\n }\n};\n//# sourceMappingURL=test-audio-scheduled-source-node-stop-method-consecutive-calls-support.js.map","export const testAudioScheduledSourceNodeStopMethodNegativeParametersSupport = (nativeContext) => {\n const nativeAudioBufferSourceNode = nativeContext.createOscillator();\n try {\n nativeAudioBufferSourceNode.stop(-1);\n }\n catch (err) {\n return err instanceof RangeError;\n }\n return false;\n};\n//# sourceMappingURL=test-audio-scheduled-source-node-stop-method-negative-parameters-support.js.map","export const testAudioWorkletNodeOptionsClonability = (audioWorkletNodeOptions) => {\n const { port1, port2 } = new MessageChannel();\n try {\n // This will throw an error if the audioWorkletNodeOptions are not clonable.\n port1.postMessage(audioWorkletNodeOptions);\n }\n finally {\n port1.close();\n port2.close();\n }\n};\n//# sourceMappingURL=test-audio-worklet-node-options-clonability.js.map","export const wrapAudioBufferSourceNodeStartMethodOffsetClamping = (nativeAudioBufferSourceNode) => {\n nativeAudioBufferSourceNode.start = ((start) => {\n return (when = 0, offset = 0, duration) => {\n const buffer = nativeAudioBufferSourceNode.buffer;\n // Bug #154: Safari does not clamp the offset if it is equal to or greater than the duration of the buffer.\n const clampedOffset = buffer === null ? offset : Math.min(buffer.duration, offset);\n // Bug #155: Safari does not handle the offset correctly if it would cause the buffer to be not be played at all.\n if (buffer !== null && clampedOffset > buffer.duration - 0.5 / nativeAudioBufferSourceNode.context.sampleRate) {\n start.call(nativeAudioBufferSourceNode, when, 0, 0);\n }\n else {\n start.call(nativeAudioBufferSourceNode, when, clampedOffset, duration);\n }\n };\n })(nativeAudioBufferSourceNode.start);\n};\n//# sourceMappingURL=wrap-audio-buffer-source-node-start-method-offset-clamping.js.map","import { interceptConnections } from './intercept-connections';\nexport const wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls = (nativeAudioScheduledSourceNode, nativeContext) => {\n const nativeGainNode = nativeContext.createGain();\n nativeAudioScheduledSourceNode.connect(nativeGainNode);\n const disconnectGainNode = ((disconnect) => {\n return () => {\n // @todo TypeScript cannot infer the overloaded signature with 1 argument yet.\n disconnect.call(nativeAudioScheduledSourceNode, nativeGainNode);\n nativeAudioScheduledSourceNode.removeEventListener('ended', disconnectGainNode);\n };\n })(nativeAudioScheduledSourceNode.disconnect);\n nativeAudioScheduledSourceNode.addEventListener('ended', disconnectGainNode);\n interceptConnections(nativeAudioScheduledSourceNode, nativeGainNode);\n nativeAudioScheduledSourceNode.stop = ((stop) => {\n let isStopped = false;\n return (when = 0) => {\n if (isStopped) {\n try {\n stop.call(nativeAudioScheduledSourceNode, when);\n }\n catch {\n nativeGainNode.gain.setValueAtTime(0, when);\n }\n }\n else {\n stop.call(nativeAudioScheduledSourceNode, when);\n isStopped = true;\n }\n };\n })(nativeAudioScheduledSourceNode.stop);\n};\n//# sourceMappingURL=wrap-audio-scheduled-source-node-stop-method-consecutive-calls.js.map","export const wrapEventListener = (target, eventListener) => {\n return (event) => {\n const descriptor = { value: target };\n Object.defineProperties(event, {\n currentTarget: descriptor,\n target: descriptor\n });\n if (typeof eventListener === 'function') {\n return eventListener.call(target, event);\n }\n return eventListener.handleEvent.call(target, event);\n };\n};\n//# sourceMappingURL=wrap-event-listener.js.map","import { createCancelAndHoldAutomationEvent, createCancelScheduledValuesAutomationEvent, createExponentialRampToValueAutomationEvent, createLinearRampToValueAutomationEvent, createSetTargetAutomationEvent, createSetValueAutomationEvent, createSetValueCurveAutomationEvent } from 'automation-events';\nimport { createAbortError } from './factories/abort-error';\nimport { createAddActiveInputConnectionToAudioNode } from './factories/add-active-input-connection-to-audio-node';\nimport { createAddAudioNodeConnections } from './factories/add-audio-node-connections';\nimport { createAddAudioParamConnections } from './factories/add-audio-param-connections';\nimport { createAddAudioWorkletModule } from './factories/add-audio-worklet-module';\nimport { createAddConnectionToAudioNode } from './factories/add-connection-to-audio-node';\nimport { createAddPassiveInputConnectionToAudioNode } from './factories/add-passive-input-connection-to-audio-node';\nimport { createAddSilentConnection } from './factories/add-silent-connection';\nimport { createAddUnrenderedAudioWorkletNode } from './factories/add-unrendered-audio-worklet-node';\nimport { createAnalyserNodeConstructor } from './factories/analyser-node-constructor';\nimport { createAnalyserNodeRendererFactory } from './factories/analyser-node-renderer-factory';\nimport { createAudioBufferConstructor } from './factories/audio-buffer-constructor';\nimport { createAudioBufferSourceNodeConstructor } from './factories/audio-buffer-source-node-constructor';\nimport { createAudioBufferSourceNodeRendererFactory } from './factories/audio-buffer-source-node-renderer-factory';\nimport { createAudioContextConstructor } from './factories/audio-context-constructor';\nimport { createAudioDestinationNodeConstructor } from './factories/audio-destination-node-constructor';\nimport { createAudioDestinationNodeRenderer } from './factories/audio-destination-node-renderer-factory';\nimport { createAudioListenerFactory } from './factories/audio-listener-factory';\nimport { createAudioNodeConstructor } from './factories/audio-node-constructor';\nimport { createAudioParamFactory } from './factories/audio-param-factory';\nimport { createAudioParamRenderer } from './factories/audio-param-renderer';\nimport { createAudioWorkletNodeConstructor } from './factories/audio-worklet-node-constructor';\nimport { createAudioWorkletNodeRendererFactory } from './factories/audio-worklet-node-renderer-factory';\nimport { createBaseAudioContextConstructor } from './factories/base-audio-context-constructor';\nimport { createBiquadFilterNodeConstructor } from './factories/biquad-filter-node-constructor';\nimport { createBiquadFilterNodeRendererFactory } from './factories/biquad-filter-node-renderer-factory';\nimport { createCacheTestResult } from './factories/cache-test-result';\nimport { createChannelMergerNodeConstructor } from './factories/channel-merger-node-constructor';\nimport { createChannelMergerNodeRendererFactory } from './factories/channel-merger-node-renderer-factory';\nimport { createChannelSplitterNodeConstructor } from './factories/channel-splitter-node-constructor';\nimport { createChannelSplitterNodeRendererFactory } from './factories/channel-splitter-node-renderer-factory';\nimport { createConnectAudioParam } from './factories/connect-audio-param';\nimport { createConnectMultipleOutputs } from './factories/connect-multiple-outputs';\nimport { createConnectedNativeAudioBufferSourceNodeFactory } from './factories/connected-native-audio-buffer-source-node-factory';\nimport { createConstantSourceNodeConstructor } from './factories/constant-source-node-constructor';\nimport { createConstantSourceNodeRendererFactory } from './factories/constant-source-node-renderer-factory';\nimport { createConvertNumberToUnsignedLong } from './factories/convert-number-to-unsigned-long';\nimport { createConvolverNodeConstructor } from './factories/convolver-node-constructor';\nimport { createConvolverNodeRendererFactory } from './factories/convolver-node-renderer-factory';\nimport { createCreateNativeOfflineAudioContext } from './factories/create-native-offline-audio-context';\nimport { createDataCloneError } from './factories/data-clone-error';\nimport { createDecodeAudioData } from './factories/decode-audio-data';\nimport { createDecrementCycleCounter } from './factories/decrement-cycle-counter';\nimport { createDelayNodeConstructor } from './factories/delay-node-constructor';\nimport { createDelayNodeRendererFactory } from './factories/delay-node-renderer-factory';\nimport { createDeleteActiveInputConnectionToAudioNode } from './factories/delete-active-input-connection-to-audio-node';\nimport { createDeleteUnrenderedAudioWorkletNode } from './factories/delete-unrendered-audio-worklet-node';\nimport { createDetectCycles } from './factories/detect-cycles';\nimport { createDisconnectMultipleOutputs } from './factories/disconnect-multiple-outputs';\nimport { createDynamicsCompressorNodeConstructor } from './factories/dynamics-compressor-node-constructor';\nimport { createDynamicsCompressorNodeRendererFactory } from './factories/dynamics-compressor-node-renderer-factory';\nimport { createEncodingError } from './factories/encoding-error';\nimport { createEvaluateSource } from './factories/evaluate-source';\nimport { createEventTargetConstructor } from './factories/event-target-constructor';\nimport { createExposeCurrentFrameAndCurrentTime } from './factories/expose-current-frame-and-current-time';\nimport { createFetchSource } from './factories/fetch-source';\nimport { createGainNodeConstructor } from './factories/gain-node-constructor';\nimport { createGainNodeRendererFactory } from './factories/gain-node-renderer-factory';\nimport { createGetActiveAudioWorkletNodeInputs } from './factories/get-active-audio-worklet-node-inputs';\nimport { createGetAudioNodeRenderer } from './factories/get-audio-node-renderer';\nimport { createGetAudioNodeTailTime } from './factories/get-audio-node-tail-time';\nimport { createGetAudioParamRenderer } from './factories/get-audio-param-renderer';\nimport { createGetBackupOfflineAudioContext } from './factories/get-backup-offline-audio-context';\nimport { createGetNativeContext } from './factories/get-native-context';\nimport { createGetOrCreateBackupOfflineAudioContext } from './factories/get-or-create-backup-offline-audio-context';\nimport { createGetUnrenderedAudioWorkletNodes } from './factories/get-unrendered-audio-worklet-nodes';\nimport { createIIRFilterNodeConstructor } from './factories/iir-filter-node-constructor';\nimport { createIIRFilterNodeRendererFactory } from './factories/iir-filter-node-renderer-factory';\nimport { createIncrementCycleCounterFactory } from './factories/increment-cycle-counter-factory';\nimport { createIndexSizeError } from './factories/index-size-error';\nimport { createInvalidAccessError } from './factories/invalid-access-error';\nimport { createInvalidStateError } from './factories/invalid-state-error';\nimport { createIsAnyAudioContext } from './factories/is-any-audio-context';\nimport { createIsAnyAudioNode } from './factories/is-any-audio-node';\nimport { createIsAnyAudioParam } from './factories/is-any-audio-param';\nimport { createIsAnyOfflineAudioContext } from './factories/is-any-offline-audio-context';\nimport { createIsNativeAudioContext } from './factories/is-native-audio-context';\nimport { createIsNativeAudioNode } from './factories/is-native-audio-node';\nimport { createIsNativeAudioParam } from './factories/is-native-audio-param';\nimport { createIsNativeContext } from './factories/is-native-context';\nimport { createIsNativeOfflineAudioContext } from './factories/is-native-offline-audio-context';\nimport { createIsSecureContext } from './factories/is-secure-context';\nimport { createIsSupportedPromise } from './factories/is-supported-promise';\nimport { createMediaElementAudioSourceNodeConstructor } from './factories/media-element-audio-source-node-constructor';\nimport { createMediaStreamAudioDestinationNodeConstructor } from './factories/media-stream-audio-destination-node-constructor';\nimport { createMediaStreamAudioSourceNodeConstructor } from './factories/media-stream-audio-source-node-constructor';\nimport { createMediaStreamTrackAudioSourceNodeConstructor } from './factories/media-stream-track-audio-source-node-constructor';\nimport { createMinimalAudioContextConstructor } from './factories/minimal-audio-context-constructor';\nimport { createMinimalBaseAudioContextConstructor } from './factories/minimal-base-audio-context-constructor';\nimport { createMinimalOfflineAudioContextConstructor } from './factories/minimal-offline-audio-context-constructor';\nimport { createMonitorConnections } from './factories/monitor-connections';\nimport { createNativeAnalyserNodeFactory } from './factories/native-analyser-node-factory';\nimport { createNativeAudioBufferConstructor } from './factories/native-audio-buffer-constructor';\nimport { createNativeAudioBufferSourceNodeFactory } from './factories/native-audio-buffer-source-node-factory';\nimport { createNativeAudioContextConstructor } from './factories/native-audio-context-constructor';\nimport { createNativeAudioDestinationNodeFactory } from './factories/native-audio-destination-node';\nimport { createNativeAudioWorkletNodeConstructor } from './factories/native-audio-worklet-node-constructor';\nimport { createNativeAudioWorkletNodeFactory } from './factories/native-audio-worklet-node-factory';\nimport { createNativeAudioWorkletNodeFakerFactory } from './factories/native-audio-worklet-node-faker-factory';\nimport { createNativeBiquadFilterNode } from './factories/native-biquad-filter-node';\nimport { createNativeChannelMergerNodeFactory } from './factories/native-channel-merger-node-factory';\nimport { createNativeChannelSplitterNode } from './factories/native-channel-splitter-node';\nimport { createNativeConstantSourceNodeFactory } from './factories/native-constant-source-node-factory';\nimport { createNativeConstantSourceNodeFakerFactory } from './factories/native-constant-source-node-faker-factory';\nimport { createNativeConvolverNodeFactory } from './factories/native-convolver-node-factory';\nimport { createNativeDelayNode } from './factories/native-delay-node';\nimport { createNativeDynamicsCompressorNodeFactory } from './factories/native-dynamics-compressor-node-factory';\nimport { createNativeGainNode } from './factories/native-gain-node';\nimport { createNativeIIRFilterNodeFactory } from './factories/native-iir-filter-node-factory';\nimport { createNativeIIRFilterNodeFakerFactory } from './factories/native-iir-filter-node-faker-factory';\nimport { createNativeMediaElementAudioSourceNode } from './factories/native-media-element-audio-source-node';\nimport { createNativeMediaStreamAudioDestinationNode } from './factories/native-media-stream-audio-destination-node';\nimport { createNativeMediaStreamAudioSourceNode } from './factories/native-media-stream-audio-source-node';\nimport { createNativeMediaStreamTrackAudioSourceNodeFactory } from './factories/native-media-stream-track-audio-source-node-factory';\nimport { createNativeOfflineAudioContextConstructor } from './factories/native-offline-audio-context-constructor';\nimport { createNativeOscillatorNodeFactory } from './factories/native-oscillator-node-factory';\nimport { createNativePannerNodeFactory } from './factories/native-panner-node-factory';\nimport { createNativePannerNodeFakerFactory } from './factories/native-panner-node-faker-factory';\nimport { createNativePeriodicWaveFactory } from './factories/native-periodic-wave-factory';\nimport { createNativeScriptProcessorNode } from './factories/native-script-processor-node';\nimport { createNativeStereoPannerNodeFactory } from './factories/native-stereo-panner-node-factory';\nimport { createNativeStereoPannerNodeFakerFactory } from './factories/native-stereo-panner-node-faker-factory';\nimport { createNativeWaveShaperNodeFactory } from './factories/native-wave-shaper-node-factory';\nimport { createNativeWaveShaperNodeFakerFactory } from './factories/native-wave-shaper-node-faker-factory';\nimport { createNotSupportedError } from './factories/not-supported-error';\nimport { createOfflineAudioContextConstructor } from './factories/offline-audio-context-constructor';\nimport { createOscillatorNodeConstructor } from './factories/oscillator-node-constructor';\nimport { createOscillatorNodeRendererFactory } from './factories/oscillator-node-renderer-factory';\nimport { createPannerNodeConstructor } from './factories/panner-node-constructor';\nimport { createPannerNodeRendererFactory } from './factories/panner-node-renderer-factory';\nimport { createPeriodicWaveConstructor } from './factories/periodic-wave-constructor';\nimport { createRenderAutomation } from './factories/render-automation';\nimport { createRenderInputsOfAudioNode } from './factories/render-inputs-of-audio-node';\nimport { createRenderInputsOfAudioParam } from './factories/render-inputs-of-audio-param';\nimport { createRenderNativeOfflineAudioContext } from './factories/render-native-offline-audio-context';\nimport { createSetActiveAudioWorkletNodeInputs } from './factories/set-active-audio-worklet-node-inputs';\nimport { createSetAudioNodeTailTime } from './factories/set-audio-node-tail-time';\nimport { createStartRendering } from './factories/start-rendering';\nimport { createStereoPannerNodeConstructor } from './factories/stereo-panner-node-constructor';\nimport { createStereoPannerNodeRendererFactory } from './factories/stereo-panner-node-renderer-factory';\nimport { createTestAudioBufferConstructorSupport } from './factories/test-audio-buffer-constructor-support';\nimport { createTestAudioBufferCopyChannelMethodsSubarraySupport } from './factories/test-audio-buffer-copy-channel-methods-subarray-support';\nimport { createTestAudioContextCloseMethodSupport } from './factories/test-audio-context-close-method-support';\nimport { createTestAudioContextDecodeAudioDataMethodTypeErrorSupport } from './factories/test-audio-context-decode-audio-data-method-type-error-support';\nimport { createTestAudioContextOptionsSupport } from './factories/test-audio-context-options-support';\nimport { createTestAudioNodeConnectMethodSupport } from './factories/test-audio-node-connect-method-support';\nimport { createTestAudioWorkletProcessorNoOutputsSupport } from './factories/test-audio-worklet-processor-no-outputs-support';\nimport { createTestAudioWorkletProcessorPostMessageSupport } from './factories/test-audio-worklet-processor-post-message-support';\nimport { createTestChannelMergerNodeChannelCountSupport } from './factories/test-channel-merger-node-channel-count-support';\nimport { createTestConstantSourceNodeAccurateSchedulingSupport } from './factories/test-constant-source-node-accurate-scheduling-support';\nimport { createTestConvolverNodeBufferReassignabilitySupport } from './factories/test-convolver-node-buffer-reassignability-support';\nimport { createTestConvolverNodeChannelCountSupport } from './factories/test-convolver-node-channel-count-support';\nimport { createTestIsSecureContextSupport } from './factories/test-is-secure-context-support';\nimport { createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport } from './factories/test-media-stream-audio-source-node-media-stream-without-audio-track-support';\nimport { createTestOfflineAudioContextCurrentTimeSupport } from './factories/test-offline-audio-context-current-time-support';\nimport { createTestStereoPannerNodeDefaultValueSupport } from './factories/test-stereo-panner-node-default-value-support';\nimport { createUnknownError } from './factories/unknown-error';\nimport { createWaveShaperNodeConstructor } from './factories/wave-shaper-node-constructor';\nimport { createWaveShaperNodeRendererFactory } from './factories/wave-shaper-node-renderer-factory';\nimport { createWindow } from './factories/window';\nimport { createWrapAudioBufferCopyChannelMethods } from './factories/wrap-audio-buffer-copy-channel-methods';\nimport { createWrapAudioBufferCopyChannelMethodsOutOfBounds } from './factories/wrap-audio-buffer-copy-channel-methods-out-of-bounds';\nimport { createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer } from './factories/wrap-audio-buffer-source-node-stop-method-nullified-buffer';\nimport { createWrapChannelMergerNode } from './factories/wrap-channel-merger-node';\nimport { AUDIO_NODE_CONNECTIONS_STORE, AUDIO_NODE_STORE, AUDIO_PARAM_CONNECTIONS_STORE, AUDIO_PARAM_STORE, CONTEXT_STORE, CYCLE_COUNTERS } from './globals';\nimport { connectNativeAudioNodeToNativeAudioNode } from './helpers/connect-native-audio-node-to-native-audio-node';\nimport { disconnectNativeAudioNodeFromNativeAudioNode } from './helpers/disconnect-native-audio-node-from-native-audio-node';\nimport { getAudioNodeConnections } from './helpers/get-audio-node-connections';\nimport { getAudioParamConnections } from './helpers/get-audio-param-connections';\nimport { getEventListenersOfAudioNode } from './helpers/get-event-listeners-of-audio-node';\nimport { getFirstSample } from './helpers/get-first-sample';\nimport { getNativeAudioNode } from './helpers/get-native-audio-node';\nimport { getNativeAudioParam } from './helpers/get-native-audio-param';\nimport { getValueForKey } from './helpers/get-value-for-key';\nimport { insertElementInSet } from './helpers/insert-element-in-set';\nimport { isActiveAudioNode } from './helpers/is-active-audio-node';\nimport { isDCCurve } from './helpers/is-dc-curve';\nimport { isPartOfACycle } from './helpers/is-part-of-a-cycle';\nimport { isPassiveAudioNode } from './helpers/is-passive-audio-node';\nimport { overwriteAccessors } from './helpers/overwrite-accessors';\nimport { pickElementFromSet } from './helpers/pick-element-from-set';\nimport { sanitizeAudioWorkletNodeOptions } from './helpers/sanitize-audio-worklet-node-options';\nimport { sanitizeChannelSplitterOptions } from './helpers/sanitize-channel-splitter-options';\nimport { sanitizePeriodicWaveOptions } from './helpers/sanitize-periodic-wave-options';\nimport { setValueAtTimeUntilPossible } from './helpers/set-value-at-time-until-possible';\nimport { testAudioBufferCopyChannelMethodsOutOfBoundsSupport } from './helpers/test-audio-buffer-copy-channel-methods-out-of-bounds-support';\nimport { testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport } from './helpers/test-audio-buffer-source-node-start-method-consecutive-calls-support';\nimport { testAudioBufferSourceNodeStartMethodOffsetClampingSupport } from './helpers/test-audio-buffer-source-node-start-method-offset-clamping-support';\nimport { testAudioBufferSourceNodeStopMethodNullifiedBufferSupport } from './helpers/test-audio-buffer-source-node-stop-method-nullified-buffer-support';\nimport { testAudioScheduledSourceNodeStartMethodNegativeParametersSupport } from './helpers/test-audio-scheduled-source-node-start-method-negative-parameters-support';\nimport { testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport } from './helpers/test-audio-scheduled-source-node-stop-method-consecutive-calls-support';\nimport { testAudioScheduledSourceNodeStopMethodNegativeParametersSupport } from './helpers/test-audio-scheduled-source-node-stop-method-negative-parameters-support';\nimport { testAudioWorkletNodeOptionsClonability } from './helpers/test-audio-worklet-node-options-clonability';\nimport { testDomExceptionConstructorSupport } from './helpers/test-dom-exception-constructor-support';\nimport { testPromiseSupport } from './helpers/test-promise-support';\nimport { testTransferablesSupport } from './helpers/test-transferables-support';\nimport { wrapAudioBufferSourceNodeStartMethodOffsetClamping } from './helpers/wrap-audio-buffer-source-node-start-method-offset-clamping';\nimport { wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls } from './helpers/wrap-audio-scheduled-source-node-stop-method-consecutive-calls';\nimport { wrapEventListener } from './helpers/wrap-event-listener';\n/*\n * @todo Explicitly referencing the barrel file seems to be necessary when enabling the\n * isolatedModules compiler option.\n */\nexport * from './interfaces/index';\nexport * from './types/index';\nconst addActiveInputConnectionToAudioNode = createAddActiveInputConnectionToAudioNode(insertElementInSet);\nconst addPassiveInputConnectionToAudioNode = createAddPassiveInputConnectionToAudioNode(insertElementInSet);\nconst deleteActiveInputConnectionToAudioNode = createDeleteActiveInputConnectionToAudioNode(pickElementFromSet);\nconst audioNodeTailTimeStore = new WeakMap();\nconst getAudioNodeTailTime = createGetAudioNodeTailTime(audioNodeTailTimeStore);\nconst cacheTestResult = createCacheTestResult(new Map(), new WeakMap());\nconst window = createWindow();\nconst createNativeAnalyserNode = createNativeAnalyserNodeFactory(cacheTestResult, createIndexSizeError);\nconst getAudioNodeRenderer = createGetAudioNodeRenderer(getAudioNodeConnections);\nconst renderInputsOfAudioNode = createRenderInputsOfAudioNode(getAudioNodeConnections, getAudioNodeRenderer, isPartOfACycle);\nconst createAnalyserNodeRenderer = createAnalyserNodeRendererFactory(createNativeAnalyserNode, getNativeAudioNode, renderInputsOfAudioNode);\nconst getNativeContext = createGetNativeContext(CONTEXT_STORE);\nconst nativeOfflineAudioContextConstructor = createNativeOfflineAudioContextConstructor(window);\nconst isNativeOfflineAudioContext = createIsNativeOfflineAudioContext(nativeOfflineAudioContextConstructor);\nconst audioParamAudioNodeStore = new WeakMap();\nconst eventTargetConstructor = createEventTargetConstructor(wrapEventListener);\nconst nativeAudioContextConstructor = createNativeAudioContextConstructor(window);\nconst isNativeAudioContext = createIsNativeAudioContext(nativeAudioContextConstructor);\nconst isNativeAudioNode = createIsNativeAudioNode(window);\nconst isNativeAudioParam = createIsNativeAudioParam(window);\nconst nativeAudioWorkletNodeConstructor = createNativeAudioWorkletNodeConstructor(window);\nconst audioNodeConstructor = createAudioNodeConstructor(createAddAudioNodeConnections(AUDIO_NODE_CONNECTIONS_STORE), createAddConnectionToAudioNode(addActiveInputConnectionToAudioNode, addPassiveInputConnectionToAudioNode, connectNativeAudioNodeToNativeAudioNode, deleteActiveInputConnectionToAudioNode, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getAudioNodeTailTime, getEventListenersOfAudioNode, getNativeAudioNode, insertElementInSet, isActiveAudioNode, isPartOfACycle, isPassiveAudioNode), cacheTestResult, createIncrementCycleCounterFactory(CYCLE_COUNTERS, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, isActiveAudioNode), createIndexSizeError, createInvalidAccessError, createNotSupportedError, createDecrementCycleCounter(connectNativeAudioNodeToNativeAudioNode, CYCLE_COUNTERS, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, getNativeContext, isActiveAudioNode, isNativeOfflineAudioContext), createDetectCycles(audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey), eventTargetConstructor, getNativeContext, isNativeAudioContext, isNativeAudioNode, isNativeAudioParam, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor);\nconst analyserNodeConstructor = createAnalyserNodeConstructor(audioNodeConstructor, createAnalyserNodeRenderer, createIndexSizeError, createNativeAnalyserNode, getNativeContext, isNativeOfflineAudioContext);\nexport { analyserNodeConstructor as AnalyserNode };\nconst audioBufferStore = new WeakSet();\nconst nativeAudioBufferConstructor = createNativeAudioBufferConstructor(window);\nconst convertNumberToUnsignedLong = createConvertNumberToUnsignedLong(new Uint32Array(1));\nconst wrapAudioBufferCopyChannelMethods = createWrapAudioBufferCopyChannelMethods(convertNumberToUnsignedLong, createIndexSizeError);\nconst wrapAudioBufferCopyChannelMethodsOutOfBounds = createWrapAudioBufferCopyChannelMethodsOutOfBounds(convertNumberToUnsignedLong);\nconst audioBufferConstructor = createAudioBufferConstructor(audioBufferStore, cacheTestResult, createNotSupportedError, nativeAudioBufferConstructor, nativeOfflineAudioContextConstructor, createTestAudioBufferConstructorSupport(nativeAudioBufferConstructor), wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds);\nexport { audioBufferConstructor as AudioBuffer };\nconst addSilentConnection = createAddSilentConnection(createNativeGainNode);\nconst renderInputsOfAudioParam = createRenderInputsOfAudioParam(getAudioNodeRenderer, getAudioParamConnections, isPartOfACycle);\nconst connectAudioParam = createConnectAudioParam(renderInputsOfAudioParam);\nconst createNativeAudioBufferSourceNode = createNativeAudioBufferSourceNodeFactory(addSilentConnection, cacheTestResult, testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, testAudioBufferSourceNodeStartMethodOffsetClampingSupport, testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioBufferSourceNodeStartMethodOffsetClamping, createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer(overwriteAccessors), wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls);\nconst renderAutomation = createRenderAutomation(createGetAudioParamRenderer(getAudioParamConnections), renderInputsOfAudioParam);\nconst createAudioBufferSourceNodeRenderer = createAudioBufferSourceNodeRendererFactory(connectAudioParam, createNativeAudioBufferSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst createAudioParam = createAudioParamFactory(createAddAudioParamConnections(AUDIO_PARAM_CONNECTIONS_STORE), audioParamAudioNodeStore, AUDIO_PARAM_STORE, createAudioParamRenderer, createCancelAndHoldAutomationEvent, createCancelScheduledValuesAutomationEvent, createExponentialRampToValueAutomationEvent, createLinearRampToValueAutomationEvent, createSetTargetAutomationEvent, createSetValueAutomationEvent, createSetValueCurveAutomationEvent, nativeAudioContextConstructor, setValueAtTimeUntilPossible);\nconst audioBufferSourceNodeConstructor = createAudioBufferSourceNodeConstructor(audioNodeConstructor, createAudioBufferSourceNodeRenderer, createAudioParam, createInvalidStateError, createNativeAudioBufferSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener);\nexport { audioBufferSourceNodeConstructor as AudioBufferSourceNode };\nconst audioDestinationNodeConstructor = createAudioDestinationNodeConstructor(audioNodeConstructor, createAudioDestinationNodeRenderer, createIndexSizeError, createInvalidStateError, createNativeAudioDestinationNodeFactory(createNativeGainNode, overwriteAccessors), getNativeContext, isNativeOfflineAudioContext, renderInputsOfAudioNode);\nconst createBiquadFilterNodeRenderer = createBiquadFilterNodeRendererFactory(connectAudioParam, createNativeBiquadFilterNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst setAudioNodeTailTime = createSetAudioNodeTailTime(audioNodeTailTimeStore);\nconst biquadFilterNodeConstructor = createBiquadFilterNodeConstructor(audioNodeConstructor, createAudioParam, createBiquadFilterNodeRenderer, createInvalidAccessError, createNativeBiquadFilterNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst monitorConnections = createMonitorConnections(insertElementInSet, isNativeAudioNode);\nconst wrapChannelMergerNode = createWrapChannelMergerNode(createInvalidStateError, monitorConnections);\nconst createNativeChannelMergerNode = createNativeChannelMergerNodeFactory(nativeAudioContextConstructor, wrapChannelMergerNode);\nconst createChannelMergerNodeRenderer = createChannelMergerNodeRendererFactory(createNativeChannelMergerNode, getNativeAudioNode, renderInputsOfAudioNode);\nconst channelMergerNodeConstructor = createChannelMergerNodeConstructor(audioNodeConstructor, createChannelMergerNodeRenderer, createNativeChannelMergerNode, getNativeContext, isNativeOfflineAudioContext);\nconst createChannelSplitterNodeRenderer = createChannelSplitterNodeRendererFactory(createNativeChannelSplitterNode, getNativeAudioNode, renderInputsOfAudioNode);\nconst channelSplitterNodeConstructor = createChannelSplitterNodeConstructor(audioNodeConstructor, createChannelSplitterNodeRenderer, createNativeChannelSplitterNode, getNativeContext, isNativeOfflineAudioContext, sanitizeChannelSplitterOptions);\nconst createNativeConstantSourceNodeFaker = createNativeConstantSourceNodeFakerFactory(addSilentConnection, createNativeAudioBufferSourceNode, createNativeGainNode, monitorConnections);\nconst createNativeConstantSourceNode = createNativeConstantSourceNodeFactory(addSilentConnection, cacheTestResult, createNativeConstantSourceNodeFaker, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport);\nconst createConstantSourceNodeRenderer = createConstantSourceNodeRendererFactory(connectAudioParam, createNativeConstantSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst constantSourceNodeConstructor = createConstantSourceNodeConstructor(audioNodeConstructor, createAudioParam, createConstantSourceNodeRenderer, createNativeConstantSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener);\nconst createNativeConvolverNode = createNativeConvolverNodeFactory(createNotSupportedError, overwriteAccessors);\nconst createConvolverNodeRenderer = createConvolverNodeRendererFactory(createNativeConvolverNode, getNativeAudioNode, renderInputsOfAudioNode);\nconst convolverNodeConstructor = createConvolverNodeConstructor(audioNodeConstructor, createConvolverNodeRenderer, createNativeConvolverNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst createDelayNodeRenderer = createDelayNodeRendererFactory(connectAudioParam, createNativeDelayNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst delayNodeConstructor = createDelayNodeConstructor(audioNodeConstructor, createAudioParam, createDelayNodeRenderer, createNativeDelayNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst createNativeDynamicsCompressorNode = createNativeDynamicsCompressorNodeFactory(createNotSupportedError);\nconst createDynamicsCompressorNodeRenderer = createDynamicsCompressorNodeRendererFactory(connectAudioParam, createNativeDynamicsCompressorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst dynamicsCompressorNodeConstructor = createDynamicsCompressorNodeConstructor(audioNodeConstructor, createAudioParam, createDynamicsCompressorNodeRenderer, createNativeDynamicsCompressorNode, createNotSupportedError, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst createGainNodeRenderer = createGainNodeRendererFactory(connectAudioParam, createNativeGainNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst gainNodeConstructor = createGainNodeConstructor(audioNodeConstructor, createAudioParam, createGainNodeRenderer, createNativeGainNode, getNativeContext, isNativeOfflineAudioContext);\nconst createNativeIIRFilterNodeFaker = createNativeIIRFilterNodeFakerFactory(createInvalidAccessError, createInvalidStateError, createNativeScriptProcessorNode, createNotSupportedError);\nconst renderNativeOfflineAudioContext = createRenderNativeOfflineAudioContext(cacheTestResult, createNativeGainNode, createNativeScriptProcessorNode, createTestOfflineAudioContextCurrentTimeSupport(createNativeGainNode, nativeOfflineAudioContextConstructor));\nconst createIIRFilterNodeRenderer = createIIRFilterNodeRendererFactory(createNativeAudioBufferSourceNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderInputsOfAudioNode, renderNativeOfflineAudioContext);\nconst createNativeIIRFilterNode = createNativeIIRFilterNodeFactory(createNativeIIRFilterNodeFaker);\nconst iIRFilterNodeConstructor = createIIRFilterNodeConstructor(audioNodeConstructor, createNativeIIRFilterNode, createIIRFilterNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst createAudioListener = createAudioListenerFactory(createAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeScriptProcessorNode, createNotSupportedError, getFirstSample, isNativeOfflineAudioContext, overwriteAccessors);\nconst unrenderedAudioWorkletNodeStore = new WeakMap();\nconst minimalBaseAudioContextConstructor = createMinimalBaseAudioContextConstructor(audioDestinationNodeConstructor, createAudioListener, eventTargetConstructor, isNativeOfflineAudioContext, unrenderedAudioWorkletNodeStore, wrapEventListener);\nconst createNativeOscillatorNode = createNativeOscillatorNodeFactory(addSilentConnection, cacheTestResult, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls);\nconst createOscillatorNodeRenderer = createOscillatorNodeRendererFactory(connectAudioParam, createNativeOscillatorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst oscillatorNodeConstructor = createOscillatorNodeConstructor(audioNodeConstructor, createAudioParam, createNativeOscillatorNode, createOscillatorNodeRenderer, getNativeContext, isNativeOfflineAudioContext, wrapEventListener);\nconst createConnectedNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNodeFactory(createNativeAudioBufferSourceNode);\nconst createNativeWaveShaperNodeFaker = createNativeWaveShaperNodeFakerFactory(createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeGainNode, isDCCurve, monitorConnections);\nconst createNativeWaveShaperNode = createNativeWaveShaperNodeFactory(createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeWaveShaperNodeFaker, isDCCurve, monitorConnections, nativeAudioContextConstructor, overwriteAccessors);\nconst createNativePannerNodeFaker = createNativePannerNodeFakerFactory(connectNativeAudioNodeToNativeAudioNode, createInvalidStateError, createNativeChannelMergerNode, createNativeGainNode, createNativeScriptProcessorNode, createNativeWaveShaperNode, createNotSupportedError, disconnectNativeAudioNodeFromNativeAudioNode, getFirstSample, monitorConnections);\nconst createNativePannerNode = createNativePannerNodeFactory(createNativePannerNodeFaker);\nconst createPannerNodeRenderer = createPannerNodeRendererFactory(connectAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeGainNode, createNativePannerNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext);\nconst pannerNodeConstructor = createPannerNodeConstructor(audioNodeConstructor, createAudioParam, createNativePannerNode, createPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst createNativePeriodicWave = createNativePeriodicWaveFactory(createIndexSizeError);\nconst periodicWaveConstructor = createPeriodicWaveConstructor(createNativePeriodicWave, getNativeContext, new WeakSet(), sanitizePeriodicWaveOptions);\nconst nativeStereoPannerNodeFakerFactory = createNativeStereoPannerNodeFakerFactory(createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeGainNode, createNativeWaveShaperNode, createNotSupportedError, monitorConnections);\nconst createNativeStereoPannerNode = createNativeStereoPannerNodeFactory(nativeStereoPannerNodeFakerFactory, createNotSupportedError);\nconst createStereoPannerNodeRenderer = createStereoPannerNodeRendererFactory(connectAudioParam, createNativeStereoPannerNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);\nconst stereoPannerNodeConstructor = createStereoPannerNodeConstructor(audioNodeConstructor, createAudioParam, createNativeStereoPannerNode, createStereoPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext);\nconst createWaveShaperNodeRenderer = createWaveShaperNodeRendererFactory(createNativeWaveShaperNode, getNativeAudioNode, renderInputsOfAudioNode);\nconst waveShaperNodeConstructor = createWaveShaperNodeConstructor(audioNodeConstructor, createInvalidStateError, createNativeWaveShaperNode, createWaveShaperNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime);\nconst isSecureContext = createIsSecureContext(window);\nconst exposeCurrentFrameAndCurrentTime = createExposeCurrentFrameAndCurrentTime(window);\nconst backupOfflineAudioContextStore = new WeakMap();\nconst getOrCreateBackupOfflineAudioContext = createGetOrCreateBackupOfflineAudioContext(backupOfflineAudioContextStore, nativeOfflineAudioContextConstructor);\n// The addAudioWorkletModule() function is only available in a SecureContext.\nexport const addAudioWorkletModule = isSecureContext\n ? createAddAudioWorkletModule(cacheTestResult, createNotSupportedError, createEvaluateSource(window), exposeCurrentFrameAndCurrentTime, createFetchSource(createAbortError), getNativeContext, getOrCreateBackupOfflineAudioContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, new WeakMap(), new WeakMap(), createTestAudioWorkletProcessorPostMessageSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor), \n // @todo window is guaranteed to be defined because isSecureContext checks that as well.\n window)\n : undefined;\nconst isNativeContext = createIsNativeContext(isNativeAudioContext, isNativeOfflineAudioContext);\nexport const decodeAudioData = createDecodeAudioData(audioBufferStore, cacheTestResult, createDataCloneError, createEncodingError, new WeakSet(), getNativeContext, isNativeContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, testPromiseSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds);\nconst baseAudioContextConstructor = createBaseAudioContextConstructor(addAudioWorkletModule, analyserNodeConstructor, audioBufferConstructor, audioBufferSourceNodeConstructor, biquadFilterNodeConstructor, channelMergerNodeConstructor, channelSplitterNodeConstructor, constantSourceNodeConstructor, convolverNodeConstructor, decodeAudioData, delayNodeConstructor, dynamicsCompressorNodeConstructor, gainNodeConstructor, iIRFilterNodeConstructor, minimalBaseAudioContextConstructor, oscillatorNodeConstructor, pannerNodeConstructor, periodicWaveConstructor, stereoPannerNodeConstructor, waveShaperNodeConstructor);\nconst mediaElementAudioSourceNodeConstructor = createMediaElementAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaElementAudioSourceNode, getNativeContext, isNativeOfflineAudioContext);\nconst mediaStreamAudioDestinationNodeConstructor = createMediaStreamAudioDestinationNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioDestinationNode, getNativeContext, isNativeOfflineAudioContext);\nconst mediaStreamAudioSourceNodeConstructor = createMediaStreamAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioSourceNode, getNativeContext, isNativeOfflineAudioContext);\nconst createNativeMediaStreamTrackAudioSourceNode = createNativeMediaStreamTrackAudioSourceNodeFactory(createInvalidStateError, isNativeOfflineAudioContext);\nconst mediaStreamTrackAudioSourceNodeConstructor = createMediaStreamTrackAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamTrackAudioSourceNode, getNativeContext);\nconst audioContextConstructor = createAudioContextConstructor(baseAudioContextConstructor, createInvalidStateError, createNotSupportedError, createUnknownError, mediaElementAudioSourceNodeConstructor, mediaStreamAudioDestinationNodeConstructor, mediaStreamAudioSourceNodeConstructor, mediaStreamTrackAudioSourceNodeConstructor, nativeAudioContextConstructor);\nexport { audioContextConstructor as AudioContext };\nconst getUnrenderedAudioWorkletNodes = createGetUnrenderedAudioWorkletNodes(unrenderedAudioWorkletNodeStore);\nconst addUnrenderedAudioWorkletNode = createAddUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes);\nconst connectMultipleOutputs = createConnectMultipleOutputs(createIndexSizeError);\nconst deleteUnrenderedAudioWorkletNode = createDeleteUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes);\nconst disconnectMultipleOutputs = createDisconnectMultipleOutputs(createIndexSizeError);\nconst activeAudioWorkletNodeInputsStore = new WeakMap();\nconst getActiveAudioWorkletNodeInputs = createGetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore, getValueForKey);\nconst createNativeAudioWorkletNodeFaker = createNativeAudioWorkletNodeFakerFactory(connectMultipleOutputs, createIndexSizeError, createInvalidStateError, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, createNativeScriptProcessorNode, createNotSupportedError, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getActiveAudioWorkletNodeInputs, monitorConnections);\nconst createNativeAudioWorkletNode = createNativeAudioWorkletNodeFactory(createInvalidStateError, createNativeAudioWorkletNodeFaker, createNativeGainNode, createNotSupportedError, monitorConnections);\nconst createAudioWorkletNodeRenderer = createAudioWorkletNodeRendererFactory(connectAudioParam, connectMultipleOutputs, createNativeAudioBufferSourceNode, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, deleteUnrenderedAudioWorkletNode, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getNativeAudioNode, nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext);\nconst getBackupOfflineAudioContext = createGetBackupOfflineAudioContext(backupOfflineAudioContextStore);\nconst setActiveAudioWorkletNodeInputs = createSetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore);\n// The AudioWorkletNode constructor is only available in a SecureContext.\nconst audioWorkletNodeConstructor = isSecureContext\n ? createAudioWorkletNodeConstructor(addUnrenderedAudioWorkletNode, audioNodeConstructor, createAudioParam, createAudioWorkletNodeRenderer, createNativeAudioWorkletNode, getAudioNodeConnections, getBackupOfflineAudioContext, getNativeContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, sanitizeAudioWorkletNodeOptions, setActiveAudioWorkletNodeInputs, testAudioWorkletNodeOptionsClonability, wrapEventListener)\n : undefined;\nexport { audioWorkletNodeConstructor as AudioWorkletNode };\nexport { biquadFilterNodeConstructor as BiquadFilterNode };\nexport { channelMergerNodeConstructor as ChannelMergerNode };\nexport { channelSplitterNodeConstructor as ChannelSplitterNode };\nexport { convolverNodeConstructor as ConvolverNode };\nexport { constantSourceNodeConstructor as ConstantSourceNode };\nexport { delayNodeConstructor as DelayNode };\nexport { dynamicsCompressorNodeConstructor as DynamicsCompressorNode };\nexport { gainNodeConstructor as GainNode };\nexport { iIRFilterNodeConstructor as IIRFilterNode };\nexport { mediaElementAudioSourceNodeConstructor as MediaElementAudioSourceNode };\nexport { mediaStreamAudioDestinationNodeConstructor as MediaStreamAudioDestinationNode };\nexport { mediaStreamAudioSourceNodeConstructor as MediaStreamAudioSourceNode };\nexport { mediaStreamTrackAudioSourceNodeConstructor as MediaStreamTrackAudioSourceNode };\nconst minimalAudioContextConstructor = createMinimalAudioContextConstructor(createInvalidStateError, createNotSupportedError, createUnknownError, minimalBaseAudioContextConstructor, nativeAudioContextConstructor);\nexport { minimalAudioContextConstructor as MinimalAudioContext };\nconst createNativeOfflineAudioContext = createCreateNativeOfflineAudioContext(createNotSupportedError, nativeOfflineAudioContextConstructor);\nconst startRendering = createStartRendering(audioBufferStore, cacheTestResult, getAudioNodeRenderer, getUnrenderedAudioWorkletNodes, renderNativeOfflineAudioContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds);\nconst minimalOfflineAudioContextConstructor = createMinimalOfflineAudioContextConstructor(cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, minimalBaseAudioContextConstructor, startRendering);\nexport { minimalOfflineAudioContextConstructor as MinimalOfflineAudioContext };\nconst offlineAudioContextConstructor = createOfflineAudioContextConstructor(baseAudioContextConstructor, cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, startRendering);\nexport { offlineAudioContextConstructor as OfflineAudioContext };\nexport { oscillatorNodeConstructor as OscillatorNode };\nexport { pannerNodeConstructor as PannerNode };\nexport { periodicWaveConstructor as PeriodicWave };\nexport { stereoPannerNodeConstructor as StereoPannerNode };\nexport { waveShaperNodeConstructor as WaveShaperNode };\nexport const isAnyAudioContext = createIsAnyAudioContext(CONTEXT_STORE, isNativeAudioContext);\nexport const isAnyAudioNode = createIsAnyAudioNode(AUDIO_NODE_STORE, isNativeAudioNode);\nexport const isAnyAudioParam = createIsAnyAudioParam(AUDIO_PARAM_STORE, isNativeAudioParam);\nexport const isAnyOfflineAudioContext = createIsAnyOfflineAudioContext(CONTEXT_STORE, isNativeOfflineAudioContext);\nexport const isSupported = () => createIsSupportedPromise(cacheTestResult, createTestAudioBufferCopyChannelMethodsSubarraySupport(nativeOfflineAudioContextConstructor), createTestAudioContextCloseMethodSupport(nativeAudioContextConstructor), createTestAudioContextDecodeAudioDataMethodTypeErrorSupport(nativeOfflineAudioContextConstructor), createTestAudioContextOptionsSupport(nativeAudioContextConstructor), createTestAudioNodeConnectMethodSupport(nativeOfflineAudioContextConstructor), createTestAudioWorkletProcessorNoOutputsSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor), createTestChannelMergerNodeChannelCountSupport(nativeOfflineAudioContextConstructor), createTestConstantSourceNodeAccurateSchedulingSupport(nativeOfflineAudioContextConstructor), createTestConvolverNodeBufferReassignabilitySupport(nativeOfflineAudioContextConstructor), createTestConvolverNodeChannelCountSupport(nativeOfflineAudioContextConstructor), testDomExceptionConstructorSupport, createTestIsSecureContextSupport(window), createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport(nativeAudioContextConstructor), createTestStereoPannerNodeDefaultValueSupport(nativeOfflineAudioContextConstructor), testTransferablesSupport);\n//# sourceMappingURL=module.js.map","/**\n * Assert that the statement is true, otherwise invoke the error.\n * @param statement\n * @param error The message which is passed into an Error\n */\nexport function assert(statement, error) {\n if (!statement) {\n throw new Error(error);\n }\n}\n/**\n * Make sure that the given value is within the range\n */\nexport function assertRange(value, gte, lte = Infinity) {\n if (!(gte <= value && value <= lte)) {\n throw new RangeError(`Value must be within [${gte}, ${lte}], got: ${value}`);\n }\n}\n/**\n * Make sure that the given value is within the range\n */\nexport function assertContextRunning(context) {\n // add a warning if the context is not started\n if (!context.isOffline && context.state !== \"running\") {\n warn(\"The AudioContext is \\\"suspended\\\". Invoke Tone.start() from a user action to start the audio.\");\n }\n}\n/**\n * The default logger is the console\n */\nlet defaultLogger = console;\n/**\n * Set the logging interface\n */\nexport function setLogger(logger) {\n defaultLogger = logger;\n}\n/**\n * Log anything\n */\nexport function log(...args) {\n defaultLogger.log(...args);\n}\n/**\n * Warn anything\n */\nexport function warn(...args) {\n defaultLogger.warn(...args);\n}\n//# sourceMappingURL=Debug.js.map","/**\n * Test if the arg is undefined\n */\nexport function isUndef(arg) {\n return typeof arg === \"undefined\";\n}\n/**\n * Test if the arg is not undefined\n */\nexport function isDefined(arg) {\n return !isUndef(arg);\n}\n/**\n * Test if the arg is a function\n */\nexport function isFunction(arg) {\n return typeof arg === \"function\";\n}\n/**\n * Test if the argument is a number.\n */\nexport function isNumber(arg) {\n return (typeof arg === \"number\");\n}\n/**\n * Test if the given argument is an object literal (i.e. `{}`);\n */\nexport function isObject(arg) {\n return (Object.prototype.toString.call(arg) === \"[object Object]\" && arg.constructor === Object);\n}\n/**\n * Test if the argument is a boolean.\n */\nexport function isBoolean(arg) {\n return (typeof arg === \"boolean\");\n}\n/**\n * Test if the argument is an Array\n */\nexport function isArray(arg) {\n return (Array.isArray(arg));\n}\n/**\n * Test if the argument is a string.\n */\nexport function isString(arg) {\n return (typeof arg === \"string\");\n}\n/**\n * Test if the argument is in the form of a note in scientific pitch notation.\n * e.g. \"C4\"\n */\nexport function isNote(arg) {\n return isString(arg) && /^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(arg);\n}\n//# sourceMappingURL=TypeCheck.js.map","import { AudioContext as stdAudioContext, AudioWorkletNode as stdAudioWorkletNode, OfflineAudioContext as stdOfflineAudioContext } from \"standardized-audio-context\";\nimport { assert } from \"../util/Debug\";\nimport { isDefined } from \"../util/TypeCheck\";\n/**\n * Create a new AudioContext\n */\nexport function createAudioContext(options) {\n return new stdAudioContext(options);\n}\n/**\n * Create a new OfflineAudioContext\n */\nexport function createOfflineAudioContext(channels, length, sampleRate) {\n return new stdOfflineAudioContext(channels, length, sampleRate);\n}\n/**\n * A reference to the window object\n * @hidden\n */\nexport const theWindow = typeof self === \"object\" ? self : null;\n/**\n * If the browser has a window object which has an AudioContext\n * @hidden\n */\nexport const hasAudioContext = theWindow &&\n (theWindow.hasOwnProperty(\"AudioContext\") || theWindow.hasOwnProperty(\"webkitAudioContext\"));\nexport function createAudioWorkletNode(context, name, options) {\n assert(isDefined(stdAudioWorkletNode), \"This node only works in a secure context (https or localhost)\");\n // @ts-ignore\n return new stdAudioWorkletNode(context, name, options);\n}\n/**\n * This promise resolves to a boolean which indicates if the\n * functionality is supported within the currently used browse.\n * Taken from [standardized-audio-context](https://github.com/chrisguttandin/standardized-audio-context#issupported)\n */\nexport { isSupported as supported } from \"standardized-audio-context\";\n//# sourceMappingURL=AudioContext.js.map","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n","/**\n * A class which provides a reliable callback using either\n * a Web Worker, or if that isn't supported, falls back to setTimeout.\n */\nexport class Ticker {\n constructor(callback, type, updateInterval) {\n this._callback = callback;\n this._type = type;\n this._updateInterval = updateInterval;\n // create the clock source for the first time\n this._createClock();\n }\n /**\n * Generate a web worker\n */\n _createWorker() {\n const blob = new Blob([\n /* javascript */ `\n\t\t\t// the initial timeout time\n\t\t\tlet timeoutTime = ${(this._updateInterval * 1000).toFixed(1)};\n\t\t\t// onmessage callback\n\t\t\tself.onmessage = function(msg){\n\t\t\t\ttimeoutTime = parseInt(msg.data);\n\t\t\t};\n\t\t\t// the tick function which posts a message\n\t\t\t// and schedules a new tick\n\t\t\tfunction tick(){\n\t\t\t\tsetTimeout(tick, timeoutTime);\n\t\t\t\tself.postMessage('tick');\n\t\t\t}\n\t\t\t// call tick initially\n\t\t\ttick();\n\t\t\t`\n ], { type: \"text/javascript\" });\n const blobUrl = URL.createObjectURL(blob);\n const worker = new Worker(blobUrl);\n worker.onmessage = this._callback.bind(this);\n this._worker = worker;\n }\n /**\n * Create a timeout loop\n */\n _createTimeout() {\n this._timeout = setTimeout(() => {\n this._createTimeout();\n this._callback();\n }, this._updateInterval * 1000);\n }\n /**\n * Create the clock source.\n */\n _createClock() {\n if (this._type === \"worker\") {\n try {\n this._createWorker();\n }\n catch (e) {\n // workers not supported, fallback to timeout\n this._type = \"timeout\";\n this._createClock();\n }\n }\n else if (this._type === \"timeout\") {\n this._createTimeout();\n }\n }\n /**\n * Clean up the current clock source\n */\n _disposeClock() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n this._timeout = 0;\n }\n if (this._worker) {\n this._worker.terminate();\n this._worker.onmessage = null;\n }\n }\n /**\n * The rate in seconds the ticker will update\n */\n get updateInterval() {\n return this._updateInterval;\n }\n set updateInterval(interval) {\n this._updateInterval = Math.max(interval, 128 / 44100);\n if (this._type === \"worker\") {\n this._worker.postMessage(Math.max(interval * 1000, 1));\n }\n }\n /**\n * The type of the ticker, either a worker or a timeout\n */\n get type() {\n return this._type;\n }\n set type(type) {\n this._disposeClock();\n this._type = type;\n this._createClock();\n }\n /**\n * Clean up\n */\n dispose() {\n this._disposeClock();\n }\n}\n//# sourceMappingURL=Ticker.js.map","import { isAnyAudioContext, isAnyAudioNode, isAnyAudioParam, isAnyOfflineAudioContext, } from \"standardized-audio-context\";\n/**\n * Test if the given value is an instanceof AudioParam\n */\nexport function isAudioParam(arg) {\n return isAnyAudioParam(arg);\n}\n/**\n * Test if the given value is an instanceof AudioNode\n */\nexport function isAudioNode(arg) {\n return isAnyAudioNode(arg);\n}\n/**\n * Test if the arg is instanceof an OfflineAudioContext\n */\nexport function isOfflineAudioContext(arg) {\n return isAnyOfflineAudioContext(arg);\n}\n/**\n * Test if the arg is an instanceof AudioContext\n */\nexport function isAudioContext(arg) {\n return isAnyAudioContext(arg);\n}\n/**\n * Test if the arg is instanceof an AudioBuffer\n */\nexport function isAudioBuffer(arg) {\n return arg instanceof AudioBuffer;\n}\n//# sourceMappingURL=AdvancedTypeCheck.js.map","import { isAudioBuffer, isAudioNode, isAudioParam } from \"./AdvancedTypeCheck\";\nimport { isDefined, isObject, isUndef } from \"./TypeCheck\";\n/**\n * Some objects should not be merged\n */\nfunction noCopy(key, arg) {\n return key === \"value\" || isAudioParam(arg) || isAudioNode(arg) || isAudioBuffer(arg);\n}\nexport function deepMerge(target, ...sources) {\n if (!sources.length) {\n return target;\n }\n const source = sources.shift();\n if (isObject(target) && isObject(source)) {\n for (const key in source) {\n if (noCopy(key, source[key])) {\n target[key] = source[key];\n }\n else if (isObject(source[key])) {\n if (!target[key]) {\n Object.assign(target, { [key]: {} });\n }\n deepMerge(target[key], source[key]);\n }\n else {\n Object.assign(target, { [key]: source[key] });\n }\n }\n }\n // @ts-ignore\n return deepMerge(target, ...sources);\n}\n/**\n * Returns true if the two arrays have the same value for each of the elements\n */\nexport function deepEquals(arrayA, arrayB) {\n return arrayA.length === arrayB.length && arrayA.every((element, index) => arrayB[index] === element);\n}\n/**\n * Convert an args array into an object.\n */\nexport function optionsFromArguments(defaults, argsArray, keys = [], objKey) {\n const opts = {};\n const args = Array.from(argsArray);\n // if the first argument is an object and has an object key\n if (isObject(args[0]) && objKey && !Reflect.has(args[0], objKey)) {\n // if it's not part of the defaults\n const partOfDefaults = Object.keys(args[0]).some(key => Reflect.has(defaults, key));\n if (!partOfDefaults) {\n // merge that key\n deepMerge(opts, { [objKey]: args[0] });\n // remove the obj key from the keys\n keys.splice(keys.indexOf(objKey), 1);\n // shift the first argument off\n args.shift();\n }\n }\n if (args.length === 1 && isObject(args[0])) {\n deepMerge(opts, args[0]);\n }\n else {\n for (let i = 0; i < keys.length; i++) {\n if (isDefined(args[i])) {\n opts[keys[i]] = args[i];\n }\n }\n }\n return deepMerge(defaults, opts);\n}\n/**\n * Return this instances default values by calling Constructor.getDefaults()\n */\nexport function getDefaultsFromInstance(instance) {\n return instance.constructor.getDefaults();\n}\n/**\n * Returns the fallback if the given object is undefined.\n * Take an array of arguments and return a formatted options object.\n */\nexport function defaultArg(given, fallback) {\n if (isUndef(given)) {\n return fallback;\n }\n else {\n return given;\n }\n}\n/**\n * Remove all of the properties belonging to omit from obj.\n */\nexport function omitFromObject(obj, omit) {\n omit.forEach(prop => {\n if (Reflect.has(obj, prop)) {\n delete obj[prop];\n }\n });\n return obj;\n}\n//# sourceMappingURL=Defaults.js.map","/**\n * Tone.js\n * @author Yotam Mann\n * @license http://opensource.org/licenses/MIT MIT License\n * @copyright 2014-2019 Yotam Mann\n */\nimport { version } from \"../version\";\nimport { theWindow } from \"./context/AudioContext\";\nimport { log } from \"./util/Debug\";\n/**\n * @class Tone is the base class of all other classes.\n * @category Core\n * @constructor\n */\nexport class Tone {\n constructor() {\n //-------------------------------------\n // \tDEBUGGING\n //-------------------------------------\n /**\n * Set this debug flag to log all events that happen in this class.\n */\n this.debug = false;\n //-------------------------------------\n // \tDISPOSING\n //-------------------------------------\n /**\n * Indicates if the instance was disposed\n */\n this._wasDisposed = false;\n }\n /**\n * Returns all of the default options belonging to the class.\n */\n static getDefaults() {\n return {};\n }\n /**\n * Prints the outputs to the console log for debugging purposes.\n * Prints the contents only if either the object has a property\n * called `debug` set to true, or a variable called TONE_DEBUG_CLASS\n * is set to the name of the class.\n * @example\n * const osc = new Tone.Oscillator();\n * // prints all logs originating from this oscillator\n * osc.debug = true;\n * // calls to start/stop will print in the console\n * osc.start();\n */\n log(...args) {\n // if the object is either set to debug = true\n // or if there is a string on the Tone.global.with the class name\n if (this.debug || (theWindow && this.toString() === theWindow.TONE_DEBUG_CLASS)) {\n log(this, ...args);\n }\n }\n /**\n * disconnect and dispose.\n */\n dispose() {\n this._wasDisposed = true;\n return this;\n }\n /**\n * Indicates if the instance was disposed. 'Disposing' an\n * instance means that all of the Web Audio nodes that were\n * created for the instance are disconnected and freed for garbage collection.\n */\n get disposed() {\n return this._wasDisposed;\n }\n /**\n * Convert the class to a string\n * @example\n * const osc = new Tone.Oscillator();\n * console.log(osc.toString());\n */\n toString() {\n return this.name;\n }\n}\n/**\n * The version number semver\n */\nTone.version = version;\n//# sourceMappingURL=Tone.js.map","/**\n * The threshold for correctness for operators. Less than one sample even\n * at very high sampling rates (e.g. `1e-6 < 1 / 192000`).\n */\nconst EPSILON = 1e-6;\n/**\n * Test if A is greater than B\n */\nexport function GT(a, b) {\n return a > b + EPSILON;\n}\n/**\n * Test if A is greater than or equal to B\n */\nexport function GTE(a, b) {\n return GT(a, b) || EQ(a, b);\n}\n/**\n * Test if A is less than B\n */\nexport function LT(a, b) {\n return a + EPSILON < b;\n}\n/**\n * Test if A is less than B\n */\nexport function EQ(a, b) {\n return Math.abs(a - b) < EPSILON;\n}\n/**\n * Clamp the value within the given range\n */\nexport function clamp(value, min, max) {\n return Math.max(Math.min(value, max), min);\n}\n//# sourceMappingURL=Math.js.map","import { Tone } from \"../Tone\";\nimport { optionsFromArguments } from \"./Defaults\";\nimport { assert } from \"./Debug\";\nimport { EQ, GT, GTE, LT } from \"./Math\";\n/**\n * A Timeline class for scheduling and maintaining state\n * along a timeline. All events must have a \"time\" property.\n * Internally, events are stored in time order for fast\n * retrieval.\n */\nexport class Timeline extends Tone {\n constructor() {\n super();\n this.name = \"Timeline\";\n /**\n * The array of scheduled timeline events\n */\n this._timeline = [];\n const options = optionsFromArguments(Timeline.getDefaults(), arguments, [\"memory\"]);\n this.memory = options.memory;\n this.increasing = options.increasing;\n }\n static getDefaults() {\n return {\n memory: Infinity,\n increasing: false,\n };\n }\n /**\n * The number of items in the timeline.\n */\n get length() {\n return this._timeline.length;\n }\n /**\n * Insert an event object onto the timeline. Events must have a \"time\" attribute.\n * @param event The event object to insert into the timeline.\n */\n add(event) {\n // the event needs to have a time attribute\n assert(Reflect.has(event, \"time\"), \"Timeline: events must have a time attribute\");\n event.time = event.time.valueOf();\n if (this.increasing && this.length) {\n const lastValue = this._timeline[this.length - 1];\n assert(GTE(event.time, lastValue.time), \"The time must be greater than or equal to the last scheduled time\");\n this._timeline.push(event);\n }\n else {\n const index = this._search(event.time);\n this._timeline.splice(index + 1, 0, event);\n }\n // if the length is more than the memory, remove the previous ones\n if (this.length > this.memory) {\n const diff = this.length - this.memory;\n this._timeline.splice(0, diff);\n }\n return this;\n }\n /**\n * Remove an event from the timeline.\n * @param {Object} event The event object to remove from the list.\n * @returns {Timeline} this\n */\n remove(event) {\n const index = this._timeline.indexOf(event);\n if (index !== -1) {\n this._timeline.splice(index, 1);\n }\n return this;\n }\n /**\n * Get the nearest event whose time is less than or equal to the given time.\n * @param time The time to query.\n */\n get(time, param = \"time\") {\n const index = this._search(time, param);\n if (index !== -1) {\n return this._timeline[index];\n }\n else {\n return null;\n }\n }\n /**\n * Return the first event in the timeline without removing it\n * @returns {Object} The first event object\n */\n peek() {\n return this._timeline[0];\n }\n /**\n * Return the first event in the timeline and remove it\n */\n shift() {\n return this._timeline.shift();\n }\n /**\n * Get the event which is scheduled after the given time.\n * @param time The time to query.\n */\n getAfter(time, param = \"time\") {\n const index = this._search(time, param);\n if (index + 1 < this._timeline.length) {\n return this._timeline[index + 1];\n }\n else {\n return null;\n }\n }\n /**\n * Get the event before the event at the given time.\n * @param time The time to query.\n */\n getBefore(time) {\n const len = this._timeline.length;\n // if it's after the last item, return the last item\n if (len > 0 && this._timeline[len - 1].time < time) {\n return this._timeline[len - 1];\n }\n const index = this._search(time);\n if (index - 1 >= 0) {\n return this._timeline[index - 1];\n }\n else {\n return null;\n }\n }\n /**\n * Cancel events at and after the given time\n * @param after The time to query.\n */\n cancel(after) {\n if (this._timeline.length > 1) {\n let index = this._search(after);\n if (index >= 0) {\n if (EQ(this._timeline[index].time, after)) {\n // get the first item with that time\n for (let i = index; i >= 0; i--) {\n if (EQ(this._timeline[i].time, after)) {\n index = i;\n }\n else {\n break;\n }\n }\n this._timeline = this._timeline.slice(0, index);\n }\n else {\n this._timeline = this._timeline.slice(0, index + 1);\n }\n }\n else {\n this._timeline = [];\n }\n }\n else if (this._timeline.length === 1) {\n // the first item's time\n if (GTE(this._timeline[0].time, after)) {\n this._timeline = [];\n }\n }\n return this;\n }\n /**\n * Cancel events before or equal to the given time.\n * @param time The time to cancel before.\n */\n cancelBefore(time) {\n const index = this._search(time);\n if (index >= 0) {\n this._timeline = this._timeline.slice(index + 1);\n }\n return this;\n }\n /**\n * Returns the previous event if there is one. null otherwise\n * @param event The event to find the previous one of\n * @return The event right before the given event\n */\n previousEvent(event) {\n const index = this._timeline.indexOf(event);\n if (index > 0) {\n return this._timeline[index - 1];\n }\n else {\n return null;\n }\n }\n /**\n * Does a binary search on the timeline array and returns the\n * nearest event index whose time is after or equal to the given time.\n * If a time is searched before the first index in the timeline, -1 is returned.\n * If the time is after the end, the index of the last item is returned.\n */\n _search(time, param = \"time\") {\n if (this._timeline.length === 0) {\n return -1;\n }\n let beginning = 0;\n const len = this._timeline.length;\n let end = len;\n if (len > 0 && this._timeline[len - 1][param] <= time) {\n return len - 1;\n }\n while (beginning < end) {\n // calculate the midpoint for roughly equal partition\n let midPoint = Math.floor(beginning + (end - beginning) / 2);\n const event = this._timeline[midPoint];\n const nextEvent = this._timeline[midPoint + 1];\n if (EQ(event[param], time)) {\n // choose the last one that has the same time\n for (let i = midPoint; i < this._timeline.length; i++) {\n const testEvent = this._timeline[i];\n if (EQ(testEvent[param], time)) {\n midPoint = i;\n }\n else {\n break;\n }\n }\n return midPoint;\n }\n else if (LT(event[param], time) && GT(nextEvent[param], time)) {\n return midPoint;\n }\n else if (GT(event[param], time)) {\n // search lower\n end = midPoint;\n }\n else {\n // search upper\n beginning = midPoint + 1;\n }\n }\n return -1;\n }\n /**\n * Internal iterator. Applies extra safety checks for\n * removing items from the array.\n */\n _iterate(callback, lowerBound = 0, upperBound = this._timeline.length - 1) {\n this._timeline.slice(lowerBound, upperBound + 1).forEach(callback);\n }\n /**\n * Iterate over everything in the array\n * @param callback The callback to invoke with every item\n */\n forEach(callback) {\n this._iterate(callback);\n return this;\n }\n /**\n * Iterate over everything in the array at or before the given time.\n * @param time The time to check if items are before\n * @param callback The callback to invoke with every item\n */\n forEachBefore(time, callback) {\n // iterate over the items in reverse so that removing an item doesn't break things\n const upperBound = this._search(time);\n if (upperBound !== -1) {\n this._iterate(callback, 0, upperBound);\n }\n return this;\n }\n /**\n * Iterate over everything in the array after the given time.\n * @param time The time to check if items are before\n * @param callback The callback to invoke with every item\n */\n forEachAfter(time, callback) {\n // iterate over the items in reverse so that removing an item doesn't break things\n const lowerBound = this._search(time);\n this._iterate(callback, lowerBound + 1);\n return this;\n }\n /**\n * Iterate over everything in the array between the startTime and endTime.\n * The timerange is inclusive of the startTime, but exclusive of the endTime.\n * range = [startTime, endTime).\n * @param startTime The time to check if items are before\n * @param endTime The end of the test interval.\n * @param callback The callback to invoke with every item\n */\n forEachBetween(startTime, endTime, callback) {\n let lowerBound = this._search(startTime);\n let upperBound = this._search(endTime);\n if (lowerBound !== -1 && upperBound !== -1) {\n if (this._timeline[lowerBound].time !== startTime) {\n lowerBound += 1;\n }\n // exclusive of the end time\n if (this._timeline[upperBound].time === endTime) {\n upperBound -= 1;\n }\n this._iterate(callback, lowerBound, upperBound);\n }\n else if (lowerBound === -1) {\n this._iterate(callback, 0, upperBound);\n }\n return this;\n }\n /**\n * Iterate over everything in the array at or after the given time. Similar to\n * forEachAfter, but includes the item(s) at the given time.\n * @param time The time to check if items are before\n * @param callback The callback to invoke with every item\n */\n forEachFrom(time, callback) {\n // iterate over the items in reverse so that removing an item doesn't break things\n let lowerBound = this._search(time);\n // work backwards until the event time is less than time\n while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) {\n lowerBound--;\n }\n this._iterate(callback, lowerBound + 1);\n return this;\n }\n /**\n * Iterate over everything in the array at the given time\n * @param time The time to check if items are before\n * @param callback The callback to invoke with every item\n */\n forEachAtTime(time, callback) {\n // iterate over the items in reverse so that removing an item doesn't break things\n const upperBound = this._search(time);\n if (upperBound !== -1 && EQ(this._timeline[upperBound].time, time)) {\n let lowerBound = upperBound;\n for (let i = upperBound; i >= 0; i--) {\n if (EQ(this._timeline[i].time, time)) {\n lowerBound = i;\n }\n else {\n break;\n }\n }\n this._iterate(event => {\n callback(event);\n }, lowerBound, upperBound);\n }\n return this;\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this._timeline = [];\n return this;\n }\n}\n//# sourceMappingURL=Timeline.js.map","//-------------------------------------\n// INITIALIZING NEW CONTEXT\n//-------------------------------------\n/**\n * Array of callbacks to invoke when a new context is created\n */\nconst notifyNewContext = [];\n/**\n * Used internally to setup a new Context\n */\nexport function onContextInit(cb) {\n notifyNewContext.push(cb);\n}\n/**\n * Invoke any classes which need to also be initialized when a new context is created.\n */\nexport function initializeContext(ctx) {\n // add any additional modules\n notifyNewContext.forEach(cb => cb(ctx));\n}\n/**\n * Array of callbacks to invoke when a new context is created\n */\nconst notifyCloseContext = [];\n/**\n * Used internally to tear down a Context\n */\nexport function onContextClose(cb) {\n notifyCloseContext.push(cb);\n}\nexport function closeContext(ctx) {\n // add any additional modules\n notifyCloseContext.forEach(cb => cb(ctx));\n}\n//# sourceMappingURL=ContextInitialization.js.map","import { Tone } from \"../Tone\";\nimport { isUndef } from \"./TypeCheck\";\n/**\n * Emitter gives classes which extend it\n * the ability to listen for and emit events.\n * Inspiration and reference from Jerome Etienne's [MicroEvent](https://github.com/jeromeetienne/microevent.js).\n * MIT (c) 2011 Jerome Etienne.\n * @category Core\n */\nexport class Emitter extends Tone {\n constructor() {\n super(...arguments);\n this.name = \"Emitter\";\n }\n /**\n * Bind a callback to a specific event.\n * @param event The name of the event to listen for.\n * @param callback The callback to invoke when the event is emitted\n */\n on(event, callback) {\n // split the event\n const events = event.split(/\\W+/);\n events.forEach(eventName => {\n if (isUndef(this._events)) {\n this._events = {};\n }\n if (!this._events.hasOwnProperty(eventName)) {\n this._events[eventName] = [];\n }\n this._events[eventName].push(callback);\n });\n return this;\n }\n /**\n * Bind a callback which is only invoked once\n * @param event The name of the event to listen for.\n * @param callback The callback to invoke when the event is emitted\n */\n once(event, callback) {\n const boundCallback = (...args) => {\n // invoke the callback\n callback(...args);\n // remove the event\n this.off(event, boundCallback);\n };\n this.on(event, boundCallback);\n return this;\n }\n /**\n * Remove the event listener.\n * @param event The event to stop listening to.\n * @param callback The callback which was bound to the event with Emitter.on.\n * If no callback is given, all callbacks events are removed.\n */\n off(event, callback) {\n const events = event.split(/\\W+/);\n events.forEach(eventName => {\n if (isUndef(this._events)) {\n this._events = {};\n }\n if (this._events.hasOwnProperty(event)) {\n if (isUndef(callback)) {\n this._events[event] = [];\n }\n else {\n const eventList = this._events[event];\n for (let i = eventList.length - 1; i >= 0; i--) {\n if (eventList[i] === callback) {\n eventList.splice(i, 1);\n }\n }\n }\n }\n });\n return this;\n }\n /**\n * Invoke all of the callbacks bound to the event\n * with any arguments passed in.\n * @param event The name of the event.\n * @param args The arguments to pass to the functions listening.\n */\n emit(event, ...args) {\n if (this._events) {\n if (this._events.hasOwnProperty(event)) {\n const eventList = this._events[event].slice(0);\n for (let i = 0, len = eventList.length; i < len; i++) {\n eventList[i].apply(this, args);\n }\n }\n }\n return this;\n }\n /**\n * Add Emitter functions (on/off/emit) to the object\n */\n static mixin(constr) {\n // instance._events = {};\n [\"on\", \"once\", \"off\", \"emit\"].forEach(name => {\n const property = Object.getOwnPropertyDescriptor(Emitter.prototype, name);\n Object.defineProperty(constr.prototype, name, property);\n });\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this._events = undefined;\n return this;\n }\n}\n//# sourceMappingURL=Emitter.js.map","import { Emitter } from \"../util/Emitter\";\nexport class BaseContext extends Emitter {\n constructor() {\n super(...arguments);\n this.isOffline = false;\n }\n /*\n * This is a placeholder so that JSON.stringify does not throw an error\n * This matches what JSON.stringify(audioContext) returns on a native\n * audioContext instance.\n */\n toJSON() {\n return {};\n }\n}\n//# sourceMappingURL=BaseContext.js.map","import { __awaiter } from \"tslib\";\nimport { Ticker } from \"../clock/Ticker\";\nimport { isAudioContext } from \"../util/AdvancedTypeCheck\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { Timeline } from \"../util/Timeline\";\nimport { isDefined, isString } from \"../util/TypeCheck\";\nimport { createAudioContext, createAudioWorkletNode, } from \"./AudioContext\";\nimport { closeContext, initializeContext } from \"./ContextInitialization\";\nimport { BaseContext } from \"./BaseContext\";\nimport { assert } from \"../util/Debug\";\n/**\n * Wrapper around the native AudioContext.\n * @category Core\n */\nexport class Context extends BaseContext {\n constructor() {\n super();\n this.name = \"Context\";\n /**\n * An object containing all of the constants AudioBufferSourceNodes\n */\n this._constants = new Map();\n /**\n * All of the setTimeout events.\n */\n this._timeouts = new Timeline();\n /**\n * The timeout id counter\n */\n this._timeoutIds = 0;\n /**\n * Private indicator if the context has been initialized\n */\n this._initialized = false;\n /**\n * Indicates if the context is an OfflineAudioContext or an AudioContext\n */\n this.isOffline = false;\n //--------------------------------------------\n // AUDIO WORKLET\n //--------------------------------------------\n /**\n * Maps a module name to promise of the addModule method\n */\n this._workletModules = new Map();\n const options = optionsFromArguments(Context.getDefaults(), arguments, [\n \"context\",\n ]);\n if (options.context) {\n this._context = options.context;\n }\n else {\n this._context = createAudioContext({\n latencyHint: options.latencyHint,\n });\n }\n this._ticker = new Ticker(this.emit.bind(this, \"tick\"), options.clockSource, options.updateInterval);\n this.on(\"tick\", this._timeoutLoop.bind(this));\n // fwd events from the context\n this._context.onstatechange = () => {\n this.emit(\"statechange\", this.state);\n };\n this._setLatencyHint(options.latencyHint);\n this.lookAhead = options.lookAhead;\n }\n static getDefaults() {\n return {\n clockSource: \"worker\",\n latencyHint: \"interactive\",\n lookAhead: 0.1,\n updateInterval: 0.05,\n };\n }\n /**\n * Finish setting up the context. **You usually do not need to do this manually.**\n */\n initialize() {\n if (!this._initialized) {\n // add any additional modules\n initializeContext(this);\n this._initialized = true;\n }\n return this;\n }\n //---------------------------\n // BASE AUDIO CONTEXT METHODS\n //---------------------------\n createAnalyser() {\n return this._context.createAnalyser();\n }\n createOscillator() {\n return this._context.createOscillator();\n }\n createBufferSource() {\n return this._context.createBufferSource();\n }\n createBiquadFilter() {\n return this._context.createBiquadFilter();\n }\n createBuffer(numberOfChannels, length, sampleRate) {\n return this._context.createBuffer(numberOfChannels, length, sampleRate);\n }\n createChannelMerger(numberOfInputs) {\n return this._context.createChannelMerger(numberOfInputs);\n }\n createChannelSplitter(numberOfOutputs) {\n return this._context.createChannelSplitter(numberOfOutputs);\n }\n createConstantSource() {\n return this._context.createConstantSource();\n }\n createConvolver() {\n return this._context.createConvolver();\n }\n createDelay(maxDelayTime) {\n return this._context.createDelay(maxDelayTime);\n }\n createDynamicsCompressor() {\n return this._context.createDynamicsCompressor();\n }\n createGain() {\n return this._context.createGain();\n }\n createIIRFilter(feedForward, feedback) {\n // @ts-ignore\n return this._context.createIIRFilter(feedForward, feedback);\n }\n createPanner() {\n return this._context.createPanner();\n }\n createPeriodicWave(real, imag, constraints) {\n return this._context.createPeriodicWave(real, imag, constraints);\n }\n createStereoPanner() {\n return this._context.createStereoPanner();\n }\n createWaveShaper() {\n return this._context.createWaveShaper();\n }\n createMediaStreamSource(stream) {\n assert(isAudioContext(this._context), \"Not available if OfflineAudioContext\");\n const context = this._context;\n return context.createMediaStreamSource(stream);\n }\n createMediaElementSource(element) {\n assert(isAudioContext(this._context), \"Not available if OfflineAudioContext\");\n const context = this._context;\n return context.createMediaElementSource(element);\n }\n createMediaStreamDestination() {\n assert(isAudioContext(this._context), \"Not available if OfflineAudioContext\");\n const context = this._context;\n return context.createMediaStreamDestination();\n }\n decodeAudioData(audioData) {\n return this._context.decodeAudioData(audioData);\n }\n /**\n * The current time in seconds of the AudioContext.\n */\n get currentTime() {\n return this._context.currentTime;\n }\n /**\n * The current time in seconds of the AudioContext.\n */\n get state() {\n return this._context.state;\n }\n /**\n * The current time in seconds of the AudioContext.\n */\n get sampleRate() {\n return this._context.sampleRate;\n }\n /**\n * The listener\n */\n get listener() {\n this.initialize();\n return this._listener;\n }\n set listener(l) {\n assert(!this._initialized, \"The listener cannot be set after initialization.\");\n this._listener = l;\n }\n /**\n * There is only one Transport per Context. It is created on initialization.\n */\n get transport() {\n this.initialize();\n return this._transport;\n }\n set transport(t) {\n assert(!this._initialized, \"The transport cannot be set after initialization.\");\n this._transport = t;\n }\n /**\n * This is the Draw object for the context which is useful for synchronizing the draw frame with the Tone.js clock.\n */\n get draw() {\n this.initialize();\n return this._draw;\n }\n set draw(d) {\n assert(!this._initialized, \"Draw cannot be set after initialization.\");\n this._draw = d;\n }\n /**\n * A reference to the Context's destination node.\n */\n get destination() {\n this.initialize();\n return this._destination;\n }\n set destination(d) {\n assert(!this._initialized, \"The destination cannot be set after initialization.\");\n this._destination = d;\n }\n /**\n * Create an audio worklet node from a name and options. The module\n * must first be loaded using [[addAudioWorkletModule]].\n */\n createAudioWorkletNode(name, options) {\n return createAudioWorkletNode(this.rawContext, name, options);\n }\n /**\n * Add an AudioWorkletProcessor module\n * @param url The url of the module\n * @param name The name of the module\n */\n addAudioWorkletModule(url, name) {\n return __awaiter(this, void 0, void 0, function* () {\n assert(isDefined(this.rawContext.audioWorklet), \"AudioWorkletNode is only available in a secure context (https or localhost)\");\n if (!this._workletModules.has(name)) {\n this._workletModules.set(name, this.rawContext.audioWorklet.addModule(url));\n }\n yield this._workletModules.get(name);\n });\n }\n /**\n * Returns a promise which resolves when all of the worklets have been loaded on this context\n */\n workletsAreReady() {\n return __awaiter(this, void 0, void 0, function* () {\n const promises = [];\n this._workletModules.forEach((promise) => promises.push(promise));\n yield Promise.all(promises);\n });\n }\n //---------------------------\n // TICKER\n //---------------------------\n /**\n * How often the interval callback is invoked.\n * This number corresponds to how responsive the scheduling\n * can be. context.updateInterval + context.lookAhead gives you the\n * total latency between scheduling an event and hearing it.\n */\n get updateInterval() {\n return this._ticker.updateInterval;\n }\n set updateInterval(interval) {\n this._ticker.updateInterval = interval;\n }\n /**\n * What the source of the clock is, either \"worker\" (default),\n * \"timeout\", or \"offline\" (none).\n */\n get clockSource() {\n return this._ticker.type;\n }\n set clockSource(type) {\n this._ticker.type = type;\n }\n /**\n * The type of playback, which affects tradeoffs between audio\n * output latency and responsiveness.\n * In addition to setting the value in seconds, the latencyHint also\n * accepts the strings \"interactive\" (prioritizes low latency),\n * \"playback\" (prioritizes sustained playback), \"balanced\" (balances\n * latency and performance).\n * @example\n * // prioritize sustained playback\n * const context = new Tone.Context({ latencyHint: \"playback\" });\n * // set this context as the global Context\n * Tone.setContext(context);\n * // the global context is gettable with Tone.getContext()\n * console.log(Tone.getContext().latencyHint);\n */\n get latencyHint() {\n return this._latencyHint;\n }\n /**\n * Update the lookAhead and updateInterval based on the latencyHint\n */\n _setLatencyHint(hint) {\n let lookAheadValue = 0;\n this._latencyHint = hint;\n if (isString(hint)) {\n switch (hint) {\n case \"interactive\":\n lookAheadValue = 0.1;\n break;\n case \"playback\":\n lookAheadValue = 0.5;\n break;\n case \"balanced\":\n lookAheadValue = 0.25;\n break;\n }\n }\n this.lookAhead = lookAheadValue;\n this.updateInterval = lookAheadValue / 2;\n }\n /**\n * The unwrapped AudioContext or OfflineAudioContext\n */\n get rawContext() {\n return this._context;\n }\n /**\n * The current audio context time plus a short [[lookAhead]].\n */\n now() {\n return this._context.currentTime + this.lookAhead;\n }\n /**\n * The current audio context time without the [[lookAhead]].\n * In most cases it is better to use [[now]] instead of [[immediate]] since\n * with [[now]] the [[lookAhead]] is applied equally to _all_ components including internal components,\n * to making sure that everything is scheduled in sync. Mixing [[now]] and [[immediate]]\n * can cause some timing issues. If no lookAhead is desired, you can set the [[lookAhead]] to `0`.\n */\n immediate() {\n return this._context.currentTime;\n }\n /**\n * Starts the audio context from a suspended state. This is required\n * to initially start the AudioContext. See [[Tone.start]]\n */\n resume() {\n if (isAudioContext(this._context)) {\n return this._context.resume();\n }\n else {\n return Promise.resolve();\n }\n }\n /**\n * Close the context. Once closed, the context can no longer be used and\n * any AudioNodes created from the context will be silent.\n */\n close() {\n return __awaiter(this, void 0, void 0, function* () {\n if (isAudioContext(this._context)) {\n yield this._context.close();\n }\n if (this._initialized) {\n closeContext(this);\n }\n });\n }\n /**\n * **Internal** Generate a looped buffer at some constant value.\n */\n getConstant(val) {\n if (this._constants.has(val)) {\n return this._constants.get(val);\n }\n else {\n const buffer = this._context.createBuffer(1, 128, this._context.sampleRate);\n const arr = buffer.getChannelData(0);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = val;\n }\n const constant = this._context.createBufferSource();\n constant.channelCount = 1;\n constant.channelCountMode = \"explicit\";\n constant.buffer = buffer;\n constant.loop = true;\n constant.start(0);\n this._constants.set(val, constant);\n return constant;\n }\n }\n /**\n * Clean up. Also closes the audio context.\n */\n dispose() {\n super.dispose();\n this._ticker.dispose();\n this._timeouts.dispose();\n Object.keys(this._constants).map((val) => this._constants[val].disconnect());\n return this;\n }\n //---------------------------\n // TIMEOUTS\n //---------------------------\n /**\n * The private loop which keeps track of the context scheduled timeouts\n * Is invoked from the clock source\n */\n _timeoutLoop() {\n const now = this.now();\n let firstEvent = this._timeouts.peek();\n while (this._timeouts.length && firstEvent && firstEvent.time <= now) {\n // invoke the callback\n firstEvent.callback();\n // shift the first event off\n this._timeouts.shift();\n // get the next one\n firstEvent = this._timeouts.peek();\n }\n }\n /**\n * A setTimeout which is guaranteed by the clock source.\n * Also runs in the offline context.\n * @param fn The callback to invoke\n * @param timeout The timeout in seconds\n * @returns ID to use when invoking Context.clearTimeout\n */\n setTimeout(fn, timeout) {\n this._timeoutIds++;\n const now = this.now();\n this._timeouts.add({\n callback: fn,\n id: this._timeoutIds,\n time: now + timeout,\n });\n return this._timeoutIds;\n }\n /**\n * Clears a previously scheduled timeout with Tone.context.setTimeout\n * @param id The ID returned from setTimeout\n */\n clearTimeout(id) {\n this._timeouts.forEach((event) => {\n if (event.id === id) {\n this._timeouts.remove(event);\n }\n });\n return this;\n }\n /**\n * Clear the function scheduled by [[setInterval]]\n */\n clearInterval(id) {\n return this.clearTimeout(id);\n }\n /**\n * Adds a repeating event to the context's callback clock\n */\n setInterval(fn, interval) {\n const id = ++this._timeoutIds;\n const intervalFn = () => {\n const now = this.now();\n this._timeouts.add({\n callback: () => {\n // invoke the callback\n fn();\n // invoke the event to repeat it\n intervalFn();\n },\n id,\n time: now + interval,\n });\n };\n // kick it off\n intervalFn();\n return id;\n }\n}\n//# sourceMappingURL=Context.js.map","import { __awaiter } from \"tslib\";\nimport { BaseContext } from \"./BaseContext\";\nexport class DummyContext extends BaseContext {\n constructor() {\n super(...arguments);\n this.lookAhead = 0;\n this.latencyHint = 0;\n this.isOffline = false;\n }\n //---------------------------\n // BASE AUDIO CONTEXT METHODS\n //---------------------------\n createAnalyser() {\n return {};\n }\n createOscillator() {\n return {};\n }\n createBufferSource() {\n return {};\n }\n createBiquadFilter() {\n return {};\n }\n createBuffer(_numberOfChannels, _length, _sampleRate) {\n return {};\n }\n createChannelMerger(_numberOfInputs) {\n return {};\n }\n createChannelSplitter(_numberOfOutputs) {\n return {};\n }\n createConstantSource() {\n return {};\n }\n createConvolver() {\n return {};\n }\n createDelay(_maxDelayTime) {\n return {};\n }\n createDynamicsCompressor() {\n return {};\n }\n createGain() {\n return {};\n }\n createIIRFilter(_feedForward, _feedback) {\n return {};\n }\n createPanner() {\n return {};\n }\n createPeriodicWave(_real, _imag, _constraints) {\n return {};\n }\n createStereoPanner() {\n return {};\n }\n createWaveShaper() {\n return {};\n }\n createMediaStreamSource(_stream) {\n return {};\n }\n createMediaElementSource(_element) {\n return {};\n }\n createMediaStreamDestination() {\n return {};\n }\n decodeAudioData(_audioData) {\n return Promise.resolve({});\n }\n //---------------------------\n // TONE AUDIO CONTEXT METHODS\n //---------------------------\n createAudioWorkletNode(_name, _options) {\n return {};\n }\n get rawContext() {\n return {};\n }\n addAudioWorkletModule(_url, _name) {\n return __awaiter(this, void 0, void 0, function* () {\n return Promise.resolve();\n });\n }\n resume() {\n return Promise.resolve();\n }\n setTimeout(_fn, _timeout) {\n return 0;\n }\n clearTimeout(_id) {\n return this;\n }\n setInterval(_fn, _interval) {\n return 0;\n }\n clearInterval(_id) {\n return this;\n }\n getConstant(_val) {\n return {};\n }\n get currentTime() {\n return 0;\n }\n get state() {\n return {};\n }\n get sampleRate() {\n return 0;\n }\n get listener() {\n return {};\n }\n get transport() {\n return {};\n }\n get draw() {\n return {};\n }\n set draw(_d) { }\n get destination() {\n return {};\n }\n set destination(_d) { }\n now() {\n return 0;\n }\n immediate() {\n return 0;\n }\n}\n//# sourceMappingURL=DummyContext.js.map","import { isArray } from \"./TypeCheck\";\n/**\n * Make the property not writable using `defineProperty`. Internal use only.\n */\nexport function readOnly(target, property) {\n if (isArray(property)) {\n property.forEach(str => readOnly(target, str));\n }\n else {\n Object.defineProperty(target, property, {\n enumerable: true,\n writable: false,\n });\n }\n}\n/**\n * Make an attribute writeable. Internal use only.\n */\nexport function writable(target, property) {\n if (isArray(property)) {\n property.forEach(str => writable(target, str));\n }\n else {\n Object.defineProperty(target, property, {\n writable: true,\n });\n }\n}\nexport const noOp = () => {\n // no operation here!\n};\n//# sourceMappingURL=Interface.js.map","import { __awaiter } from \"tslib\";\nimport { getContext } from \"../Global\";\nimport { Tone } from \"../Tone\";\nimport { isAudioBuffer } from \"../util/AdvancedTypeCheck\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { noOp } from \"../util/Interface\";\nimport { isArray, isNumber, isString } from \"../util/TypeCheck\";\nimport { assert } from \"../util/Debug\";\n/**\n * AudioBuffer loading and storage. ToneAudioBuffer is used internally by all\n * classes that make requests for audio files such as Tone.Player,\n * Tone.Sampler and Tone.Convolver.\n * @example\n * const buffer = new Tone.ToneAudioBuffer(\"https://tonejs.github.io/audio/casio/A1.mp3\", () => {\n * \tconsole.log(\"loaded\");\n * });\n * @category Core\n */\nexport class ToneAudioBuffer extends Tone {\n constructor() {\n super();\n this.name = \"ToneAudioBuffer\";\n /**\n * Callback when the buffer is loaded.\n */\n this.onload = noOp;\n const options = optionsFromArguments(ToneAudioBuffer.getDefaults(), arguments, [\"url\", \"onload\", \"onerror\"]);\n this.reverse = options.reverse;\n this.onload = options.onload;\n if (options.url && isAudioBuffer(options.url) || options.url instanceof ToneAudioBuffer) {\n this.set(options.url);\n }\n else if (isString(options.url)) {\n // initiate the download\n this.load(options.url).catch(options.onerror);\n }\n }\n static getDefaults() {\n return {\n onerror: noOp,\n onload: noOp,\n reverse: false,\n };\n }\n /**\n * The sample rate of the AudioBuffer\n */\n get sampleRate() {\n if (this._buffer) {\n return this._buffer.sampleRate;\n }\n else {\n return getContext().sampleRate;\n }\n }\n /**\n * Pass in an AudioBuffer or ToneAudioBuffer to set the value of this buffer.\n */\n set(buffer) {\n if (buffer instanceof ToneAudioBuffer) {\n // if it's loaded, set it\n if (buffer.loaded) {\n this._buffer = buffer.get();\n }\n else {\n // otherwise when it's loaded, invoke it's callback\n buffer.onload = () => {\n this.set(buffer);\n this.onload(this);\n };\n }\n }\n else {\n this._buffer = buffer;\n }\n // reverse it initially\n if (this._reversed) {\n this._reverse();\n }\n return this;\n }\n /**\n * The audio buffer stored in the object.\n */\n get() {\n return this._buffer;\n }\n /**\n * Makes an fetch request for the selected url then decodes the file as an audio buffer.\n * Invokes the callback once the audio buffer loads.\n * @param url The url of the buffer to load. filetype support depends on the browser.\n * @returns A Promise which resolves with this ToneAudioBuffer\n */\n load(url) {\n return __awaiter(this, void 0, void 0, function* () {\n const doneLoading = ToneAudioBuffer.load(url).then(audioBuffer => {\n this.set(audioBuffer);\n // invoke the onload method\n this.onload(this);\n });\n ToneAudioBuffer.downloads.push(doneLoading);\n try {\n yield doneLoading;\n }\n finally {\n // remove the downloaded file\n const index = ToneAudioBuffer.downloads.indexOf(doneLoading);\n ToneAudioBuffer.downloads.splice(index, 1);\n }\n return this;\n });\n }\n /**\n * clean up\n */\n dispose() {\n super.dispose();\n this._buffer = undefined;\n return this;\n }\n /**\n * Set the audio buffer from the array.\n * To create a multichannel AudioBuffer, pass in a multidimensional array.\n * @param array The array to fill the audio buffer\n */\n fromArray(array) {\n const isMultidimensional = isArray(array) && array[0].length > 0;\n const channels = isMultidimensional ? array.length : 1;\n const len = isMultidimensional ? array[0].length : array.length;\n const context = getContext();\n const buffer = context.createBuffer(channels, len, context.sampleRate);\n const multiChannelArray = !isMultidimensional && channels === 1 ?\n [array] : array;\n for (let c = 0; c < channels; c++) {\n buffer.copyToChannel(multiChannelArray[c], c);\n }\n this._buffer = buffer;\n return this;\n }\n /**\n * Sums multiple channels into 1 channel\n * @param chanNum Optionally only copy a single channel from the array.\n */\n toMono(chanNum) {\n if (isNumber(chanNum)) {\n this.fromArray(this.toArray(chanNum));\n }\n else {\n let outputArray = new Float32Array(this.length);\n const numChannels = this.numberOfChannels;\n for (let channel = 0; channel < numChannels; channel++) {\n const channelArray = this.toArray(channel);\n for (let i = 0; i < channelArray.length; i++) {\n outputArray[i] += channelArray[i];\n }\n }\n // divide by the number of channels\n outputArray = outputArray.map(sample => sample / numChannels);\n this.fromArray(outputArray);\n }\n return this;\n }\n /**\n * Get the buffer as an array. Single channel buffers will return a 1-dimensional\n * Float32Array, and multichannel buffers will return multidimensional arrays.\n * @param channel Optionally only copy a single channel from the array.\n */\n toArray(channel) {\n if (isNumber(channel)) {\n return this.getChannelData(channel);\n }\n else if (this.numberOfChannels === 1) {\n return this.toArray(0);\n }\n else {\n const ret = [];\n for (let c = 0; c < this.numberOfChannels; c++) {\n ret[c] = this.getChannelData(c);\n }\n return ret;\n }\n }\n /**\n * Returns the Float32Array representing the PCM audio data for the specific channel.\n * @param channel The channel number to return\n * @return The audio as a TypedArray\n */\n getChannelData(channel) {\n if (this._buffer) {\n return this._buffer.getChannelData(channel);\n }\n else {\n return new Float32Array(0);\n }\n }\n /**\n * Cut a subsection of the array and return a buffer of the\n * subsection. Does not modify the original buffer\n * @param start The time to start the slice\n * @param end The end time to slice. If none is given will default to the end of the buffer\n */\n slice(start, end = this.duration) {\n const startSamples = Math.floor(start * this.sampleRate);\n const endSamples = Math.floor(end * this.sampleRate);\n assert(startSamples < endSamples, \"The start time must be less than the end time\");\n const length = endSamples - startSamples;\n const retBuffer = getContext().createBuffer(this.numberOfChannels, length, this.sampleRate);\n for (let channel = 0; channel < this.numberOfChannels; channel++) {\n retBuffer.copyToChannel(this.getChannelData(channel).subarray(startSamples, endSamples), channel);\n }\n return new ToneAudioBuffer(retBuffer);\n }\n /**\n * Reverse the buffer.\n */\n _reverse() {\n if (this.loaded) {\n for (let i = 0; i < this.numberOfChannels; i++) {\n this.getChannelData(i).reverse();\n }\n }\n return this;\n }\n /**\n * If the buffer is loaded or not\n */\n get loaded() {\n return this.length > 0;\n }\n /**\n * The duration of the buffer in seconds.\n */\n get duration() {\n if (this._buffer) {\n return this._buffer.duration;\n }\n else {\n return 0;\n }\n }\n /**\n * The length of the buffer in samples\n */\n get length() {\n if (this._buffer) {\n return this._buffer.length;\n }\n else {\n return 0;\n }\n }\n /**\n * The number of discrete audio channels. Returns 0 if no buffer is loaded.\n */\n get numberOfChannels() {\n if (this._buffer) {\n return this._buffer.numberOfChannels;\n }\n else {\n return 0;\n }\n }\n /**\n * Reverse the buffer.\n */\n get reverse() {\n return this._reversed;\n }\n set reverse(rev) {\n if (this._reversed !== rev) {\n this._reversed = rev;\n this._reverse();\n }\n }\n /**\n * Create a ToneAudioBuffer from the array. To create a multichannel AudioBuffer,\n * pass in a multidimensional array.\n * @param array The array to fill the audio buffer\n * @return A ToneAudioBuffer created from the array\n */\n static fromArray(array) {\n return (new ToneAudioBuffer()).fromArray(array);\n }\n /**\n * Creates a ToneAudioBuffer from a URL, returns a promise which resolves to a ToneAudioBuffer\n * @param url The url to load.\n * @return A promise which resolves to a ToneAudioBuffer\n */\n static fromUrl(url) {\n return __awaiter(this, void 0, void 0, function* () {\n const buffer = new ToneAudioBuffer();\n return yield buffer.load(url);\n });\n }\n /**\n * Loads a url using fetch and returns the AudioBuffer.\n */\n static load(url) {\n return __awaiter(this, void 0, void 0, function* () {\n // test if the url contains multiple extensions\n const matches = url.match(/\\[([^\\]\\[]+\\|.+)\\]$/);\n if (matches) {\n const extensions = matches[1].split(\"|\");\n let extension = extensions[0];\n for (const ext of extensions) {\n if (ToneAudioBuffer.supportsType(ext)) {\n extension = ext;\n break;\n }\n }\n url = url.replace(matches[0], extension);\n }\n // make sure there is a slash between the baseUrl and the url\n const baseUrl = ToneAudioBuffer.baseUrl === \"\" || ToneAudioBuffer.baseUrl.endsWith(\"/\") ? ToneAudioBuffer.baseUrl : ToneAudioBuffer.baseUrl + \"/\";\n const response = yield fetch(baseUrl + url);\n if (!response.ok) {\n throw new Error(`could not load url: ${url}`);\n }\n const arrayBuffer = yield response.arrayBuffer();\n const audioBuffer = yield getContext().decodeAudioData(arrayBuffer);\n return audioBuffer;\n });\n }\n /**\n * Checks a url's extension to see if the current browser can play that file type.\n * @param url The url/extension to test\n * @return If the file extension can be played\n * @static\n * @example\n * Tone.ToneAudioBuffer.supportsType(\"wav\"); // returns true\n * Tone.ToneAudioBuffer.supportsType(\"path/to/file.wav\"); // returns true\n */\n static supportsType(url) {\n const extensions = url.split(\".\");\n const extension = extensions[extensions.length - 1];\n const response = document.createElement(\"audio\").canPlayType(\"audio/\" + extension);\n return response !== \"\";\n }\n /**\n * Returns a Promise which resolves when all of the buffers have loaded\n */\n static loaded() {\n return __awaiter(this, void 0, void 0, function* () {\n // this makes sure that the function is always async\n yield Promise.resolve();\n while (ToneAudioBuffer.downloads.length) {\n yield ToneAudioBuffer.downloads[0];\n }\n });\n }\n}\n//-------------------------------------\n// STATIC METHODS\n//-------------------------------------\n/**\n * A path which is prefixed before every url.\n */\nToneAudioBuffer.baseUrl = \"\";\n/**\n * All of the downloads\n */\nToneAudioBuffer.downloads = [];\n//# sourceMappingURL=ToneAudioBuffer.js.map","import { __awaiter } from \"tslib\";\nimport { createOfflineAudioContext } from \"../context/AudioContext\";\nimport { Context } from \"../context/Context\";\nimport { isOfflineAudioContext } from \"../util/AdvancedTypeCheck\";\nimport { ToneAudioBuffer } from \"./ToneAudioBuffer\";\n/**\n * Wrapper around the OfflineAudioContext\n * @category Core\n * @example\n * // generate a single channel, 0.5 second buffer\n * const context = new Tone.OfflineContext(1, 0.5, 44100);\n * const osc = new Tone.Oscillator({ context });\n * context.render().then(buffer => {\n * \tconsole.log(buffer.numberOfChannels, buffer.duration);\n * });\n */\nexport class OfflineContext extends Context {\n constructor() {\n super({\n clockSource: \"offline\",\n context: isOfflineAudioContext(arguments[0]) ?\n arguments[0] : createOfflineAudioContext(arguments[0], arguments[1] * arguments[2], arguments[2]),\n lookAhead: 0,\n updateInterval: isOfflineAudioContext(arguments[0]) ?\n 128 / arguments[0].sampleRate : 128 / arguments[2],\n });\n this.name = \"OfflineContext\";\n /**\n * An artificial clock source\n */\n this._currentTime = 0;\n this.isOffline = true;\n this._duration = isOfflineAudioContext(arguments[0]) ?\n arguments[0].length / arguments[0].sampleRate : arguments[1];\n }\n /**\n * Override the now method to point to the internal clock time\n */\n now() {\n return this._currentTime;\n }\n /**\n * Same as this.now()\n */\n get currentTime() {\n return this._currentTime;\n }\n /**\n * Render just the clock portion of the audio context.\n */\n _renderClock(asynchronous) {\n return __awaiter(this, void 0, void 0, function* () {\n let index = 0;\n while (this._duration - this._currentTime >= 0) {\n // invoke all the callbacks on that time\n this.emit(\"tick\");\n // increment the clock in block-sized chunks\n this._currentTime += 128 / this.sampleRate;\n // yield once a second of audio\n index++;\n const yieldEvery = Math.floor(this.sampleRate / 128);\n if (asynchronous && index % yieldEvery === 0) {\n yield new Promise(done => setTimeout(done, 1));\n }\n }\n });\n }\n /**\n * Render the output of the OfflineContext\n * @param asynchronous If the clock should be rendered asynchronously, which will not block the main thread, but be slightly slower.\n */\n render(asynchronous = true) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.workletsAreReady();\n yield this._renderClock(asynchronous);\n const buffer = yield this._context.startRendering();\n return new ToneAudioBuffer(buffer);\n });\n }\n /**\n * Close the context\n */\n close() {\n return Promise.resolve();\n }\n}\n//# sourceMappingURL=OfflineContext.js.map","import { version } from \"../version\";\nimport { hasAudioContext, theWindow } from \"./context/AudioContext\";\nimport { Context } from \"./context/Context\";\nimport { DummyContext } from \"./context/DummyContext\";\nimport { OfflineContext } from \"./context/OfflineContext\";\nimport { isAudioContext, isOfflineAudioContext } from \"./util/AdvancedTypeCheck\";\n/**\n * This dummy context is used to avoid throwing immediate errors when importing in Node.js\n */\nconst dummyContext = new DummyContext();\n/**\n * The global audio context which is getable and assignable through\n * getContext and setContext\n */\nlet globalContext = dummyContext;\n/**\n * Returns the default system-wide [[Context]]\n * @category Core\n */\nexport function getContext() {\n if (globalContext === dummyContext && hasAudioContext) {\n setContext(new Context());\n }\n return globalContext;\n}\n/**\n * Set the default audio context\n * @category Core\n */\nexport function setContext(context) {\n if (isAudioContext(context)) {\n globalContext = new Context(context);\n }\n else if (isOfflineAudioContext(context)) {\n globalContext = new OfflineContext(context);\n }\n else {\n globalContext = context;\n }\n}\n/**\n * Most browsers will not play _any_ audio until a user\n * clicks something (like a play button). Invoke this method\n * on a click or keypress event handler to start the audio context.\n * More about the Autoplay policy\n * [here](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio)\n * @example\n * document.querySelector(\"button\").addEventListener(\"click\", async () => {\n * \tawait Tone.start();\n * \tconsole.log(\"context started\");\n * });\n * @category Core\n */\nexport function start() {\n return globalContext.resume();\n}\n/**\n * Log Tone.js + version in the console.\n */\nif (theWindow && !theWindow.TONE_SILENCE_LOGGING) {\n let prefix = \"v\";\n if (version === \"dev\") {\n prefix = \"\";\n }\n const printString = ` * Tone.js ${prefix}${version} * `;\n // eslint-disable-next-line no-console\n console.log(`%c${printString}`, \"background: #000; color: #fff\");\n}\n//# sourceMappingURL=Global.js.map","/**\n * Equal power gain scale. Good for cross-fading.\n * @param percent (0-1)\n */\nexport function equalPowerScale(percent) {\n const piFactor = 0.5 * Math.PI;\n return Math.sin(percent * piFactor);\n}\n/**\n * Convert decibels into gain.\n */\nexport function dbToGain(db) {\n return Math.pow(10, db / 20);\n}\n/**\n * Convert gain to decibels.\n */\nexport function gainToDb(gain) {\n return 20 * (Math.log(gain) / Math.LN10);\n}\n/**\n * Convert an interval (in semitones) to a frequency ratio.\n * @param interval the number of semitones above the base note\n * @example\n * Tone.intervalToFrequencyRatio(0); // 1\n * Tone.intervalToFrequencyRatio(12); // 2\n * Tone.intervalToFrequencyRatio(-12); // 0.5\n */\nexport function intervalToFrequencyRatio(interval) {\n return Math.pow(2, (interval / 12));\n}\n/**\n * The Global [concert tuning pitch](https://en.wikipedia.org/wiki/Concert_pitch) which is used\n * to generate all the other pitch values from notes. A4's values in Hertz.\n */\nlet A4 = 440;\nexport function getA4() {\n return A4;\n}\nexport function setA4(freq) {\n A4 = freq;\n}\n/**\n * Convert a frequency value to a MIDI note.\n * @param frequency The value to frequency value to convert.\n * @example\n * Tone.ftom(440); // returns 69\n */\nexport function ftom(frequency) {\n return Math.round(ftomf(frequency));\n}\n/**\n * Convert a frequency to a floating point midi value\n */\nexport function ftomf(frequency) {\n return 69 + 12 * Math.log2(frequency / A4);\n}\n/**\n * Convert a MIDI note to frequency value.\n * @param midi The midi number to convert.\n * @return The corresponding frequency value\n * @example\n * Tone.mtof(69); // 440\n */\nexport function mtof(midi) {\n return A4 * Math.pow(2, (midi - 69) / 12);\n}\n//# sourceMappingURL=Conversions.js.map","import { Tone } from \"../Tone\";\nimport { isDefined, isObject, isString, isUndef } from \"../util/TypeCheck\";\n/**\n * TimeBase is a flexible encoding of time which can be evaluated to and from a string.\n */\nexport class TimeBaseClass extends Tone {\n /**\n * @param context The context associated with the time value. Used to compute\n * Transport and context-relative timing.\n * @param value The time value as a number, string or object\n * @param units Unit values\n */\n constructor(context, value, units) {\n super();\n /**\n * The default units\n */\n this.defaultUnits = \"s\";\n this._val = value;\n this._units = units;\n this.context = context;\n this._expressions = this._getExpressions();\n }\n /**\n * All of the time encoding expressions\n */\n _getExpressions() {\n return {\n hz: {\n method: (value) => {\n return this._frequencyToUnits(parseFloat(value));\n },\n regexp: /^(\\d+(?:\\.\\d+)?)hz$/i,\n },\n i: {\n method: (value) => {\n return this._ticksToUnits(parseInt(value, 10));\n },\n regexp: /^(\\d+)i$/i,\n },\n m: {\n method: (value) => {\n return this._beatsToUnits(parseInt(value, 10) * this._getTimeSignature());\n },\n regexp: /^(\\d+)m$/i,\n },\n n: {\n method: (value, dot) => {\n const numericValue = parseInt(value, 10);\n const scalar = dot === \".\" ? 1.5 : 1;\n if (numericValue === 1) {\n return this._beatsToUnits(this._getTimeSignature()) * scalar;\n }\n else {\n return this._beatsToUnits(4 / numericValue) * scalar;\n }\n },\n regexp: /^(\\d+)n(\\.?)$/i,\n },\n number: {\n method: (value) => {\n return this._expressions[this.defaultUnits].method.call(this, value);\n },\n regexp: /^(\\d+(?:\\.\\d+)?)$/,\n },\n s: {\n method: (value) => {\n return this._secondsToUnits(parseFloat(value));\n },\n regexp: /^(\\d+(?:\\.\\d+)?)s$/,\n },\n samples: {\n method: (value) => {\n return parseInt(value, 10) / this.context.sampleRate;\n },\n regexp: /^(\\d+)samples$/,\n },\n t: {\n method: (value) => {\n const numericValue = parseInt(value, 10);\n return this._beatsToUnits(8 / (Math.floor(numericValue) * 3));\n },\n regexp: /^(\\d+)t$/i,\n },\n tr: {\n method: (m, q, s) => {\n let total = 0;\n if (m && m !== \"0\") {\n total += this._beatsToUnits(this._getTimeSignature() * parseFloat(m));\n }\n if (q && q !== \"0\") {\n total += this._beatsToUnits(parseFloat(q));\n }\n if (s && s !== \"0\") {\n total += this._beatsToUnits(parseFloat(s) / 4);\n }\n return total;\n },\n regexp: /^(\\d+(?:\\.\\d+)?):(\\d+(?:\\.\\d+)?):?(\\d+(?:\\.\\d+)?)?$/,\n },\n };\n }\n //-------------------------------------\n // \tVALUE OF\n //-------------------------------------\n /**\n * Evaluate the time value. Returns the time in seconds.\n */\n valueOf() {\n if (this._val instanceof TimeBaseClass) {\n this.fromType(this._val);\n }\n if (isUndef(this._val)) {\n return this._noArg();\n }\n else if (isString(this._val) && isUndef(this._units)) {\n for (const units in this._expressions) {\n if (this._expressions[units].regexp.test(this._val.trim())) {\n this._units = units;\n break;\n }\n }\n }\n else if (isObject(this._val)) {\n let total = 0;\n for (const typeName in this._val) {\n if (isDefined(this._val[typeName])) {\n const quantity = this._val[typeName];\n // @ts-ignore\n const time = (new this.constructor(this.context, typeName)).valueOf() * quantity;\n total += time;\n }\n }\n return total;\n }\n if (isDefined(this._units)) {\n const expr = this._expressions[this._units];\n const matching = this._val.toString().trim().match(expr.regexp);\n if (matching) {\n return expr.method.apply(this, matching.slice(1));\n }\n else {\n return expr.method.call(this, this._val);\n }\n }\n else if (isString(this._val)) {\n return parseFloat(this._val);\n }\n else {\n return this._val;\n }\n }\n //-------------------------------------\n // \tUNIT CONVERSIONS\n //-------------------------------------\n /**\n * Returns the value of a frequency in the current units\n */\n _frequencyToUnits(freq) {\n return 1 / freq;\n }\n /**\n * Return the value of the beats in the current units\n */\n _beatsToUnits(beats) {\n return (60 / this._getBpm()) * beats;\n }\n /**\n * Returns the value of a second in the current units\n */\n _secondsToUnits(seconds) {\n return seconds;\n }\n /**\n * Returns the value of a tick in the current time units\n */\n _ticksToUnits(ticks) {\n return (ticks * (this._beatsToUnits(1)) / this._getPPQ());\n }\n /**\n * With no arguments, return 'now'\n */\n _noArg() {\n return this._now();\n }\n //-------------------------------------\n // \tTEMPO CONVERSIONS\n //-------------------------------------\n /**\n * Return the bpm\n */\n _getBpm() {\n return this.context.transport.bpm.value;\n }\n /**\n * Return the timeSignature\n */\n _getTimeSignature() {\n return this.context.transport.timeSignature;\n }\n /**\n * Return the PPQ or 192 if Transport is not available\n */\n _getPPQ() {\n return this.context.transport.PPQ;\n }\n //-------------------------------------\n // \tCONVERSION INTERFACE\n //-------------------------------------\n /**\n * Coerce a time type into this units type.\n * @param type Any time type units\n */\n fromType(type) {\n this._units = undefined;\n switch (this.defaultUnits) {\n case \"s\":\n this._val = type.toSeconds();\n break;\n case \"i\":\n this._val = type.toTicks();\n break;\n case \"hz\":\n this._val = type.toFrequency();\n break;\n case \"midi\":\n this._val = type.toMidi();\n break;\n }\n return this;\n }\n /**\n * Return the value in hertz\n */\n toFrequency() {\n return 1 / this.toSeconds();\n }\n /**\n * Return the time in samples\n */\n toSamples() {\n return this.toSeconds() * this.context.sampleRate;\n }\n /**\n * Return the time in milliseconds.\n */\n toMilliseconds() {\n return this.toSeconds() * 1000;\n }\n}\n//# sourceMappingURL=TimeBase.js.map","import { getContext } from \"../Global\";\nimport { ftom } from \"./Conversions\";\nimport { TimeBaseClass } from \"./TimeBase\";\n/**\n * TimeClass is a primitive type for encoding and decoding Time values.\n * TimeClass can be passed into the parameter of any method which takes time as an argument.\n * @param val The time value.\n * @param units The units of the value.\n * @example\n * const time = Tone.Time(\"4n\"); // a quarter note\n * @category Unit\n */\nexport class TimeClass extends TimeBaseClass {\n constructor() {\n super(...arguments);\n this.name = \"TimeClass\";\n }\n _getExpressions() {\n return Object.assign(super._getExpressions(), {\n now: {\n method: (capture) => {\n return this._now() + new this.constructor(this.context, capture).valueOf();\n },\n regexp: /^\\+(.+)/,\n },\n quantize: {\n method: (capture) => {\n const quantTo = new TimeClass(this.context, capture).valueOf();\n return this._secondsToUnits(this.context.transport.nextSubdivision(quantTo));\n },\n regexp: /^@(.+)/,\n },\n });\n }\n /**\n * Quantize the time by the given subdivision. Optionally add a\n * percentage which will move the time value towards the ideal\n * quantized value by that percentage.\n * @param subdiv The subdivision to quantize to\n * @param percent Move the time value towards the quantized value by a percentage.\n * @example\n * Tone.Time(21).quantize(2); // returns 22\n * Tone.Time(0.6).quantize(\"4n\", 0.5); // returns 0.55\n */\n quantize(subdiv, percent = 1) {\n const subdivision = new this.constructor(this.context, subdiv).valueOf();\n const value = this.valueOf();\n const multiple = Math.round(value / subdivision);\n const ideal = multiple * subdivision;\n const diff = ideal - value;\n return value + diff * percent;\n }\n //-------------------------------------\n // CONVERSIONS\n //-------------------------------------\n /**\n * Convert a Time to Notation. The notation values are will be the\n * closest representation between 1m to 128th note.\n * @return {Notation}\n * @example\n * // if the Transport is at 120bpm:\n * Tone.Time(2).toNotation(); // returns \"1m\"\n */\n toNotation() {\n const time = this.toSeconds();\n const testNotations = [\"1m\"];\n for (let power = 1; power < 9; power++) {\n const subdiv = Math.pow(2, power);\n testNotations.push(subdiv + \"n.\");\n testNotations.push(subdiv + \"n\");\n testNotations.push(subdiv + \"t\");\n }\n testNotations.push(\"0\");\n // find the closets notation representation\n let closest = testNotations[0];\n let closestSeconds = new TimeClass(this.context, testNotations[0]).toSeconds();\n testNotations.forEach(notation => {\n const notationSeconds = new TimeClass(this.context, notation).toSeconds();\n if (Math.abs(notationSeconds - time) < Math.abs(closestSeconds - time)) {\n closest = notation;\n closestSeconds = notationSeconds;\n }\n });\n return closest;\n }\n /**\n * Return the time encoded as Bars:Beats:Sixteenths.\n */\n toBarsBeatsSixteenths() {\n const quarterTime = this._beatsToUnits(1);\n let quarters = this.valueOf() / quarterTime;\n quarters = parseFloat(quarters.toFixed(4));\n const measures = Math.floor(quarters / this._getTimeSignature());\n let sixteenths = (quarters % 1) * 4;\n quarters = Math.floor(quarters) % this._getTimeSignature();\n const sixteenthString = sixteenths.toString();\n if (sixteenthString.length > 3) {\n // the additional parseFloat removes insignificant trailing zeroes\n sixteenths = parseFloat(parseFloat(sixteenthString).toFixed(3));\n }\n const progress = [measures, quarters, sixteenths];\n return progress.join(\":\");\n }\n /**\n * Return the time in ticks.\n */\n toTicks() {\n const quarterTime = this._beatsToUnits(1);\n const quarters = this.valueOf() / quarterTime;\n return Math.round(quarters * this._getPPQ());\n }\n /**\n * Return the time in seconds.\n */\n toSeconds() {\n return this.valueOf();\n }\n /**\n * Return the value as a midi note.\n */\n toMidi() {\n return ftom(this.toFrequency());\n }\n _now() {\n return this.context.now();\n }\n}\n/**\n * Create a TimeClass from a time string or number. The time is computed against the\n * global Tone.Context. To use a specific context, use [[TimeClass]]\n * @param value A value which represents time\n * @param units The value's units if they can't be inferred by the value.\n * @category Unit\n * @example\n * const time = Tone.Time(\"4n\").toSeconds();\n * console.log(time);\n * @example\n * const note = Tone.Time(1).toNotation();\n * console.log(note);\n * @example\n * const freq = Tone.Time(0.5).toFrequency();\n * console.log(freq);\n */\nexport function Time(value, units) {\n return new TimeClass(getContext(), value, units);\n}\n//# sourceMappingURL=Time.js.map","import { getContext } from \"../Global\";\nimport { intervalToFrequencyRatio, mtof } from \"./Conversions\";\nimport { ftom, getA4, setA4 } from \"./Conversions\";\nimport { TimeClass } from \"./Time\";\n/**\n * Frequency is a primitive type for encoding Frequency values.\n * Eventually all time values are evaluated to hertz using the `valueOf` method.\n * @example\n * Tone.Frequency(\"C3\"); // 261\n * Tone.Frequency(38, \"midi\");\n * Tone.Frequency(\"C3\").transpose(4);\n * @category Unit\n */\nexport class FrequencyClass extends TimeClass {\n constructor() {\n super(...arguments);\n this.name = \"Frequency\";\n this.defaultUnits = \"hz\";\n }\n /**\n * The [concert tuning pitch](https://en.wikipedia.org/wiki/Concert_pitch) which is used\n * to generate all the other pitch values from notes. A4's values in Hertz.\n */\n static get A4() {\n return getA4();\n }\n static set A4(freq) {\n setA4(freq);\n }\n //-------------------------------------\n // \tAUGMENT BASE EXPRESSIONS\n //-------------------------------------\n _getExpressions() {\n return Object.assign({}, super._getExpressions(), {\n midi: {\n regexp: /^(\\d+(?:\\.\\d+)?midi)/,\n method(value) {\n if (this.defaultUnits === \"midi\") {\n return value;\n }\n else {\n return FrequencyClass.mtof(value);\n }\n },\n },\n note: {\n regexp: /^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,\n method(pitch, octave) {\n const index = noteToScaleIndex[pitch.toLowerCase()];\n const noteNumber = index + (parseInt(octave, 10) + 1) * 12;\n if (this.defaultUnits === \"midi\") {\n return noteNumber;\n }\n else {\n return FrequencyClass.mtof(noteNumber);\n }\n },\n },\n tr: {\n regexp: /^(\\d+(?:\\.\\d+)?):(\\d+(?:\\.\\d+)?):?(\\d+(?:\\.\\d+)?)?/,\n method(m, q, s) {\n let total = 1;\n if (m && m !== \"0\") {\n total *= this._beatsToUnits(this._getTimeSignature() * parseFloat(m));\n }\n if (q && q !== \"0\") {\n total *= this._beatsToUnits(parseFloat(q));\n }\n if (s && s !== \"0\") {\n total *= this._beatsToUnits(parseFloat(s) / 4);\n }\n return total;\n },\n },\n });\n }\n //-------------------------------------\n // \tEXPRESSIONS\n //-------------------------------------\n /**\n * Transposes the frequency by the given number of semitones.\n * @return A new transposed frequency\n * @example\n * Tone.Frequency(\"A4\").transpose(3); // \"C5\"\n */\n transpose(interval) {\n return new FrequencyClass(this.context, this.valueOf() * intervalToFrequencyRatio(interval));\n }\n /**\n * Takes an array of semitone intervals and returns\n * an array of frequencies transposed by those intervals.\n * @return Returns an array of Frequencies\n * @example\n * Tone.Frequency(\"A4\").harmonize([0, 3, 7]); // [\"A4\", \"C5\", \"E5\"]\n */\n harmonize(intervals) {\n return intervals.map(interval => {\n return this.transpose(interval);\n });\n }\n //-------------------------------------\n // \tUNIT CONVERSIONS\n //-------------------------------------\n /**\n * Return the value of the frequency as a MIDI note\n * @example\n * Tone.Frequency(\"C4\").toMidi(); // 60\n */\n toMidi() {\n return ftom(this.valueOf());\n }\n /**\n * Return the value of the frequency in Scientific Pitch Notation\n * @example\n * Tone.Frequency(69, \"midi\").toNote(); // \"A4\"\n */\n toNote() {\n const freq = this.toFrequency();\n const log = Math.log2(freq / FrequencyClass.A4);\n let noteNumber = Math.round(12 * log) + 57;\n const octave = Math.floor(noteNumber / 12);\n if (octave < 0) {\n noteNumber += -12 * octave;\n }\n const noteName = scaleIndexToNote[noteNumber % 12];\n return noteName + octave.toString();\n }\n /**\n * Return the duration of one cycle in seconds.\n */\n toSeconds() {\n return 1 / super.toSeconds();\n }\n /**\n * Return the duration of one cycle in ticks\n */\n toTicks() {\n const quarterTime = this._beatsToUnits(1);\n const quarters = this.valueOf() / quarterTime;\n return Math.floor(quarters * this._getPPQ());\n }\n //-------------------------------------\n // \tUNIT CONVERSIONS HELPERS\n //-------------------------------------\n /**\n * With no arguments, return 0\n */\n _noArg() {\n return 0;\n }\n /**\n * Returns the value of a frequency in the current units\n */\n _frequencyToUnits(freq) {\n return freq;\n }\n /**\n * Returns the value of a tick in the current time units\n */\n _ticksToUnits(ticks) {\n return 1 / ((ticks * 60) / (this._getBpm() * this._getPPQ()));\n }\n /**\n * Return the value of the beats in the current units\n */\n _beatsToUnits(beats) {\n return 1 / super._beatsToUnits(beats);\n }\n /**\n * Returns the value of a second in the current units\n */\n _secondsToUnits(seconds) {\n return 1 / seconds;\n }\n /**\n * Convert a MIDI note to frequency value.\n * @param midi The midi number to convert.\n * @return The corresponding frequency value\n */\n static mtof(midi) {\n return mtof(midi);\n }\n /**\n * Convert a frequency value to a MIDI note.\n * @param frequency The value to frequency value to convert.\n */\n static ftom(frequency) {\n return ftom(frequency);\n }\n}\n//-------------------------------------\n// \tFREQUENCY CONVERSIONS\n//-------------------------------------\n/**\n * Note to scale index.\n * @hidden\n */\nconst noteToScaleIndex = {\n cbb: -2, cb: -1, c: 0, \"c#\": 1, cx: 2,\n dbb: 0, db: 1, d: 2, \"d#\": 3, dx: 4,\n ebb: 2, eb: 3, e: 4, \"e#\": 5, ex: 6,\n fbb: 3, fb: 4, f: 5, \"f#\": 6, fx: 7,\n gbb: 5, gb: 6, g: 7, \"g#\": 8, gx: 9,\n abb: 7, ab: 8, a: 9, \"a#\": 10, ax: 11,\n bbb: 9, bb: 10, b: 11, \"b#\": 12, bx: 13,\n};\n/**\n * scale index to note (sharps)\n * @hidden\n */\nconst scaleIndexToNote = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/**\n * Convert a value into a FrequencyClass object.\n * @category Unit\n * @example\n * const midi = Tone.Frequency(\"C3\").toMidi();\n * console.log(midi);\n * @example\n * const hertz = Tone.Frequency(38, \"midi\").toFrequency();\n * console.log(hertz);\n */\nexport function Frequency(value, units) {\n return new FrequencyClass(getContext(), value, units);\n}\n//# sourceMappingURL=Frequency.js.map","import { getContext } from \"../Global\";\nimport { TimeClass } from \"./Time\";\n/**\n * TransportTime is a the time along the Transport's\n * timeline. It is similar to Tone.Time, but instead of evaluating\n * against the AudioContext's clock, it is evaluated against\n * the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime).\n * @category Unit\n */\nexport class TransportTimeClass extends TimeClass {\n constructor() {\n super(...arguments);\n this.name = \"TransportTime\";\n }\n /**\n * Return the current time in whichever context is relevant\n */\n _now() {\n return this.context.transport.seconds;\n }\n}\n/**\n * TransportTime is a the time along the Transport's\n * timeline. It is similar to [[Time]], but instead of evaluating\n * against the AudioContext's clock, it is evaluated against\n * the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime).\n * @category Unit\n */\nexport function TransportTime(value, units) {\n return new TransportTimeClass(getContext(), value, units);\n}\n//# sourceMappingURL=TransportTime.js.map","import { getContext } from \"../Global\";\nimport { Tone } from \"../Tone\";\nimport { FrequencyClass } from \"../type/Frequency\";\nimport { TimeClass } from \"../type/Time\";\nimport { TransportTimeClass } from \"../type/TransportTime\";\nimport { getDefaultsFromInstance, optionsFromArguments } from \"../util/Defaults\";\nimport { isArray, isBoolean, isDefined, isNumber, isString, isUndef } from \"../util/TypeCheck\";\n/**\n * The Base class for all nodes that have an AudioContext.\n */\nexport class ToneWithContext extends Tone {\n constructor() {\n super();\n const options = optionsFromArguments(ToneWithContext.getDefaults(), arguments, [\"context\"]);\n if (this.defaultContext) {\n this.context = this.defaultContext;\n }\n else {\n this.context = options.context;\n }\n }\n static getDefaults() {\n return {\n context: getContext(),\n };\n }\n /**\n * Return the current time of the Context clock plus the lookAhead.\n * @example\n * setInterval(() => {\n * \tconsole.log(Tone.now());\n * }, 100);\n */\n now() {\n return this.context.currentTime + this.context.lookAhead;\n }\n /**\n * Return the current time of the Context clock without any lookAhead.\n * @example\n * setInterval(() => {\n * \tconsole.log(Tone.immediate());\n * }, 100);\n */\n immediate() {\n return this.context.currentTime;\n }\n /**\n * The duration in seconds of one sample.\n * @example\n * console.log(Tone.Transport.sampleTime);\n */\n get sampleTime() {\n return 1 / this.context.sampleRate;\n }\n /**\n * The number of seconds of 1 processing block (128 samples)\n * @example\n * console.log(Tone.Destination.blockTime);\n */\n get blockTime() {\n return 128 / this.context.sampleRate;\n }\n /**\n * Convert the incoming time to seconds.\n * This is calculated against the current [[Tone.Transport]] bpm\n * @example\n * const gain = new Tone.Gain();\n * setInterval(() => console.log(gain.toSeconds(\"4n\")), 100);\n * // ramp the tempo to 60 bpm over 30 seconds\n * Tone.getTransport().bpm.rampTo(60, 30);\n */\n toSeconds(time) {\n return new TimeClass(this.context, time).toSeconds();\n }\n /**\n * Convert the input to a frequency number\n * @example\n * const gain = new Tone.Gain();\n * console.log(gain.toFrequency(\"4n\"));\n */\n toFrequency(freq) {\n return new FrequencyClass(this.context, freq).toFrequency();\n }\n /**\n * Convert the input time into ticks\n * @example\n * const gain = new Tone.Gain();\n * console.log(gain.toTicks(\"4n\"));\n */\n toTicks(time) {\n return new TransportTimeClass(this.context, time).toTicks();\n }\n //-------------------------------------\n // \tGET/SET\n //-------------------------------------\n /**\n * Get a subset of the properties which are in the partial props\n */\n _getPartialProperties(props) {\n const options = this.get();\n // remove attributes from the prop that are not in the partial\n Object.keys(options).forEach(name => {\n if (isUndef(props[name])) {\n delete options[name];\n }\n });\n return options;\n }\n /**\n * Get the object's attributes.\n * @example\n * const osc = new Tone.Oscillator();\n * console.log(osc.get());\n */\n get() {\n const defaults = getDefaultsFromInstance(this);\n Object.keys(defaults).forEach(attribute => {\n if (Reflect.has(this, attribute)) {\n const member = this[attribute];\n if (isDefined(member) && isDefined(member.value) && isDefined(member.setValueAtTime)) {\n defaults[attribute] = member.value;\n }\n else if (member instanceof ToneWithContext) {\n defaults[attribute] = member._getPartialProperties(defaults[attribute]);\n // otherwise make sure it's a serializable type\n }\n else if (isArray(member) || isNumber(member) || isString(member) || isBoolean(member)) {\n defaults[attribute] = member;\n }\n else {\n // remove all undefined and unserializable attributes\n delete defaults[attribute];\n }\n }\n });\n return defaults;\n }\n /**\n * Set multiple properties at once with an object.\n * @example\n * const filter = new Tone.Filter().toDestination();\n * // set values using an object\n * filter.set({\n * \tfrequency: \"C6\",\n * \ttype: \"highpass\"\n * });\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/Analogsynth_octaves_highmid.mp3\").connect(filter);\n * player.autostart = true;\n */\n set(props) {\n Object.keys(props).forEach(attribute => {\n if (Reflect.has(this, attribute) && isDefined(this[attribute])) {\n if (this[attribute] && isDefined(this[attribute].value) && isDefined(this[attribute].setValueAtTime)) {\n // small optimization\n if (this[attribute].value !== props[attribute]) {\n this[attribute].value = props[attribute];\n }\n }\n else if (this[attribute] instanceof ToneWithContext) {\n this[attribute].set(props[attribute]);\n }\n else {\n this[attribute] = props[attribute];\n }\n }\n });\n return this;\n }\n}\n//# sourceMappingURL=ToneWithContext.js.map","import { Timeline } from \"./Timeline\";\nimport { assertRange } from \"./Debug\";\n/**\n * A Timeline State. Provides the methods: `setStateAtTime(\"state\", time)` and `getValueAtTime(time)`\n * @param initial The initial state of the StateTimeline. Defaults to `undefined`\n */\nexport class StateTimeline extends Timeline {\n constructor(initial = \"stopped\") {\n super();\n this.name = \"StateTimeline\";\n this._initial = initial;\n this.setStateAtTime(this._initial, 0);\n }\n /**\n * Returns the scheduled state scheduled before or at\n * the given time.\n * @param time The time to query.\n * @return The name of the state input in setStateAtTime.\n */\n getValueAtTime(time) {\n const event = this.get(time);\n if (event !== null) {\n return event.state;\n }\n else {\n return this._initial;\n }\n }\n /**\n * Add a state to the timeline.\n * @param state The name of the state to set.\n * @param time The time to query.\n * @param options Any additional options that are needed in the timeline.\n */\n setStateAtTime(state, time, options) {\n assertRange(time, 0);\n this.add(Object.assign({}, options, {\n state,\n time,\n }));\n return this;\n }\n /**\n * Return the event before the time with the given state\n * @param state The state to look for\n * @param time When to check before\n * @return The event with the given state before the time\n */\n getLastState(state, time) {\n // time = this.toSeconds(time);\n const index = this._search(time);\n for (let i = index; i >= 0; i--) {\n const event = this._timeline[i];\n if (event.state === state) {\n return event;\n }\n }\n }\n /**\n * Return the event after the time with the given state\n * @param state The state to look for\n * @param time When to check from\n * @return The event with the given state after the time\n */\n getNextState(state, time) {\n // time = this.toSeconds(time);\n const index = this._search(time);\n if (index !== -1) {\n for (let i = index; i < this._timeline.length; i++) {\n const event = this._timeline[i];\n if (event.state === state) {\n return event;\n }\n }\n }\n }\n}\n//# sourceMappingURL=StateTimeline.js.map","import { dbToGain, gainToDb } from \"../type/Conversions\";\nimport { isAudioParam } from \"../util/AdvancedTypeCheck\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { Timeline } from \"../util/Timeline\";\nimport { isDefined } from \"../util/TypeCheck\";\nimport { ToneWithContext } from \"./ToneWithContext\";\nimport { EQ } from \"../util/Math\";\nimport { assert, assertRange } from \"../util/Debug\";\n/**\n * Param wraps the native Web Audio's AudioParam to provide\n * additional unit conversion functionality. It also\n * serves as a base-class for classes which have a single,\n * automatable parameter.\n * @category Core\n */\nexport class Param extends ToneWithContext {\n constructor() {\n super(optionsFromArguments(Param.getDefaults(), arguments, [\"param\", \"units\", \"convert\"]));\n this.name = \"Param\";\n this.overridden = false;\n /**\n * The minimum output value\n */\n this._minOutput = 1e-7;\n const options = optionsFromArguments(Param.getDefaults(), arguments, [\"param\", \"units\", \"convert\"]);\n assert(isDefined(options.param) &&\n (isAudioParam(options.param) || options.param instanceof Param), \"param must be an AudioParam\");\n while (!isAudioParam(options.param)) {\n options.param = options.param._param;\n }\n this._swappable = isDefined(options.swappable) ? options.swappable : false;\n if (this._swappable) {\n this.input = this.context.createGain();\n // initialize\n this._param = options.param;\n this.input.connect(this._param);\n }\n else {\n this._param = this.input = options.param;\n }\n this._events = new Timeline(1000);\n this._initialValue = this._param.defaultValue;\n this.units = options.units;\n this.convert = options.convert;\n this._minValue = options.minValue;\n this._maxValue = options.maxValue;\n // if the value is defined, set it immediately\n if (isDefined(options.value) && options.value !== this._toType(this._initialValue)) {\n this.setValueAtTime(options.value, 0);\n }\n }\n static getDefaults() {\n return Object.assign(ToneWithContext.getDefaults(), {\n convert: true,\n units: \"number\",\n });\n }\n get value() {\n const now = this.now();\n return this.getValueAtTime(now);\n }\n set value(value) {\n this.cancelScheduledValues(this.now());\n this.setValueAtTime(value, this.now());\n }\n get minValue() {\n // if it's not the default minValue, return it\n if (isDefined(this._minValue)) {\n return this._minValue;\n }\n else if (this.units === \"time\" || this.units === \"frequency\" ||\n this.units === \"normalRange\" || this.units === \"positive\" ||\n this.units === \"transportTime\" || this.units === \"ticks\" ||\n this.units === \"bpm\" || this.units === \"hertz\" || this.units === \"samples\") {\n return 0;\n }\n else if (this.units === \"audioRange\") {\n return -1;\n }\n else if (this.units === \"decibels\") {\n return -Infinity;\n }\n else {\n return this._param.minValue;\n }\n }\n get maxValue() {\n if (isDefined(this._maxValue)) {\n return this._maxValue;\n }\n else if (this.units === \"normalRange\" ||\n this.units === \"audioRange\") {\n return 1;\n }\n else {\n return this._param.maxValue;\n }\n }\n /**\n * Type guard based on the unit name\n */\n _is(arg, type) {\n return this.units === type;\n }\n /**\n * Make sure the value is always in the defined range\n */\n _assertRange(value) {\n if (isDefined(this.maxValue) && isDefined(this.minValue)) {\n assertRange(value, this._fromType(this.minValue), this._fromType(this.maxValue));\n }\n return value;\n }\n /**\n * Convert the given value from the type specified by Param.units\n * into the destination value (such as Gain or Frequency).\n */\n _fromType(val) {\n if (this.convert && !this.overridden) {\n if (this._is(val, \"time\")) {\n return this.toSeconds(val);\n }\n else if (this._is(val, \"decibels\")) {\n return dbToGain(val);\n }\n else if (this._is(val, \"frequency\")) {\n return this.toFrequency(val);\n }\n else {\n return val;\n }\n }\n else if (this.overridden) {\n // if it's overridden, should only schedule 0s\n return 0;\n }\n else {\n return val;\n }\n }\n /**\n * Convert the parameters value into the units specified by Param.units.\n */\n _toType(val) {\n if (this.convert && this.units === \"decibels\") {\n return gainToDb(val);\n }\n else {\n return val;\n }\n }\n //-------------------------------------\n // ABSTRACT PARAM INTERFACE\n // all docs are generated from ParamInterface.ts\n //-------------------------------------\n setValueAtTime(value, time) {\n const computedTime = this.toSeconds(time);\n const numericValue = this._fromType(value);\n assert(isFinite(numericValue) && isFinite(computedTime), `Invalid argument(s) to setValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(time)}`);\n this._assertRange(numericValue);\n this.log(this.units, \"setValueAtTime\", value, computedTime);\n this._events.add({\n time: computedTime,\n type: \"setValueAtTime\",\n value: numericValue,\n });\n this._param.setValueAtTime(numericValue, computedTime);\n return this;\n }\n getValueAtTime(time) {\n const computedTime = Math.max(this.toSeconds(time), 0);\n const after = this._events.getAfter(computedTime);\n const before = this._events.get(computedTime);\n let value = this._initialValue;\n // if it was set by\n if (before === null) {\n value = this._initialValue;\n }\n else if (before.type === \"setTargetAtTime\" && (after === null || after.type === \"setValueAtTime\")) {\n const previous = this._events.getBefore(before.time);\n let previousVal;\n if (previous === null) {\n previousVal = this._initialValue;\n }\n else {\n previousVal = previous.value;\n }\n if (before.type === \"setTargetAtTime\") {\n value = this._exponentialApproach(before.time, previousVal, before.value, before.constant, computedTime);\n }\n }\n else if (after === null) {\n value = before.value;\n }\n else if (after.type === \"linearRampToValueAtTime\" || after.type === \"exponentialRampToValueAtTime\") {\n let beforeValue = before.value;\n if (before.type === \"setTargetAtTime\") {\n const previous = this._events.getBefore(before.time);\n if (previous === null) {\n beforeValue = this._initialValue;\n }\n else {\n beforeValue = previous.value;\n }\n }\n if (after.type === \"linearRampToValueAtTime\") {\n value = this._linearInterpolate(before.time, beforeValue, after.time, after.value, computedTime);\n }\n else {\n value = this._exponentialInterpolate(before.time, beforeValue, after.time, after.value, computedTime);\n }\n }\n else {\n value = before.value;\n }\n return this._toType(value);\n }\n setRampPoint(time) {\n time = this.toSeconds(time);\n let currentVal = this.getValueAtTime(time);\n this.cancelAndHoldAtTime(time);\n if (this._fromType(currentVal) === 0) {\n currentVal = this._toType(this._minOutput);\n }\n this.setValueAtTime(currentVal, time);\n return this;\n }\n linearRampToValueAtTime(value, endTime) {\n const numericValue = this._fromType(value);\n const computedTime = this.toSeconds(endTime);\n assert(isFinite(numericValue) && isFinite(computedTime), `Invalid argument(s) to linearRampToValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(endTime)}`);\n this._assertRange(numericValue);\n this._events.add({\n time: computedTime,\n type: \"linearRampToValueAtTime\",\n value: numericValue,\n });\n this.log(this.units, \"linearRampToValueAtTime\", value, computedTime);\n this._param.linearRampToValueAtTime(numericValue, computedTime);\n return this;\n }\n exponentialRampToValueAtTime(value, endTime) {\n let numericValue = this._fromType(value);\n // the value can't be 0\n numericValue = EQ(numericValue, 0) ? this._minOutput : numericValue;\n this._assertRange(numericValue);\n const computedTime = this.toSeconds(endTime);\n assert(isFinite(numericValue) && isFinite(computedTime), `Invalid argument(s) to exponentialRampToValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(endTime)}`);\n // store the event\n this._events.add({\n time: computedTime,\n type: \"exponentialRampToValueAtTime\",\n value: numericValue,\n });\n this.log(this.units, \"exponentialRampToValueAtTime\", value, computedTime);\n this._param.exponentialRampToValueAtTime(numericValue, computedTime);\n return this;\n }\n exponentialRampTo(value, rampTime, startTime) {\n startTime = this.toSeconds(startTime);\n this.setRampPoint(startTime);\n this.exponentialRampToValueAtTime(value, startTime + this.toSeconds(rampTime));\n return this;\n }\n linearRampTo(value, rampTime, startTime) {\n startTime = this.toSeconds(startTime);\n this.setRampPoint(startTime);\n this.linearRampToValueAtTime(value, startTime + this.toSeconds(rampTime));\n return this;\n }\n targetRampTo(value, rampTime, startTime) {\n startTime = this.toSeconds(startTime);\n this.setRampPoint(startTime);\n this.exponentialApproachValueAtTime(value, startTime, rampTime);\n return this;\n }\n exponentialApproachValueAtTime(value, time, rampTime) {\n time = this.toSeconds(time);\n rampTime = this.toSeconds(rampTime);\n const timeConstant = Math.log(rampTime + 1) / Math.log(200);\n this.setTargetAtTime(value, time, timeConstant);\n // at 90% start a linear ramp to the final value\n this.cancelAndHoldAtTime(time + rampTime * 0.9);\n this.linearRampToValueAtTime(value, time + rampTime);\n return this;\n }\n setTargetAtTime(value, startTime, timeConstant) {\n const numericValue = this._fromType(value);\n // The value will never be able to approach without timeConstant > 0.\n assert(isFinite(timeConstant) && timeConstant > 0, \"timeConstant must be a number greater than 0\");\n const computedTime = this.toSeconds(startTime);\n this._assertRange(numericValue);\n assert(isFinite(numericValue) && isFinite(computedTime), `Invalid argument(s) to setTargetAtTime: ${JSON.stringify(value)}, ${JSON.stringify(startTime)}`);\n this._events.add({\n constant: timeConstant,\n time: computedTime,\n type: \"setTargetAtTime\",\n value: numericValue,\n });\n this.log(this.units, \"setTargetAtTime\", value, computedTime, timeConstant);\n this._param.setTargetAtTime(numericValue, computedTime, timeConstant);\n return this;\n }\n setValueCurveAtTime(values, startTime, duration, scaling = 1) {\n duration = this.toSeconds(duration);\n startTime = this.toSeconds(startTime);\n const startingValue = this._fromType(values[0]) * scaling;\n this.setValueAtTime(this._toType(startingValue), startTime);\n const segTime = duration / (values.length - 1);\n for (let i = 1; i < values.length; i++) {\n const numericValue = this._fromType(values[i]) * scaling;\n this.linearRampToValueAtTime(this._toType(numericValue), startTime + i * segTime);\n }\n return this;\n }\n cancelScheduledValues(time) {\n const computedTime = this.toSeconds(time);\n assert(isFinite(computedTime), `Invalid argument to cancelScheduledValues: ${JSON.stringify(time)}`);\n this._events.cancel(computedTime);\n this._param.cancelScheduledValues(computedTime);\n this.log(this.units, \"cancelScheduledValues\", computedTime);\n return this;\n }\n cancelAndHoldAtTime(time) {\n const computedTime = this.toSeconds(time);\n const valueAtTime = this._fromType(this.getValueAtTime(computedTime));\n // remove the schedule events\n assert(isFinite(computedTime), `Invalid argument to cancelAndHoldAtTime: ${JSON.stringify(time)}`);\n this.log(this.units, \"cancelAndHoldAtTime\", computedTime, \"value=\" + valueAtTime);\n // if there is an event at the given computedTime\n // and that even is not a \"set\"\n const before = this._events.get(computedTime);\n const after = this._events.getAfter(computedTime);\n if (before && EQ(before.time, computedTime)) {\n // remove everything after\n if (after) {\n this._param.cancelScheduledValues(after.time);\n this._events.cancel(after.time);\n }\n else {\n this._param.cancelAndHoldAtTime(computedTime);\n this._events.cancel(computedTime + this.sampleTime);\n }\n }\n else if (after) {\n this._param.cancelScheduledValues(after.time);\n // cancel the next event(s)\n this._events.cancel(after.time);\n if (after.type === \"linearRampToValueAtTime\") {\n this.linearRampToValueAtTime(this._toType(valueAtTime), computedTime);\n }\n else if (after.type === \"exponentialRampToValueAtTime\") {\n this.exponentialRampToValueAtTime(this._toType(valueAtTime), computedTime);\n }\n }\n // set the value at the given time\n this._events.add({\n time: computedTime,\n type: \"setValueAtTime\",\n value: valueAtTime,\n });\n this._param.setValueAtTime(valueAtTime, computedTime);\n return this;\n }\n rampTo(value, rampTime = 0.1, startTime) {\n if (this.units === \"frequency\" || this.units === \"bpm\" || this.units === \"decibels\") {\n this.exponentialRampTo(value, rampTime, startTime);\n }\n else {\n this.linearRampTo(value, rampTime, startTime);\n }\n return this;\n }\n /**\n * Apply all of the previously scheduled events to the passed in Param or AudioParam.\n * The applied values will start at the context's current time and schedule\n * all of the events which are scheduled on this Param onto the passed in param.\n */\n apply(param) {\n const now = this.context.currentTime;\n // set the param's value at the current time and schedule everything else\n param.setValueAtTime(this.getValueAtTime(now), now);\n // if the previous event was a curve, then set the rest of it\n const previousEvent = this._events.get(now);\n if (previousEvent && previousEvent.type === \"setTargetAtTime\") {\n // approx it until the next event with linear ramps\n const nextEvent = this._events.getAfter(previousEvent.time);\n // or for 2 seconds if there is no event\n const endTime = nextEvent ? nextEvent.time : now + 2;\n const subdivisions = (endTime - now) / 10;\n for (let i = now; i < endTime; i += subdivisions) {\n param.linearRampToValueAtTime(this.getValueAtTime(i), i);\n }\n }\n this._events.forEachAfter(this.context.currentTime, event => {\n if (event.type === \"cancelScheduledValues\") {\n param.cancelScheduledValues(event.time);\n }\n else if (event.type === \"setTargetAtTime\") {\n param.setTargetAtTime(event.value, event.time, event.constant);\n }\n else {\n param[event.type](event.value, event.time);\n }\n });\n return this;\n }\n /**\n * Replace the Param's internal AudioParam. Will apply scheduled curves\n * onto the parameter and replace the connections.\n */\n setParam(param) {\n assert(this._swappable, \"The Param must be assigned as 'swappable' in the constructor\");\n const input = this.input;\n input.disconnect(this._param);\n this.apply(param);\n this._param = param;\n input.connect(this._param);\n return this;\n }\n dispose() {\n super.dispose();\n this._events.dispose();\n return this;\n }\n get defaultValue() {\n return this._toType(this._param.defaultValue);\n }\n //-------------------------------------\n // \tAUTOMATION CURVE CALCULATIONS\n // \tMIT License, copyright (c) 2014 Jordan Santell\n //-------------------------------------\n // Calculates the the value along the curve produced by setTargetAtTime\n _exponentialApproach(t0, v0, v1, timeConstant, t) {\n return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant);\n }\n // Calculates the the value along the curve produced by linearRampToValueAtTime\n _linearInterpolate(t0, v0, t1, v1, t) {\n return v0 + (v1 - v0) * ((t - t0) / (t1 - t0));\n }\n // Calculates the the value along the curve produced by exponentialRampToValueAtTime\n _exponentialInterpolate(t0, v0, t1, v1, t) {\n return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0));\n }\n}\n//# sourceMappingURL=Param.js.map","import { isAudioNode, isAudioParam } from \"../util/AdvancedTypeCheck\";\nimport { isDefined } from \"../util/TypeCheck\";\nimport { Param } from \"./Param\";\nimport { ToneWithContext } from \"./ToneWithContext\";\nimport { assert, warn } from \"../util/Debug\";\n/**\n * ToneAudioNode is the base class for classes which process audio.\n */\nexport class ToneAudioNode extends ToneWithContext {\n constructor() {\n super(...arguments);\n /**\n * The name of the class\n */\n this.name = \"ToneAudioNode\";\n /**\n * List all of the node that must be set to match the ChannelProperties\n */\n this._internalChannels = [];\n }\n /**\n * The number of inputs feeding into the AudioNode.\n * For source nodes, this will be 0.\n * @example\n * const node = new Tone.Gain();\n * console.log(node.numberOfInputs);\n */\n get numberOfInputs() {\n if (isDefined(this.input)) {\n if (isAudioParam(this.input) || this.input instanceof Param) {\n return 1;\n }\n else {\n return this.input.numberOfInputs;\n }\n }\n else {\n return 0;\n }\n }\n /**\n * The number of outputs of the AudioNode.\n * @example\n * const node = new Tone.Gain();\n * console.log(node.numberOfOutputs);\n */\n get numberOfOutputs() {\n if (isDefined(this.output)) {\n return this.output.numberOfOutputs;\n }\n else {\n return 0;\n }\n }\n //-------------------------------------\n // AUDIO PROPERTIES\n //-------------------------------------\n /**\n * Used to decide which nodes to get/set properties on\n */\n _isAudioNode(node) {\n return isDefined(node) && (node instanceof ToneAudioNode || isAudioNode(node));\n }\n /**\n * Get all of the audio nodes (either internal or input/output) which together\n * make up how the class node responds to channel input/output\n */\n _getInternalNodes() {\n const nodeList = this._internalChannels.slice(0);\n if (this._isAudioNode(this.input)) {\n nodeList.push(this.input);\n }\n if (this._isAudioNode(this.output)) {\n if (this.input !== this.output) {\n nodeList.push(this.output);\n }\n }\n return nodeList;\n }\n /**\n * Set the audio options for this node such as channelInterpretation\n * channelCount, etc.\n * @param options\n */\n _setChannelProperties(options) {\n const nodeList = this._getInternalNodes();\n nodeList.forEach(node => {\n node.channelCount = options.channelCount;\n node.channelCountMode = options.channelCountMode;\n node.channelInterpretation = options.channelInterpretation;\n });\n }\n /**\n * Get the current audio options for this node such as channelInterpretation\n * channelCount, etc.\n */\n _getChannelProperties() {\n const nodeList = this._getInternalNodes();\n assert(nodeList.length > 0, \"ToneAudioNode does not have any internal nodes\");\n // use the first node to get properties\n // they should all be the same\n const node = nodeList[0];\n return {\n channelCount: node.channelCount,\n channelCountMode: node.channelCountMode,\n channelInterpretation: node.channelInterpretation,\n };\n }\n /**\n * channelCount is the number of channels used when up-mixing and down-mixing\n * connections to any inputs to the node. The default value is 2 except for\n * specific nodes where its value is specially determined.\n */\n get channelCount() {\n return this._getChannelProperties().channelCount;\n }\n set channelCount(channelCount) {\n const props = this._getChannelProperties();\n // merge it with the other properties\n this._setChannelProperties(Object.assign(props, { channelCount }));\n }\n /**\n * channelCountMode determines how channels will be counted when up-mixing and\n * down-mixing connections to any inputs to the node.\n * The default value is \"max\". This attribute has no effect for nodes with no inputs.\n * * \"max\" - computedNumberOfChannels is the maximum of the number of channels of all connections to an input. In this mode channelCount is ignored.\n * * \"clamped-max\" - computedNumberOfChannels is determined as for \"max\" and then clamped to a maximum value of the given channelCount.\n * * \"explicit\" - computedNumberOfChannels is the exact value as specified by the channelCount.\n */\n get channelCountMode() {\n return this._getChannelProperties().channelCountMode;\n }\n set channelCountMode(channelCountMode) {\n const props = this._getChannelProperties();\n // merge it with the other properties\n this._setChannelProperties(Object.assign(props, { channelCountMode }));\n }\n /**\n * channelInterpretation determines how individual channels will be treated\n * when up-mixing and down-mixing connections to any inputs to the node.\n * The default value is \"speakers\".\n */\n get channelInterpretation() {\n return this._getChannelProperties().channelInterpretation;\n }\n set channelInterpretation(channelInterpretation) {\n const props = this._getChannelProperties();\n // merge it with the other properties\n this._setChannelProperties(Object.assign(props, { channelInterpretation }));\n }\n //-------------------------------------\n // CONNECTIONS\n //-------------------------------------\n /**\n * connect the output of a ToneAudioNode to an AudioParam, AudioNode, or ToneAudioNode\n * @param destination The output to connect to\n * @param outputNum The output to connect from\n * @param inputNum The input to connect to\n */\n connect(destination, outputNum = 0, inputNum = 0) {\n connect(this, destination, outputNum, inputNum);\n return this;\n }\n /**\n * Connect the output to the context's destination node.\n * @example\n * const osc = new Tone.Oscillator(\"C2\").start();\n * osc.toDestination();\n */\n toDestination() {\n this.connect(this.context.destination);\n return this;\n }\n /**\n * Connect the output to the context's destination node.\n * See [[toDestination]]\n * @deprecated\n */\n toMaster() {\n warn(\"toMaster() has been renamed toDestination()\");\n return this.toDestination();\n }\n /**\n * disconnect the output\n */\n disconnect(destination, outputNum = 0, inputNum = 0) {\n disconnect(this, destination, outputNum, inputNum);\n return this;\n }\n /**\n * Connect the output of this node to the rest of the nodes in series.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/handdrum-loop.mp3\");\n * player.autostart = true;\n * const filter = new Tone.AutoFilter(4).start();\n * const distortion = new Tone.Distortion(0.5);\n * // connect the player to the filter, distortion and then to the master output\n * player.chain(filter, distortion, Tone.Destination);\n */\n chain(...nodes) {\n connectSeries(this, ...nodes);\n return this;\n }\n /**\n * connect the output of this node to the rest of the nodes in parallel.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/conga-rhythm.mp3\");\n * player.autostart = true;\n * const pitchShift = new Tone.PitchShift(4).toDestination();\n * const filter = new Tone.Filter(\"G5\").toDestination();\n * // connect a node to the pitch shift and filter in parallel\n * player.fan(pitchShift, filter);\n */\n fan(...nodes) {\n nodes.forEach(node => this.connect(node));\n return this;\n }\n /**\n * Dispose and disconnect\n */\n dispose() {\n super.dispose();\n if (isDefined(this.input)) {\n if (this.input instanceof ToneAudioNode) {\n this.input.dispose();\n }\n else if (isAudioNode(this.input)) {\n this.input.disconnect();\n }\n }\n if (isDefined(this.output)) {\n if (this.output instanceof ToneAudioNode) {\n this.output.dispose();\n }\n else if (isAudioNode(this.output)) {\n this.output.disconnect();\n }\n }\n this._internalChannels = [];\n return this;\n }\n}\n//-------------------------------------\n// CONNECTIONS\n//-------------------------------------\n/**\n * connect together all of the arguments in series\n * @param nodes\n */\nexport function connectSeries(...nodes) {\n const first = nodes.shift();\n nodes.reduce((prev, current) => {\n if (prev instanceof ToneAudioNode) {\n prev.connect(current);\n }\n else if (isAudioNode(prev)) {\n connect(prev, current);\n }\n return current;\n }, first);\n}\n/**\n * Connect two nodes together so that signal flows from the\n * first node to the second. Optionally specify the input and output channels.\n * @param srcNode The source node\n * @param dstNode The destination node\n * @param outputNumber The output channel of the srcNode\n * @param inputNumber The input channel of the dstNode\n */\nexport function connect(srcNode, dstNode, outputNumber = 0, inputNumber = 0) {\n assert(isDefined(srcNode), \"Cannot connect from undefined node\");\n assert(isDefined(dstNode), \"Cannot connect to undefined node\");\n if (dstNode instanceof ToneAudioNode || isAudioNode(dstNode)) {\n assert(dstNode.numberOfInputs > 0, \"Cannot connect to node with no inputs\");\n }\n assert(srcNode.numberOfOutputs > 0, \"Cannot connect from node with no outputs\");\n // resolve the input of the dstNode\n while ((dstNode instanceof ToneAudioNode || dstNode instanceof Param)) {\n if (isDefined(dstNode.input)) {\n dstNode = dstNode.input;\n }\n }\n while (srcNode instanceof ToneAudioNode) {\n if (isDefined(srcNode.output)) {\n srcNode = srcNode.output;\n }\n }\n // make the connection\n if (isAudioParam(dstNode)) {\n srcNode.connect(dstNode, outputNumber);\n }\n else {\n srcNode.connect(dstNode, outputNumber, inputNumber);\n }\n}\n/**\n * Disconnect a node from all nodes or optionally include a destination node and input/output channels.\n * @param srcNode The source node\n * @param dstNode The destination node\n * @param outputNumber The output channel of the srcNode\n * @param inputNumber The input channel of the dstNode\n */\nexport function disconnect(srcNode, dstNode, outputNumber = 0, inputNumber = 0) {\n // resolve the destination node\n if (isDefined(dstNode)) {\n while (dstNode instanceof ToneAudioNode) {\n dstNode = dstNode.input;\n }\n }\n // resolve the src node\n while (!(isAudioNode(srcNode))) {\n if (isDefined(srcNode.output)) {\n srcNode = srcNode.output;\n }\n }\n if (isAudioParam(dstNode)) {\n srcNode.disconnect(dstNode, outputNumber);\n }\n else if (isAudioNode(dstNode)) {\n srcNode.disconnect(dstNode, outputNumber, inputNumber);\n }\n else {\n srcNode.disconnect();\n }\n}\n//# sourceMappingURL=ToneAudioNode.js.map","import { Param } from \"../context/Param\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { readOnly } from \"../util/Interface\";\nimport { ToneAudioNode } from \"./ToneAudioNode\";\n/**\n * A thin wrapper around the Native Web Audio GainNode.\n * The GainNode is a basic building block of the Web Audio\n * API and is useful for routing audio and adjusting gains.\n * @category Core\n * @example\n * return Tone.Offline(() => {\n * \tconst gainNode = new Tone.Gain(0).toDestination();\n * \tconst osc = new Tone.Oscillator(30).connect(gainNode).start();\n * \tgainNode.gain.rampTo(1, 0.1);\n * \tgainNode.gain.rampTo(0, 0.4, 0.2);\n * }, 0.7, 1);\n */\nexport class Gain extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Gain.getDefaults(), arguments, [\"gain\", \"units\"]));\n this.name = \"Gain\";\n /**\n * The wrapped GainNode.\n */\n this._gainNode = this.context.createGain();\n // input = output\n this.input = this._gainNode;\n this.output = this._gainNode;\n const options = optionsFromArguments(Gain.getDefaults(), arguments, [\"gain\", \"units\"]);\n this.gain = new Param({\n context: this.context,\n convert: options.convert,\n param: this._gainNode.gain,\n units: options.units,\n value: options.gain,\n minValue: options.minValue,\n maxValue: options.maxValue,\n });\n readOnly(this, \"gain\");\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n convert: true,\n gain: 1,\n units: \"gain\",\n });\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this._gainNode.disconnect();\n this.gain.dispose();\n return this;\n }\n}\n//# sourceMappingURL=Gain.js.map","import { Gain } from \"../core/context/Gain\";\nimport { ToneAudioNode, } from \"../core/context/ToneAudioNode\";\nimport { noOp } from \"../core/util/Interface\";\nimport { assert } from \"../core/util/Debug\";\n/**\n * Base class for fire-and-forget nodes\n */\nexport class OneShotSource extends ToneAudioNode {\n constructor(options) {\n super(options);\n /**\n * The callback to invoke after the\n * source is done playing.\n */\n this.onended = noOp;\n /**\n * The start time\n */\n this._startTime = -1;\n /**\n * The stop time\n */\n this._stopTime = -1;\n /**\n * The id of the timeout\n */\n this._timeout = -1;\n /**\n * The public output node\n */\n this.output = new Gain({\n context: this.context,\n gain: 0,\n });\n /**\n * The output gain node.\n */\n this._gainNode = this.output;\n /**\n * Get the playback state at the given time\n */\n this.getStateAtTime = function (time) {\n const computedTime = this.toSeconds(time);\n if (this._startTime !== -1 &&\n computedTime >= this._startTime &&\n (this._stopTime === -1 || computedTime <= this._stopTime)) {\n return \"started\";\n }\n else {\n return \"stopped\";\n }\n };\n this._fadeIn = options.fadeIn;\n this._fadeOut = options.fadeOut;\n this._curve = options.curve;\n this.onended = options.onended;\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n curve: \"linear\",\n fadeIn: 0,\n fadeOut: 0,\n onended: noOp,\n });\n }\n /**\n * Start the source at the given time\n * @param time When to start the source\n */\n _startGain(time, gain = 1) {\n assert(this._startTime === -1, \"Source cannot be started more than once\");\n // apply a fade in envelope\n const fadeInTime = this.toSeconds(this._fadeIn);\n // record the start time\n this._startTime = time + fadeInTime;\n this._startTime = Math.max(this._startTime, this.context.currentTime);\n // schedule the envelope\n if (fadeInTime > 0) {\n this._gainNode.gain.setValueAtTime(0, time);\n if (this._curve === \"linear\") {\n this._gainNode.gain.linearRampToValueAtTime(gain, time + fadeInTime);\n }\n else {\n this._gainNode.gain.exponentialApproachValueAtTime(gain, time, fadeInTime);\n }\n }\n else {\n this._gainNode.gain.setValueAtTime(gain, time);\n }\n return this;\n }\n /**\n * Stop the source node at the given time.\n * @param time When to stop the source\n */\n stop(time) {\n this.log(\"stop\", time);\n this._stopGain(this.toSeconds(time));\n return this;\n }\n /**\n * Stop the source at the given time\n * @param time When to stop the source\n */\n _stopGain(time) {\n assert(this._startTime !== -1, \"'start' must be called before 'stop'\");\n // cancel the previous stop\n this.cancelStop();\n // the fadeOut time\n const fadeOutTime = this.toSeconds(this._fadeOut);\n // schedule the stop callback\n this._stopTime = this.toSeconds(time) + fadeOutTime;\n this._stopTime = Math.max(this._stopTime, this.context.currentTime);\n if (fadeOutTime > 0) {\n // start the fade out curve at the given time\n if (this._curve === \"linear\") {\n this._gainNode.gain.linearRampTo(0, fadeOutTime, time);\n }\n else {\n this._gainNode.gain.targetRampTo(0, fadeOutTime, time);\n }\n }\n else {\n // stop any ongoing ramps, and set the value to 0\n this._gainNode.gain.cancelAndHoldAtTime(time);\n this._gainNode.gain.setValueAtTime(0, time);\n }\n this.context.clearTimeout(this._timeout);\n this._timeout = this.context.setTimeout(() => {\n // allow additional time for the exponential curve to fully decay\n const additionalTail = this._curve === \"exponential\" ? fadeOutTime * 2 : 0;\n this._stopSource(this.now() + additionalTail);\n this._onended();\n }, this._stopTime - this.context.currentTime);\n return this;\n }\n /**\n * Invoke the onended callback\n */\n _onended() {\n if (this.onended !== noOp) {\n this.onended(this);\n // overwrite onended to make sure it only is called once\n this.onended = noOp;\n // dispose when it's ended to free up for garbage collection only in the online context\n if (!this.context.isOffline) {\n const disposeCallback = () => this.dispose();\n // @ts-ignore\n if (typeof window.requestIdleCallback !== \"undefined\") {\n // @ts-ignore\n window.requestIdleCallback(disposeCallback);\n }\n else {\n setTimeout(disposeCallback, 1000);\n }\n }\n }\n }\n /**\n * Get the playback state at the current time\n */\n get state() {\n return this.getStateAtTime(this.now());\n }\n /**\n * Cancel a scheduled stop event\n */\n cancelStop() {\n this.log(\"cancelStop\");\n assert(this._startTime !== -1, \"Source is not started\");\n // cancel the stop envelope\n this._gainNode.gain.cancelScheduledValues(this._startTime + this.sampleTime);\n this.context.clearTimeout(this._timeout);\n this._stopTime = -1;\n return this;\n }\n dispose() {\n super.dispose();\n this._gainNode.disconnect();\n return this;\n }\n}\n//# sourceMappingURL=OneShotSource.js.map","import { connect } from \"../core/context/ToneAudioNode\";\nimport { Param } from \"../core/context/Param\";\nimport { optionsFromArguments } from \"../core/util/Defaults\";\nimport { OneShotSource } from \"../source/OneShotSource\";\n/**\n * Wrapper around the native fire-and-forget ConstantSource.\n * Adds the ability to reschedule the stop method.\n * @category Signal\n */\nexport class ToneConstantSource extends OneShotSource {\n constructor() {\n super(optionsFromArguments(ToneConstantSource.getDefaults(), arguments, [\"offset\"]));\n this.name = \"ToneConstantSource\";\n /**\n * The signal generator\n */\n this._source = this.context.createConstantSource();\n const options = optionsFromArguments(ToneConstantSource.getDefaults(), arguments, [\"offset\"]);\n connect(this._source, this._gainNode);\n this.offset = new Param({\n context: this.context,\n convert: options.convert,\n param: this._source.offset,\n units: options.units,\n value: options.offset,\n minValue: options.minValue,\n maxValue: options.maxValue,\n });\n }\n static getDefaults() {\n return Object.assign(OneShotSource.getDefaults(), {\n convert: true,\n offset: 1,\n units: \"number\",\n });\n }\n /**\n * Start the source node at the given time\n * @param time When to start the source\n */\n start(time) {\n const computedTime = this.toSeconds(time);\n this.log(\"start\", computedTime);\n this._startGain(computedTime);\n this._source.start(computedTime);\n return this;\n }\n _stopSource(time) {\n this._source.stop(time);\n }\n dispose() {\n super.dispose();\n if (this.state === \"started\") {\n this.stop();\n }\n this._source.disconnect();\n this.offset.dispose();\n return this;\n }\n}\n//# sourceMappingURL=ToneConstantSource.js.map","import { Param } from \"../core/context/Param\";\nimport { ToneAudioNode } from \"../core/context/ToneAudioNode\";\nimport { connect } from \"../core/context/ToneAudioNode\";\nimport { isAudioParam } from \"../core/util/AdvancedTypeCheck\";\nimport { optionsFromArguments } from \"../core/util/Defaults\";\nimport { ToneConstantSource } from \"./ToneConstantSource\";\n/**\n * A signal is an audio-rate value. Tone.Signal is a core component of the library.\n * Unlike a number, Signals can be scheduled with sample-level accuracy. Tone.Signal\n * has all of the methods available to native Web Audio\n * [AudioParam](http://webaudio.github.io/web-audio-api/#the-audioparam-interface)\n * as well as additional conveniences. Read more about working with signals\n * [here](https://github.com/Tonejs/Tone.js/wiki/Signals).\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * // a scheduleable signal which can be connected to control an AudioParam or another Signal\n * const signal = new Tone.Signal({\n * \tvalue: \"C4\",\n * \tunits: \"frequency\"\n * }).connect(osc.frequency);\n * // the scheduled ramp controls the connected signal\n * signal.rampTo(\"C2\", 4, \"+0.5\");\n * @category Signal\n */\nexport class Signal extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Signal.getDefaults(), arguments, [\"value\", \"units\"]));\n this.name = \"Signal\";\n /**\n * Indicates if the value should be overridden on connection.\n */\n this.override = true;\n const options = optionsFromArguments(Signal.getDefaults(), arguments, [\"value\", \"units\"]);\n this.output = this._constantSource = new ToneConstantSource({\n context: this.context,\n convert: options.convert,\n offset: options.value,\n units: options.units,\n minValue: options.minValue,\n maxValue: options.maxValue,\n });\n this._constantSource.start(0);\n this.input = this._param = this._constantSource.offset;\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n convert: true,\n units: \"number\",\n value: 0,\n });\n }\n connect(destination, outputNum = 0, inputNum = 0) {\n // start it only when connected to something\n connectSignal(this, destination, outputNum, inputNum);\n return this;\n }\n dispose() {\n super.dispose();\n this._param.dispose();\n this._constantSource.dispose();\n return this;\n }\n //-------------------------------------\n // ABSTRACT PARAM INTERFACE\n // just a proxy for the ConstantSourceNode's offset AudioParam\n // all docs are generated from AbstractParam.ts\n //-------------------------------------\n setValueAtTime(value, time) {\n this._param.setValueAtTime(value, time);\n return this;\n }\n getValueAtTime(time) {\n return this._param.getValueAtTime(time);\n }\n setRampPoint(time) {\n this._param.setRampPoint(time);\n return this;\n }\n linearRampToValueAtTime(value, time) {\n this._param.linearRampToValueAtTime(value, time);\n return this;\n }\n exponentialRampToValueAtTime(value, time) {\n this._param.exponentialRampToValueAtTime(value, time);\n return this;\n }\n exponentialRampTo(value, rampTime, startTime) {\n this._param.exponentialRampTo(value, rampTime, startTime);\n return this;\n }\n linearRampTo(value, rampTime, startTime) {\n this._param.linearRampTo(value, rampTime, startTime);\n return this;\n }\n targetRampTo(value, rampTime, startTime) {\n this._param.targetRampTo(value, rampTime, startTime);\n return this;\n }\n exponentialApproachValueAtTime(value, time, rampTime) {\n this._param.exponentialApproachValueAtTime(value, time, rampTime);\n return this;\n }\n setTargetAtTime(value, startTime, timeConstant) {\n this._param.setTargetAtTime(value, startTime, timeConstant);\n return this;\n }\n setValueCurveAtTime(values, startTime, duration, scaling) {\n this._param.setValueCurveAtTime(values, startTime, duration, scaling);\n return this;\n }\n cancelScheduledValues(time) {\n this._param.cancelScheduledValues(time);\n return this;\n }\n cancelAndHoldAtTime(time) {\n this._param.cancelAndHoldAtTime(time);\n return this;\n }\n rampTo(value, rampTime, startTime) {\n this._param.rampTo(value, rampTime, startTime);\n return this;\n }\n get value() {\n return this._param.value;\n }\n set value(value) {\n this._param.value = value;\n }\n get convert() {\n return this._param.convert;\n }\n set convert(convert) {\n this._param.convert = convert;\n }\n get units() {\n return this._param.units;\n }\n get overridden() {\n return this._param.overridden;\n }\n set overridden(overridden) {\n this._param.overridden = overridden;\n }\n get maxValue() {\n return this._param.maxValue;\n }\n get minValue() {\n return this._param.minValue;\n }\n /**\n * See [[Param.apply]].\n */\n apply(param) {\n this._param.apply(param);\n return this;\n }\n}\n/**\n * When connecting from a signal, it's necessary to zero out the node destination\n * node if that node is also a signal. If the destination is not 0, then the values\n * will be summed. This method insures that the output of the destination signal will\n * be the same as the source signal, making the destination signal a pass through node.\n * @param signal The output signal to connect from\n * @param destination the destination to connect to\n * @param outputNum the optional output number\n * @param inputNum the input number\n */\nexport function connectSignal(signal, destination, outputNum, inputNum) {\n if (destination instanceof Param || isAudioParam(destination) ||\n (destination instanceof Signal && destination.override)) {\n // cancel changes\n destination.cancelScheduledValues(0);\n // reset the value\n destination.setValueAtTime(0, 0);\n // mark the value as overridden\n if (destination instanceof Signal) {\n destination.overridden = true;\n }\n }\n connect(signal, destination, outputNum, inputNum);\n}\n//# sourceMappingURL=Signal.js.map","import { Param } from \"../context/Param\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { Timeline } from \"../util/Timeline\";\nimport { isUndef } from \"../util/TypeCheck\";\n/**\n * A Param class just for computing ticks. Similar to the [[Param]] class,\n * but offers conversion to BPM values as well as ability to compute tick\n * duration and elapsed ticks\n */\nexport class TickParam extends Param {\n constructor() {\n super(optionsFromArguments(TickParam.getDefaults(), arguments, [\"value\"]));\n this.name = \"TickParam\";\n /**\n * The timeline which tracks all of the automations.\n */\n this._events = new Timeline(Infinity);\n /**\n * The internal holder for the multiplier value\n */\n this._multiplier = 1;\n const options = optionsFromArguments(TickParam.getDefaults(), arguments, [\"value\"]);\n // set the multiplier\n this._multiplier = options.multiplier;\n // clear the ticks from the beginning\n this._events.cancel(0);\n // set an initial event\n this._events.add({\n ticks: 0,\n time: 0,\n type: \"setValueAtTime\",\n value: this._fromType(options.value),\n });\n this.setValueAtTime(options.value, 0);\n }\n static getDefaults() {\n return Object.assign(Param.getDefaults(), {\n multiplier: 1,\n units: \"hertz\",\n value: 1,\n });\n }\n setTargetAtTime(value, time, constant) {\n // approximate it with multiple linear ramps\n time = this.toSeconds(time);\n this.setRampPoint(time);\n const computedValue = this._fromType(value);\n // start from previously scheduled value\n const prevEvent = this._events.get(time);\n const segments = Math.round(Math.max(1 / constant, 1));\n for (let i = 0; i <= segments; i++) {\n const segTime = constant * i + time;\n const rampVal = this._exponentialApproach(prevEvent.time, prevEvent.value, computedValue, constant, segTime);\n this.linearRampToValueAtTime(this._toType(rampVal), segTime);\n }\n return this;\n }\n setValueAtTime(value, time) {\n const computedTime = this.toSeconds(time);\n super.setValueAtTime(value, time);\n const event = this._events.get(computedTime);\n const previousEvent = this._events.previousEvent(event);\n const ticksUntilTime = this._getTicksUntilEvent(previousEvent, computedTime);\n event.ticks = Math.max(ticksUntilTime, 0);\n return this;\n }\n linearRampToValueAtTime(value, time) {\n const computedTime = this.toSeconds(time);\n super.linearRampToValueAtTime(value, time);\n const event = this._events.get(computedTime);\n const previousEvent = this._events.previousEvent(event);\n const ticksUntilTime = this._getTicksUntilEvent(previousEvent, computedTime);\n event.ticks = Math.max(ticksUntilTime, 0);\n return this;\n }\n exponentialRampToValueAtTime(value, time) {\n // aproximate it with multiple linear ramps\n time = this.toSeconds(time);\n const computedVal = this._fromType(value);\n // start from previously scheduled value\n const prevEvent = this._events.get(time);\n // approx 10 segments per second\n const segments = Math.round(Math.max((time - prevEvent.time) * 10, 1));\n const segmentDur = ((time - prevEvent.time) / segments);\n for (let i = 0; i <= segments; i++) {\n const segTime = segmentDur * i + prevEvent.time;\n const rampVal = this._exponentialInterpolate(prevEvent.time, prevEvent.value, time, computedVal, segTime);\n this.linearRampToValueAtTime(this._toType(rampVal), segTime);\n }\n return this;\n }\n /**\n * Returns the tick value at the time. Takes into account\n * any automation curves scheduled on the signal.\n * @param event The time to get the tick count at\n * @return The number of ticks which have elapsed at the time given any automations.\n */\n _getTicksUntilEvent(event, time) {\n if (event === null) {\n event = {\n ticks: 0,\n time: 0,\n type: \"setValueAtTime\",\n value: 0,\n };\n }\n else if (isUndef(event.ticks)) {\n const previousEvent = this._events.previousEvent(event);\n event.ticks = this._getTicksUntilEvent(previousEvent, event.time);\n }\n const val0 = this._fromType(this.getValueAtTime(event.time));\n let val1 = this._fromType(this.getValueAtTime(time));\n // if it's right on the line, take the previous value\n const onTheLineEvent = this._events.get(time);\n if (onTheLineEvent && onTheLineEvent.time === time && onTheLineEvent.type === \"setValueAtTime\") {\n val1 = this._fromType(this.getValueAtTime(time - this.sampleTime));\n }\n return 0.5 * (time - event.time) * (val0 + val1) + event.ticks;\n }\n /**\n * Returns the tick value at the time. Takes into account\n * any automation curves scheduled on the signal.\n * @param time The time to get the tick count at\n * @return The number of ticks which have elapsed at the time given any automations.\n */\n getTicksAtTime(time) {\n const computedTime = this.toSeconds(time);\n const event = this._events.get(computedTime);\n return Math.max(this._getTicksUntilEvent(event, computedTime), 0);\n }\n /**\n * Return the elapsed time of the number of ticks from the given time\n * @param ticks The number of ticks to calculate\n * @param time The time to get the next tick from\n * @return The duration of the number of ticks from the given time in seconds\n */\n getDurationOfTicks(ticks, time) {\n const computedTime = this.toSeconds(time);\n const currentTick = this.getTicksAtTime(time);\n return this.getTimeOfTick(currentTick + ticks) - computedTime;\n }\n /**\n * Given a tick, returns the time that tick occurs at.\n * @return The time that the tick occurs.\n */\n getTimeOfTick(tick) {\n const before = this._events.get(tick, \"ticks\");\n const after = this._events.getAfter(tick, \"ticks\");\n if (before && before.ticks === tick) {\n return before.time;\n }\n else if (before && after &&\n after.type === \"linearRampToValueAtTime\" &&\n before.value !== after.value) {\n const val0 = this._fromType(this.getValueAtTime(before.time));\n const val1 = this._fromType(this.getValueAtTime(after.time));\n const delta = (val1 - val0) / (after.time - before.time);\n const k = Math.sqrt(Math.pow(val0, 2) - 2 * delta * (before.ticks - tick));\n const sol1 = (-val0 + k) / delta;\n const sol2 = (-val0 - k) / delta;\n return (sol1 > 0 ? sol1 : sol2) + before.time;\n }\n else if (before) {\n if (before.value === 0) {\n return Infinity;\n }\n else {\n return before.time + (tick - before.ticks) / before.value;\n }\n }\n else {\n return tick / this._initialValue;\n }\n }\n /**\n * Convert some number of ticks their the duration in seconds accounting\n * for any automation curves starting at the given time.\n * @param ticks The number of ticks to convert to seconds.\n * @param when When along the automation timeline to convert the ticks.\n * @return The duration in seconds of the ticks.\n */\n ticksToTime(ticks, when) {\n return this.getDurationOfTicks(ticks, when);\n }\n /**\n * The inverse of [[ticksToTime]]. Convert a duration in\n * seconds to the corresponding number of ticks accounting for any\n * automation curves starting at the given time.\n * @param duration The time interval to convert to ticks.\n * @param when When along the automation timeline to convert the ticks.\n * @return The duration in ticks.\n */\n timeToTicks(duration, when) {\n const computedTime = this.toSeconds(when);\n const computedDuration = this.toSeconds(duration);\n const startTicks = this.getTicksAtTime(computedTime);\n const endTicks = this.getTicksAtTime(computedTime + computedDuration);\n return endTicks - startTicks;\n }\n /**\n * Convert from the type when the unit value is BPM\n */\n _fromType(val) {\n if (this.units === \"bpm\" && this.multiplier) {\n return 1 / (60 / val / this.multiplier);\n }\n else {\n return super._fromType(val);\n }\n }\n /**\n * Special case of type conversion where the units === \"bpm\"\n */\n _toType(val) {\n if (this.units === \"bpm\" && this.multiplier) {\n return (val / this.multiplier) * 60;\n }\n else {\n return super._toType(val);\n }\n }\n /**\n * A multiplier on the bpm value. Useful for setting a PPQ relative to the base frequency value.\n */\n get multiplier() {\n return this._multiplier;\n }\n set multiplier(m) {\n // get and reset the current value with the new multiplier\n // might be necessary to clear all the previous values\n const currentVal = this.value;\n this._multiplier = m;\n this.cancelScheduledValues(0);\n this.setValueAtTime(currentVal, 0);\n }\n}\n//# sourceMappingURL=TickParam.js.map","import { Signal } from \"../../signal/Signal\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { TickParam } from \"./TickParam\";\n/**\n * TickSignal extends Tone.Signal, but adds the capability\n * to calculate the number of elapsed ticks. exponential and target curves\n * are approximated with multiple linear ramps.\n *\n * Thank you Bruno Dias, H. Sofia Pinto, and David M. Matos,\n * for your [WAC paper](https://smartech.gatech.edu/bitstream/handle/1853/54588/WAC2016-49.pdf)\n * describing integrating timing functions for tempo calculations.\n */\nexport class TickSignal extends Signal {\n constructor() {\n super(optionsFromArguments(TickSignal.getDefaults(), arguments, [\"value\"]));\n this.name = \"TickSignal\";\n const options = optionsFromArguments(TickSignal.getDefaults(), arguments, [\"value\"]);\n this.input = this._param = new TickParam({\n context: this.context,\n convert: options.convert,\n multiplier: options.multiplier,\n param: this._constantSource.offset,\n units: options.units,\n value: options.value,\n });\n }\n static getDefaults() {\n return Object.assign(Signal.getDefaults(), {\n multiplier: 1,\n units: \"hertz\",\n value: 1,\n });\n }\n ticksToTime(ticks, when) {\n return this._param.ticksToTime(ticks, when);\n }\n timeToTicks(duration, when) {\n return this._param.timeToTicks(duration, when);\n }\n getTimeOfTick(tick) {\n return this._param.getTimeOfTick(tick);\n }\n getDurationOfTicks(ticks, time) {\n return this._param.getDurationOfTicks(ticks, time);\n }\n getTicksAtTime(time) {\n return this._param.getTicksAtTime(time);\n }\n /**\n * A multiplier on the bpm value. Useful for setting a PPQ relative to the base frequency value.\n */\n get multiplier() {\n return this._param.multiplier;\n }\n set multiplier(m) {\n this._param.multiplier = m;\n }\n dispose() {\n super.dispose();\n this._param.dispose();\n return this;\n }\n}\n//# sourceMappingURL=TickSignal.js.map","import { ToneWithContext } from \"../context/ToneWithContext\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { readOnly } from \"../util/Interface\";\nimport { StateTimeline } from \"../util/StateTimeline\";\nimport { Timeline } from \"../util/Timeline\";\nimport { isDefined } from \"../util/TypeCheck\";\nimport { TickSignal } from \"./TickSignal\";\nimport { EQ } from \"../util/Math\";\n/**\n * Uses [TickSignal](TickSignal) to track elapsed ticks with complex automation curves.\n */\nexport class TickSource extends ToneWithContext {\n constructor() {\n super(optionsFromArguments(TickSource.getDefaults(), arguments, [\"frequency\"]));\n this.name = \"TickSource\";\n /**\n * The state timeline\n */\n this._state = new StateTimeline();\n /**\n * The offset values of the ticks\n */\n this._tickOffset = new Timeline();\n const options = optionsFromArguments(TickSource.getDefaults(), arguments, [\"frequency\"]);\n this.frequency = new TickSignal({\n context: this.context,\n units: options.units,\n value: options.frequency,\n });\n readOnly(this, \"frequency\");\n // set the initial state\n this._state.setStateAtTime(\"stopped\", 0);\n // add the first event\n this.setTicksAtTime(0, 0);\n }\n static getDefaults() {\n return Object.assign({\n frequency: 1,\n units: \"hertz\",\n }, ToneWithContext.getDefaults());\n }\n /**\n * Returns the playback state of the source, either \"started\", \"stopped\" or \"paused\".\n */\n get state() {\n return this.getStateAtTime(this.now());\n }\n /**\n * Start the clock at the given time. Optionally pass in an offset\n * of where to start the tick counter from.\n * @param time The time the clock should start\n * @param offset The number of ticks to start the source at\n */\n start(time, offset) {\n const computedTime = this.toSeconds(time);\n if (this._state.getValueAtTime(computedTime) !== \"started\") {\n this._state.setStateAtTime(\"started\", computedTime);\n if (isDefined(offset)) {\n this.setTicksAtTime(offset, computedTime);\n }\n }\n return this;\n }\n /**\n * Stop the clock. Stopping the clock resets the tick counter to 0.\n * @param time The time when the clock should stop.\n */\n stop(time) {\n const computedTime = this.toSeconds(time);\n // cancel the previous stop\n if (this._state.getValueAtTime(computedTime) === \"stopped\") {\n const event = this._state.get(computedTime);\n if (event && event.time > 0) {\n this._tickOffset.cancel(event.time);\n this._state.cancel(event.time);\n }\n }\n this._state.cancel(computedTime);\n this._state.setStateAtTime(\"stopped\", computedTime);\n this.setTicksAtTime(0, computedTime);\n return this;\n }\n /**\n * Pause the clock. Pausing does not reset the tick counter.\n * @param time The time when the clock should stop.\n */\n pause(time) {\n const computedTime = this.toSeconds(time);\n if (this._state.getValueAtTime(computedTime) === \"started\") {\n this._state.setStateAtTime(\"paused\", computedTime);\n }\n return this;\n }\n /**\n * Cancel start/stop/pause and setTickAtTime events scheduled after the given time.\n * @param time When to clear the events after\n */\n cancel(time) {\n time = this.toSeconds(time);\n this._state.cancel(time);\n this._tickOffset.cancel(time);\n return this;\n }\n /**\n * Get the elapsed ticks at the given time\n * @param time When to get the tick value\n * @return The number of ticks\n */\n getTicksAtTime(time) {\n const computedTime = this.toSeconds(time);\n const stopEvent = this._state.getLastState(\"stopped\", computedTime);\n // this event allows forEachBetween to iterate until the current time\n const tmpEvent = { state: \"paused\", time: computedTime };\n this._state.add(tmpEvent);\n // keep track of the previous offset event\n let lastState = stopEvent;\n let elapsedTicks = 0;\n // iterate through all the events since the last stop\n this._state.forEachBetween(stopEvent.time, computedTime + this.sampleTime, e => {\n let periodStartTime = lastState.time;\n // if there is an offset event in this period use that\n const offsetEvent = this._tickOffset.get(e.time);\n if (offsetEvent && offsetEvent.time >= lastState.time) {\n elapsedTicks = offsetEvent.ticks;\n periodStartTime = offsetEvent.time;\n }\n if (lastState.state === \"started\" && e.state !== \"started\") {\n elapsedTicks += this.frequency.getTicksAtTime(e.time) - this.frequency.getTicksAtTime(periodStartTime);\n }\n lastState = e;\n });\n // remove the temporary event\n this._state.remove(tmpEvent);\n // return the ticks\n return elapsedTicks;\n }\n /**\n * The number of times the callback was invoked. Starts counting at 0\n * and increments after the callback was invoked. Returns -1 when stopped.\n */\n get ticks() {\n return this.getTicksAtTime(this.now());\n }\n set ticks(t) {\n this.setTicksAtTime(t, this.now());\n }\n /**\n * The time since ticks=0 that the TickSource has been running. Accounts\n * for tempo curves\n */\n get seconds() {\n return this.getSecondsAtTime(this.now());\n }\n set seconds(s) {\n const now = this.now();\n const ticks = this.frequency.timeToTicks(s, now);\n this.setTicksAtTime(ticks, now);\n }\n /**\n * Return the elapsed seconds at the given time.\n * @param time When to get the elapsed seconds\n * @return The number of elapsed seconds\n */\n getSecondsAtTime(time) {\n time = this.toSeconds(time);\n const stopEvent = this._state.getLastState(\"stopped\", time);\n // this event allows forEachBetween to iterate until the current time\n const tmpEvent = { state: \"paused\", time };\n this._state.add(tmpEvent);\n // keep track of the previous offset event\n let lastState = stopEvent;\n let elapsedSeconds = 0;\n // iterate through all the events since the last stop\n this._state.forEachBetween(stopEvent.time, time + this.sampleTime, e => {\n let periodStartTime = lastState.time;\n // if there is an offset event in this period use that\n const offsetEvent = this._tickOffset.get(e.time);\n if (offsetEvent && offsetEvent.time >= lastState.time) {\n elapsedSeconds = offsetEvent.seconds;\n periodStartTime = offsetEvent.time;\n }\n if (lastState.state === \"started\" && e.state !== \"started\") {\n elapsedSeconds += e.time - periodStartTime;\n }\n lastState = e;\n });\n // remove the temporary event\n this._state.remove(tmpEvent);\n // return the ticks\n return elapsedSeconds;\n }\n /**\n * Set the clock's ticks at the given time.\n * @param ticks The tick value to set\n * @param time When to set the tick value\n */\n setTicksAtTime(ticks, time) {\n time = this.toSeconds(time);\n this._tickOffset.cancel(time);\n this._tickOffset.add({\n seconds: this.frequency.getDurationOfTicks(ticks, time),\n ticks,\n time,\n });\n return this;\n }\n /**\n * Returns the scheduled state at the given time.\n * @param time The time to query.\n */\n getStateAtTime(time) {\n time = this.toSeconds(time);\n return this._state.getValueAtTime(time);\n }\n /**\n * Get the time of the given tick. The second argument\n * is when to test before. Since ticks can be set (with setTicksAtTime)\n * there may be multiple times for a given tick value.\n * @param tick The tick number.\n * @param before When to measure the tick value from.\n * @return The time of the tick\n */\n getTimeOfTick(tick, before = this.now()) {\n const offset = this._tickOffset.get(before);\n const event = this._state.get(before);\n const startTime = Math.max(offset.time, event.time);\n const absoluteTicks = this.frequency.getTicksAtTime(startTime) + tick - offset.ticks;\n return this.frequency.getTimeOfTick(absoluteTicks);\n }\n /**\n * Invoke the callback event at all scheduled ticks between the\n * start time and the end time\n * @param startTime The beginning of the search range\n * @param endTime The end of the search range\n * @param callback The callback to invoke with each tick\n */\n forEachTickBetween(startTime, endTime, callback) {\n // only iterate through the sections where it is \"started\"\n let lastStateEvent = this._state.get(startTime);\n this._state.forEachBetween(startTime, endTime, event => {\n if (lastStateEvent && lastStateEvent.state === \"started\" && event.state !== \"started\") {\n this.forEachTickBetween(Math.max(lastStateEvent.time, startTime), event.time - this.sampleTime, callback);\n }\n lastStateEvent = event;\n });\n let error = null;\n if (lastStateEvent && lastStateEvent.state === \"started\") {\n const maxStartTime = Math.max(lastStateEvent.time, startTime);\n // figure out the difference between the frequency ticks and the\n const startTicks = this.frequency.getTicksAtTime(maxStartTime);\n const ticksAtStart = this.frequency.getTicksAtTime(lastStateEvent.time);\n const diff = startTicks - ticksAtStart;\n let offset = Math.ceil(diff) - diff;\n // guard against floating point issues\n offset = EQ(offset, 1) ? 0 : offset;\n let nextTickTime = this.frequency.getTimeOfTick(startTicks + offset);\n while (nextTickTime < endTime) {\n try {\n callback(nextTickTime, Math.round(this.getTicksAtTime(nextTickTime)));\n }\n catch (e) {\n error = e;\n break;\n }\n nextTickTime += this.frequency.getDurationOfTicks(1, nextTickTime);\n }\n }\n if (error) {\n throw error;\n }\n return this;\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this._state.dispose();\n this._tickOffset.dispose();\n this.frequency.dispose();\n return this;\n }\n}\n//# sourceMappingURL=TickSource.js.map","import { ToneWithContext } from \"../context/ToneWithContext\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { Emitter } from \"../util/Emitter\";\nimport { noOp, readOnly } from \"../util/Interface\";\nimport { StateTimeline } from \"../util/StateTimeline\";\nimport { TickSource } from \"./TickSource\";\nimport { assertContextRunning } from \"../util/Debug\";\n/**\n * A sample accurate clock which provides a callback at the given rate.\n * While the callback is not sample-accurate (it is still susceptible to\n * loose JS timing), the time passed in as the argument to the callback\n * is precise. For most applications, it is better to use Tone.Transport\n * instead of the Clock by itself since you can synchronize multiple callbacks.\n * @example\n * // the callback will be invoked approximately once a second\n * // and will print the time exactly once a second apart.\n * const clock = new Tone.Clock(time => {\n * \tconsole.log(time);\n * }, 1);\n * clock.start();\n * @category Core\n */\nexport class Clock extends ToneWithContext {\n constructor() {\n super(optionsFromArguments(Clock.getDefaults(), arguments, [\"callback\", \"frequency\"]));\n this.name = \"Clock\";\n /**\n * The callback function to invoke at the scheduled tick.\n */\n this.callback = noOp;\n /**\n * The last time the loop callback was invoked\n */\n this._lastUpdate = 0;\n /**\n * Keep track of the playback state\n */\n this._state = new StateTimeline(\"stopped\");\n /**\n * Context bound reference to the _loop method\n * This is necessary to remove the event in the end.\n */\n this._boundLoop = this._loop.bind(this);\n const options = optionsFromArguments(Clock.getDefaults(), arguments, [\"callback\", \"frequency\"]);\n this.callback = options.callback;\n this._tickSource = new TickSource({\n context: this.context,\n frequency: options.frequency,\n units: options.units,\n });\n this._lastUpdate = 0;\n this.frequency = this._tickSource.frequency;\n readOnly(this, \"frequency\");\n // add an initial state\n this._state.setStateAtTime(\"stopped\", 0);\n // bind a callback to the worker thread\n this.context.on(\"tick\", this._boundLoop);\n }\n static getDefaults() {\n return Object.assign(ToneWithContext.getDefaults(), {\n callback: noOp,\n frequency: 1,\n units: \"hertz\",\n });\n }\n /**\n * Returns the playback state of the source, either \"started\", \"stopped\" or \"paused\".\n */\n get state() {\n return this._state.getValueAtTime(this.now());\n }\n /**\n * Start the clock at the given time. Optionally pass in an offset\n * of where to start the tick counter from.\n * @param time The time the clock should start\n * @param offset Where the tick counter starts counting from.\n */\n start(time, offset) {\n // make sure the context is running\n assertContextRunning(this.context);\n // start the loop\n const computedTime = this.toSeconds(time);\n this.log(\"start\", computedTime);\n if (this._state.getValueAtTime(computedTime) !== \"started\") {\n this._state.setStateAtTime(\"started\", computedTime);\n this._tickSource.start(computedTime, offset);\n if (computedTime < this._lastUpdate) {\n this.emit(\"start\", computedTime, offset);\n }\n }\n return this;\n }\n /**\n * Stop the clock. Stopping the clock resets the tick counter to 0.\n * @param time The time when the clock should stop.\n * @example\n * const clock = new Tone.Clock(time => {\n * \tconsole.log(time);\n * }, 1);\n * clock.start();\n * // stop the clock after 10 seconds\n * clock.stop(\"+10\");\n */\n stop(time) {\n const computedTime = this.toSeconds(time);\n this.log(\"stop\", computedTime);\n this._state.cancel(computedTime);\n this._state.setStateAtTime(\"stopped\", computedTime);\n this._tickSource.stop(computedTime);\n if (computedTime < this._lastUpdate) {\n this.emit(\"stop\", computedTime);\n }\n return this;\n }\n /**\n * Pause the clock. Pausing does not reset the tick counter.\n * @param time The time when the clock should stop.\n */\n pause(time) {\n const computedTime = this.toSeconds(time);\n if (this._state.getValueAtTime(computedTime) === \"started\") {\n this._state.setStateAtTime(\"paused\", computedTime);\n this._tickSource.pause(computedTime);\n if (computedTime < this._lastUpdate) {\n this.emit(\"pause\", computedTime);\n }\n }\n return this;\n }\n /**\n * The number of times the callback was invoked. Starts counting at 0\n * and increments after the callback was invoked.\n */\n get ticks() {\n return Math.ceil(this.getTicksAtTime(this.now()));\n }\n set ticks(t) {\n this._tickSource.ticks = t;\n }\n /**\n * The time since ticks=0 that the Clock has been running. Accounts for tempo curves\n */\n get seconds() {\n return this._tickSource.seconds;\n }\n set seconds(s) {\n this._tickSource.seconds = s;\n }\n /**\n * Return the elapsed seconds at the given time.\n * @param time When to get the elapsed seconds\n * @return The number of elapsed seconds\n */\n getSecondsAtTime(time) {\n return this._tickSource.getSecondsAtTime(time);\n }\n /**\n * Set the clock's ticks at the given time.\n * @param ticks The tick value to set\n * @param time When to set the tick value\n */\n setTicksAtTime(ticks, time) {\n this._tickSource.setTicksAtTime(ticks, time);\n return this;\n }\n /**\n * Get the time of the given tick. The second argument\n * is when to test before. Since ticks can be set (with setTicksAtTime)\n * there may be multiple times for a given tick value.\n * @param tick The tick number.\n * @param before When to measure the tick value from.\n * @return The time of the tick\n */\n getTimeOfTick(tick, before = this.now()) {\n return this._tickSource.getTimeOfTick(tick, before);\n }\n /**\n * Get the clock's ticks at the given time.\n * @param time When to get the tick value\n * @return The tick value at the given time.\n */\n getTicksAtTime(time) {\n return this._tickSource.getTicksAtTime(time);\n }\n /**\n * Get the time of the next tick\n * @param offset The tick number.\n */\n nextTickTime(offset, when) {\n const computedTime = this.toSeconds(when);\n const currentTick = this.getTicksAtTime(computedTime);\n return this._tickSource.getTimeOfTick(currentTick + offset, computedTime);\n }\n /**\n * The scheduling loop.\n */\n _loop() {\n const startTime = this._lastUpdate;\n const endTime = this.now();\n this._lastUpdate = endTime;\n this.log(\"loop\", startTime, endTime);\n if (startTime !== endTime) {\n // the state change events\n this._state.forEachBetween(startTime, endTime, e => {\n switch (e.state) {\n case \"started\":\n const offset = this._tickSource.getTicksAtTime(e.time);\n this.emit(\"start\", e.time, offset);\n break;\n case \"stopped\":\n if (e.time !== 0) {\n this.emit(\"stop\", e.time);\n }\n break;\n case \"paused\":\n this.emit(\"pause\", e.time);\n break;\n }\n });\n // the tick callbacks\n this._tickSource.forEachTickBetween(startTime, endTime, (time, ticks) => {\n this.callback(time, ticks);\n });\n }\n }\n /**\n * Returns the scheduled state at the given time.\n * @param time The time to query.\n * @return The name of the state input in setStateAtTime.\n * @example\n * const clock = new Tone.Clock();\n * clock.start(\"+0.1\");\n * clock.getStateAtTime(\"+0.1\"); // returns \"started\"\n */\n getStateAtTime(time) {\n const computedTime = this.toSeconds(time);\n return this._state.getValueAtTime(computedTime);\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this.context.off(\"tick\", this._boundLoop);\n this._tickSource.dispose();\n this._state.dispose();\n return this;\n }\n}\nEmitter.mixin(Clock);\n//# sourceMappingURL=Clock.js.map","import { Tone } from \"../Tone\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { noOp } from \"../util/Interface\";\nimport { isString } from \"../util/TypeCheck\";\nimport { ToneAudioBuffer } from \"./ToneAudioBuffer\";\nimport { assert } from \"../util/Debug\";\n/**\n * A data structure for holding multiple buffers in a Map-like datastructure.\n *\n * @example\n * const pianoSamples = new Tone.ToneAudioBuffers({\n * \tA1: \"https://tonejs.github.io/audio/casio/A1.mp3\",\n * \tA2: \"https://tonejs.github.io/audio/casio/A2.mp3\",\n * }, () => {\n * \tconst player = new Tone.Player().toDestination();\n * \t// play one of the samples when they all load\n * \tplayer.buffer = pianoSamples.get(\"A2\");\n * \tplayer.start();\n * });\n * @example\n * // To pass in additional parameters in the second parameter\n * const buffers = new Tone.ToneAudioBuffers({\n * \t urls: {\n * \t\t A1: \"A1.mp3\",\n * \t\t A2: \"A2.mp3\",\n * \t },\n * \t onload: () => console.log(\"loaded\"),\n * \t baseUrl: \"https://tonejs.github.io/audio/casio/\"\n * });\n * @category Core\n */\nexport class ToneAudioBuffers extends Tone {\n constructor() {\n super();\n this.name = \"ToneAudioBuffers\";\n /**\n * All of the buffers\n */\n this._buffers = new Map();\n /**\n * Keep track of the number of loaded buffers\n */\n this._loadingCount = 0;\n const options = optionsFromArguments(ToneAudioBuffers.getDefaults(), arguments, [\"urls\", \"onload\", \"baseUrl\"], \"urls\");\n this.baseUrl = options.baseUrl;\n // add each one\n Object.keys(options.urls).forEach(name => {\n this._loadingCount++;\n const url = options.urls[name];\n this.add(name, url, this._bufferLoaded.bind(this, options.onload), options.onerror);\n });\n }\n static getDefaults() {\n return {\n baseUrl: \"\",\n onerror: noOp,\n onload: noOp,\n urls: {},\n };\n }\n /**\n * True if the buffers object has a buffer by that name.\n * @param name The key or index of the buffer.\n */\n has(name) {\n return this._buffers.has(name.toString());\n }\n /**\n * Get a buffer by name. If an array was loaded,\n * then use the array index.\n * @param name The key or index of the buffer.\n */\n get(name) {\n assert(this.has(name), `ToneAudioBuffers has no buffer named: ${name}`);\n return this._buffers.get(name.toString());\n }\n /**\n * A buffer was loaded. decrement the counter.\n */\n _bufferLoaded(callback) {\n this._loadingCount--;\n if (this._loadingCount === 0 && callback) {\n callback();\n }\n }\n /**\n * If the buffers are loaded or not\n */\n get loaded() {\n return Array.from(this._buffers).every(([_, buffer]) => buffer.loaded);\n }\n /**\n * Add a buffer by name and url to the Buffers\n * @param name A unique name to give the buffer\n * @param url Either the url of the bufer, or a buffer which will be added with the given name.\n * @param callback The callback to invoke when the url is loaded.\n * @param onerror Invoked if the buffer can't be loaded\n */\n add(name, url, callback = noOp, onerror = noOp) {\n if (isString(url)) {\n this._buffers.set(name.toString(), new ToneAudioBuffer(this.baseUrl + url, callback, onerror));\n }\n else {\n this._buffers.set(name.toString(), new ToneAudioBuffer(url, callback, onerror));\n }\n return this;\n }\n dispose() {\n super.dispose();\n this._buffers.forEach(buffer => buffer.dispose());\n this._buffers.clear();\n return this;\n }\n}\n//# sourceMappingURL=ToneAudioBuffers.js.map","import { getContext } from \"../Global\";\nimport { TransportTimeClass } from \"./TransportTime\";\n/**\n * Ticks is a primitive type for encoding Time values.\n * Ticks can be constructed with or without the `new` keyword. Ticks can be passed\n * into the parameter of any method which takes time as an argument.\n * @example\n * const t = Tone.Ticks(\"4n\"); // a quarter note as ticks\n * @category Unit\n */\nexport class TicksClass extends TransportTimeClass {\n constructor() {\n super(...arguments);\n this.name = \"Ticks\";\n this.defaultUnits = \"i\";\n }\n /**\n * Get the current time in the given units\n */\n _now() {\n return this.context.transport.ticks;\n }\n /**\n * Return the value of the beats in the current units\n */\n _beatsToUnits(beats) {\n return this._getPPQ() * beats;\n }\n /**\n * Returns the value of a second in the current units\n */\n _secondsToUnits(seconds) {\n return Math.floor(seconds / (60 / this._getBpm()) * this._getPPQ());\n }\n /**\n * Returns the value of a tick in the current time units\n */\n _ticksToUnits(ticks) {\n return ticks;\n }\n /**\n * Return the time in ticks\n */\n toTicks() {\n return this.valueOf();\n }\n /**\n * Return the time in seconds\n */\n toSeconds() {\n return (this.valueOf() / this._getPPQ()) * (60 / this._getBpm());\n }\n}\n/**\n * Convert a time representation to ticks\n * @category Unit\n */\nexport function Ticks(value, units) {\n return new TicksClass(getContext(), value, units);\n}\n//# sourceMappingURL=Ticks.js.map","import { ToneWithContext } from \"../context/ToneWithContext\";\nimport { Timeline } from \"./Timeline\";\nimport { onContextClose, onContextInit } from \"../context/ContextInitialization\";\n/**\n * Draw is useful for synchronizing visuals and audio events.\n * Callbacks from Tone.Transport or any of the Tone.Event classes\n * always happen _before_ the scheduled time and are not synchronized\n * to the animation frame so they are not good for triggering tightly\n * synchronized visuals and sound. Draw makes it easy to schedule\n * callbacks using the AudioContext time and uses requestAnimationFrame.\n * @example\n * Tone.Transport.schedule((time) => {\n * \t// use the time argument to schedule a callback with Draw\n * \tTone.Draw.schedule(() => {\n * \t\t// do drawing or DOM manipulation here\n * \t\tconsole.log(time);\n * \t}, time);\n * }, \"+0.5\");\n * Tone.Transport.start();\n * @category Core\n */\nexport class Draw extends ToneWithContext {\n constructor() {\n super(...arguments);\n this.name = \"Draw\";\n /**\n * The duration after which events are not invoked.\n */\n this.expiration = 0.25;\n /**\n * The amount of time before the scheduled time\n * that the callback can be invoked. Default is\n * half the time of an animation frame (0.008 seconds).\n */\n this.anticipation = 0.008;\n /**\n * All of the events.\n */\n this._events = new Timeline();\n /**\n * The draw loop\n */\n this._boundDrawLoop = this._drawLoop.bind(this);\n /**\n * The animation frame id\n */\n this._animationFrame = -1;\n }\n /**\n * Schedule a function at the given time to be invoked\n * on the nearest animation frame.\n * @param callback Callback is invoked at the given time.\n * @param time The time relative to the AudioContext time to invoke the callback.\n * @example\n * Tone.Transport.scheduleRepeat(time => {\n * \tTone.Draw.schedule(() => console.log(time), time);\n * }, 1);\n * Tone.Transport.start();\n */\n schedule(callback, time) {\n this._events.add({\n callback,\n time: this.toSeconds(time),\n });\n // start the draw loop on the first event\n if (this._events.length === 1) {\n this._animationFrame = requestAnimationFrame(this._boundDrawLoop);\n }\n return this;\n }\n /**\n * Cancel events scheduled after the given time\n * @param after Time after which scheduled events will be removed from the scheduling timeline.\n */\n cancel(after) {\n this._events.cancel(this.toSeconds(after));\n return this;\n }\n /**\n * The draw loop\n */\n _drawLoop() {\n const now = this.context.currentTime;\n while (this._events.length && this._events.peek().time - this.anticipation <= now) {\n const event = this._events.shift();\n if (event && now - event.time <= this.expiration) {\n event.callback();\n }\n }\n if (this._events.length > 0) {\n this._animationFrame = requestAnimationFrame(this._boundDrawLoop);\n }\n }\n dispose() {\n super.dispose();\n this._events.dispose();\n cancelAnimationFrame(this._animationFrame);\n return this;\n }\n}\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\nonContextInit(context => {\n context.draw = new Draw({ context });\n});\nonContextClose(context => {\n context.draw.dispose();\n});\n//# sourceMappingURL=Draw.js.map","import { Tone } from \"../Tone\";\nimport { isDefined } from \"./TypeCheck\";\nimport { assert } from \"./Debug\";\n/**\n * Similar to Tone.Timeline, but all events represent\n * intervals with both \"time\" and \"duration\" times. The\n * events are placed in a tree structure optimized\n * for querying an intersection point with the timeline\n * events. Internally uses an [Interval Tree](https://en.wikipedia.org/wiki/Interval_tree)\n * to represent the data.\n */\nexport class IntervalTimeline extends Tone {\n constructor() {\n super(...arguments);\n this.name = \"IntervalTimeline\";\n /**\n * The root node of the inteval tree\n */\n this._root = null;\n /**\n * Keep track of the length of the timeline.\n */\n this._length = 0;\n }\n /**\n * The event to add to the timeline. All events must\n * have a time and duration value\n * @param event The event to add to the timeline\n */\n add(event) {\n assert(isDefined(event.time), \"Events must have a time property\");\n assert(isDefined(event.duration), \"Events must have a duration parameter\");\n event.time = event.time.valueOf();\n let node = new IntervalNode(event.time, event.time + event.duration, event);\n if (this._root === null) {\n this._root = node;\n }\n else {\n this._root.insert(node);\n }\n this._length++;\n // Restructure tree to be balanced\n while (node !== null) {\n node.updateHeight();\n node.updateMax();\n this._rebalance(node);\n node = node.parent;\n }\n return this;\n }\n /**\n * Remove an event from the timeline.\n * @param event The event to remove from the timeline\n */\n remove(event) {\n if (this._root !== null) {\n const results = [];\n this._root.search(event.time, results);\n for (const node of results) {\n if (node.event === event) {\n this._removeNode(node);\n this._length--;\n break;\n }\n }\n }\n return this;\n }\n /**\n * The number of items in the timeline.\n * @readOnly\n */\n get length() {\n return this._length;\n }\n /**\n * Remove events whose time time is after the given time\n * @param after The time to query.\n */\n cancel(after) {\n this.forEachFrom(after, event => this.remove(event));\n return this;\n }\n /**\n * Set the root node as the given node\n */\n _setRoot(node) {\n this._root = node;\n if (this._root !== null) {\n this._root.parent = null;\n }\n }\n /**\n * Replace the references to the node in the node's parent\n * with the replacement node.\n */\n _replaceNodeInParent(node, replacement) {\n if (node.parent !== null) {\n if (node.isLeftChild()) {\n node.parent.left = replacement;\n }\n else {\n node.parent.right = replacement;\n }\n this._rebalance(node.parent);\n }\n else {\n this._setRoot(replacement);\n }\n }\n /**\n * Remove the node from the tree and replace it with\n * a successor which follows the schema.\n */\n _removeNode(node) {\n if (node.left === null && node.right === null) {\n this._replaceNodeInParent(node, null);\n }\n else if (node.right === null) {\n this._replaceNodeInParent(node, node.left);\n }\n else if (node.left === null) {\n this._replaceNodeInParent(node, node.right);\n }\n else {\n const balance = node.getBalance();\n let replacement;\n let temp = null;\n if (balance > 0) {\n if (node.left.right === null) {\n replacement = node.left;\n replacement.right = node.right;\n temp = replacement;\n }\n else {\n replacement = node.left.right;\n while (replacement.right !== null) {\n replacement = replacement.right;\n }\n if (replacement.parent) {\n replacement.parent.right = replacement.left;\n temp = replacement.parent;\n replacement.left = node.left;\n replacement.right = node.right;\n }\n }\n }\n else if (node.right.left === null) {\n replacement = node.right;\n replacement.left = node.left;\n temp = replacement;\n }\n else {\n replacement = node.right.left;\n while (replacement.left !== null) {\n replacement = replacement.left;\n }\n if (replacement.parent) {\n replacement.parent.left = replacement.right;\n temp = replacement.parent;\n replacement.left = node.left;\n replacement.right = node.right;\n }\n }\n if (node.parent !== null) {\n if (node.isLeftChild()) {\n node.parent.left = replacement;\n }\n else {\n node.parent.right = replacement;\n }\n }\n else {\n this._setRoot(replacement);\n }\n if (temp) {\n this._rebalance(temp);\n }\n }\n node.dispose();\n }\n /**\n * Rotate the tree to the left\n */\n _rotateLeft(node) {\n const parent = node.parent;\n const isLeftChild = node.isLeftChild();\n // Make node.right the new root of this sub tree (instead of node)\n const pivotNode = node.right;\n if (pivotNode) {\n node.right = pivotNode.left;\n pivotNode.left = node;\n }\n if (parent !== null) {\n if (isLeftChild) {\n parent.left = pivotNode;\n }\n else {\n parent.right = pivotNode;\n }\n }\n else {\n this._setRoot(pivotNode);\n }\n }\n /**\n * Rotate the tree to the right\n */\n _rotateRight(node) {\n const parent = node.parent;\n const isLeftChild = node.isLeftChild();\n // Make node.left the new root of this sub tree (instead of node)\n const pivotNode = node.left;\n if (pivotNode) {\n node.left = pivotNode.right;\n pivotNode.right = node;\n }\n if (parent !== null) {\n if (isLeftChild) {\n parent.left = pivotNode;\n }\n else {\n parent.right = pivotNode;\n }\n }\n else {\n this._setRoot(pivotNode);\n }\n }\n /**\n * Balance the BST\n */\n _rebalance(node) {\n const balance = node.getBalance();\n if (balance > 1 && node.left) {\n if (node.left.getBalance() < 0) {\n this._rotateLeft(node.left);\n }\n else {\n this._rotateRight(node);\n }\n }\n else if (balance < -1 && node.right) {\n if (node.right.getBalance() > 0) {\n this._rotateRight(node.right);\n }\n else {\n this._rotateLeft(node);\n }\n }\n }\n /**\n * Get an event whose time and duration span the give time. Will\n * return the match whose \"time\" value is closest to the given time.\n * @return The event which spans the desired time\n */\n get(time) {\n if (this._root !== null) {\n const results = [];\n this._root.search(time, results);\n if (results.length > 0) {\n let max = results[0];\n for (let i = 1; i < results.length; i++) {\n if (results[i].low > max.low) {\n max = results[i];\n }\n }\n return max.event;\n }\n }\n return null;\n }\n /**\n * Iterate over everything in the timeline.\n * @param callback The callback to invoke with every item\n */\n forEach(callback) {\n if (this._root !== null) {\n const allNodes = [];\n this._root.traverse(node => allNodes.push(node));\n allNodes.forEach(node => {\n if (node.event) {\n callback(node.event);\n }\n });\n }\n return this;\n }\n /**\n * Iterate over everything in the array in which the given time\n * overlaps with the time and duration time of the event.\n * @param time The time to check if items are overlapping\n * @param callback The callback to invoke with every item\n */\n forEachAtTime(time, callback) {\n if (this._root !== null) {\n const results = [];\n this._root.search(time, results);\n results.forEach(node => {\n if (node.event) {\n callback(node.event);\n }\n });\n }\n return this;\n }\n /**\n * Iterate over everything in the array in which the time is greater\n * than or equal to the given time.\n * @param time The time to check if items are before\n * @param callback The callback to invoke with every item\n */\n forEachFrom(time, callback) {\n if (this._root !== null) {\n const results = [];\n this._root.searchAfter(time, results);\n results.forEach(node => {\n if (node.event) {\n callback(node.event);\n }\n });\n }\n return this;\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n if (this._root !== null) {\n this._root.traverse(node => node.dispose());\n }\n this._root = null;\n return this;\n }\n}\n//-------------------------------------\n// \tINTERVAL NODE HELPER\n//-------------------------------------\n/**\n * Represents a node in the binary search tree, with the addition\n * of a \"high\" value which keeps track of the highest value of\n * its children.\n * References:\n * https://brooknovak.wordpress.com/2013/12/07/augmented-interval-tree-in-c/\n * http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf\n * @param low\n * @param high\n */\nclass IntervalNode {\n constructor(low, high, event) {\n // the nodes to the left\n this._left = null;\n // the nodes to the right\n this._right = null;\n // the parent node\n this.parent = null;\n // the number of child nodes\n this.height = 0;\n this.event = event;\n // the low value\n this.low = low;\n // the high value\n this.high = high;\n // the high value for this and all child nodes\n this.max = this.high;\n }\n /**\n * Insert a node into the correct spot in the tree\n */\n insert(node) {\n if (node.low <= this.low) {\n if (this.left === null) {\n this.left = node;\n }\n else {\n this.left.insert(node);\n }\n }\n else if (this.right === null) {\n this.right = node;\n }\n else {\n this.right.insert(node);\n }\n }\n /**\n * Search the tree for nodes which overlap\n * with the given point\n * @param point The point to query\n * @param results The array to put the results\n */\n search(point, results) {\n // If p is to the right of the rightmost point of any interval\n // in this node and all children, there won't be any matches.\n if (point > this.max) {\n return;\n }\n // Search left children\n if (this.left !== null) {\n this.left.search(point, results);\n }\n // Check this node\n if (this.low <= point && this.high > point) {\n results.push(this);\n }\n // If p is to the left of the time of this interval,\n // then it can't be in any child to the right.\n if (this.low > point) {\n return;\n }\n // Search right children\n if (this.right !== null) {\n this.right.search(point, results);\n }\n }\n /**\n * Search the tree for nodes which are less\n * than the given point\n * @param point The point to query\n * @param results The array to put the results\n */\n searchAfter(point, results) {\n // Check this node\n if (this.low >= point) {\n results.push(this);\n if (this.left !== null) {\n this.left.searchAfter(point, results);\n }\n }\n // search the right side\n if (this.right !== null) {\n this.right.searchAfter(point, results);\n }\n }\n /**\n * Invoke the callback on this element and both it's branches\n * @param {Function} callback\n */\n traverse(callback) {\n callback(this);\n if (this.left !== null) {\n this.left.traverse(callback);\n }\n if (this.right !== null) {\n this.right.traverse(callback);\n }\n }\n /**\n * Update the height of the node\n */\n updateHeight() {\n if (this.left !== null && this.right !== null) {\n this.height = Math.max(this.left.height, this.right.height) + 1;\n }\n else if (this.right !== null) {\n this.height = this.right.height + 1;\n }\n else if (this.left !== null) {\n this.height = this.left.height + 1;\n }\n else {\n this.height = 0;\n }\n }\n /**\n * Update the height of the node\n */\n updateMax() {\n this.max = this.high;\n if (this.left !== null) {\n this.max = Math.max(this.max, this.left.max);\n }\n if (this.right !== null) {\n this.max = Math.max(this.max, this.right.max);\n }\n }\n /**\n * The balance is how the leafs are distributed on the node\n * @return Negative numbers are balanced to the right\n */\n getBalance() {\n let balance = 0;\n if (this.left !== null && this.right !== null) {\n balance = this.left.height - this.right.height;\n }\n else if (this.left !== null) {\n balance = this.left.height + 1;\n }\n else if (this.right !== null) {\n balance = -(this.right.height + 1);\n }\n return balance;\n }\n /**\n * @returns true if this node is the left child of its parent\n */\n isLeftChild() {\n return this.parent !== null && this.parent.left === this;\n }\n /**\n * get/set the left node\n */\n get left() {\n return this._left;\n }\n set left(node) {\n this._left = node;\n if (node !== null) {\n node.parent = this;\n }\n this.updateHeight();\n this.updateMax();\n }\n /**\n * get/set the right node\n */\n get right() {\n return this._right;\n }\n set right(node) {\n this._right = node;\n if (node !== null) {\n node.parent = this;\n }\n this.updateHeight();\n this.updateMax();\n }\n /**\n * null out references.\n */\n dispose() {\n this.parent = null;\n this._left = null;\n this._right = null;\n this.event = null;\n }\n}\n//# sourceMappingURL=IntervalTimeline.js.map","import { Gain } from \"../../core/context/Gain\";\nimport { ToneAudioNode } from \"../../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\n/**\n * Volume is a simple volume node, useful for creating a volume fader.\n *\n * @example\n * const vol = new Tone.Volume(-12).toDestination();\n * const osc = new Tone.Oscillator().connect(vol).start();\n * @category Component\n */\nexport class Volume extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Volume.getDefaults(), arguments, [\"volume\"]));\n this.name = \"Volume\";\n const options = optionsFromArguments(Volume.getDefaults(), arguments, [\"volume\"]);\n this.input = this.output = new Gain({\n context: this.context,\n gain: options.volume,\n units: \"decibels\",\n });\n this.volume = this.output.gain;\n readOnly(this, \"volume\");\n this._unmutedVolume = options.volume;\n // set the mute initially\n this.mute = options.mute;\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n mute: false,\n volume: 0,\n });\n }\n /**\n * Mute the output.\n * @example\n * const vol = new Tone.Volume(-12).toDestination();\n * const osc = new Tone.Oscillator().connect(vol).start();\n * // mute the output\n * vol.mute = true;\n */\n get mute() {\n return this.volume.value === -Infinity;\n }\n set mute(mute) {\n if (!this.mute && mute) {\n this._unmutedVolume = this.volume.value;\n // maybe it should ramp here?\n this.volume.value = -Infinity;\n }\n else if (this.mute && !mute) {\n this.volume.value = this._unmutedVolume;\n }\n }\n /**\n * clean up\n */\n dispose() {\n super.dispose();\n this.input.dispose();\n this.volume.dispose();\n return this;\n }\n}\n//# sourceMappingURL=Volume.js.map","import { Volume } from \"../../component/channel/Volume\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { onContextClose, onContextInit } from \"./ContextInitialization\";\nimport { Gain } from \"./Gain\";\nimport { connectSeries, ToneAudioNode } from \"./ToneAudioNode\";\n/**\n * A single master output which is connected to the\n * AudioDestinationNode (aka your speakers).\n * It provides useful conveniences such as the ability\n * to set the volume and mute the entire application.\n * It also gives you the ability to apply master effects to your application.\n *\n * @example\n * const oscillator = new Tone.Oscillator().start();\n * // the audio will go from the oscillator to the speakers\n * oscillator.connect(Tone.getDestination());\n * // a convenience for connecting to the master output is also provided:\n * oscillator.toDestination();\n * @category Core\n */\nexport class Destination extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Destination.getDefaults(), arguments));\n this.name = \"Destination\";\n this.input = new Volume({ context: this.context });\n this.output = new Gain({ context: this.context });\n /**\n * The volume of the master output in decibels. -Infinity is silent, and 0 is no change.\n * @example\n * const osc = new Tone.Oscillator().toDestination();\n * osc.start();\n * // ramp the volume down to silent over 10 seconds\n * Tone.getDestination().volume.rampTo(-Infinity, 10);\n */\n this.volume = this.input.volume;\n const options = optionsFromArguments(Destination.getDefaults(), arguments);\n connectSeries(this.input, this.output, this.context.rawContext.destination);\n this.mute = options.mute;\n this._internalChannels = [this.input, this.context.rawContext.destination, this.output];\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n mute: false,\n volume: 0,\n });\n }\n /**\n * Mute the output.\n * @example\n * const oscillator = new Tone.Oscillator().start().toDestination();\n * setTimeout(() => {\n * \t// mute the output\n * \tTone.Destination.mute = true;\n * }, 1000);\n */\n get mute() {\n return this.input.mute;\n }\n set mute(mute) {\n this.input.mute = mute;\n }\n /**\n * Add a master effects chain. NOTE: this will disconnect any nodes which were previously\n * chained in the master effects chain.\n * @param args All arguments will be connected in a row and the Master will be routed through it.\n * @example\n * // route all audio through a filter and compressor\n * const lowpass = new Tone.Filter(800, \"lowpass\");\n * const compressor = new Tone.Compressor(-18);\n * Tone.Destination.chain(lowpass, compressor);\n */\n chain(...args) {\n this.input.disconnect();\n args.unshift(this.input);\n args.push(this.output);\n connectSeries(...args);\n return this;\n }\n /**\n * The maximum number of channels the system can output\n * @example\n * console.log(Tone.Destination.maxChannelCount);\n */\n get maxChannelCount() {\n return this.context.rawContext.destination.maxChannelCount;\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this.volume.dispose();\n return this;\n }\n}\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\nonContextInit(context => {\n context.destination = new Destination({ context });\n});\nonContextClose(context => {\n context.destination.dispose();\n});\n//# sourceMappingURL=Destination.js.map","import { Timeline } from \"./Timeline\";\nimport { Tone } from \"../Tone\";\n/**\n * Represents a single value which is gettable and settable in a timed way\n */\nexport class TimelineValue extends Tone {\n /**\n * @param initialValue The value to return if there is no scheduled values\n */\n constructor(initialValue) {\n super();\n this.name = \"TimelineValue\";\n /**\n * The timeline which stores the values\n */\n this._timeline = new Timeline({ memory: 10 });\n this._initialValue = initialValue;\n }\n /**\n * Set the value at the given time\n */\n set(value, time) {\n this._timeline.add({\n value, time\n });\n return this;\n }\n /**\n * Get the value at the given time\n */\n get(time) {\n const event = this._timeline.get(time);\n if (event) {\n return event.value;\n }\n else {\n return this._initialValue;\n }\n }\n}\n//# sourceMappingURL=TimelineValue.js.map","import { noOp } from \"../util/Interface\";\n/**\n * TransportEvent is an internal class used by [[Transport]]\n * to schedule events. Do no invoke this class directly, it is\n * handled from within Tone.Transport.\n */\nexport class TransportEvent {\n /**\n * @param transport The transport object which the event belongs to\n */\n constructor(transport, opts) {\n /**\n * The unique id of the event\n */\n this.id = TransportEvent._eventId++;\n const options = Object.assign(TransportEvent.getDefaults(), opts);\n this.transport = transport;\n this.callback = options.callback;\n this._once = options.once;\n this.time = options.time;\n }\n static getDefaults() {\n return {\n callback: noOp,\n once: false,\n time: 0,\n };\n }\n /**\n * Invoke the event callback.\n * @param time The AudioContext time in seconds of the event\n */\n invoke(time) {\n if (this.callback) {\n this.callback(time);\n if (this._once) {\n this.transport.clear(this.id);\n }\n }\n }\n /**\n * Clean up\n */\n dispose() {\n this.callback = undefined;\n return this;\n }\n}\n/**\n * Current ID counter\n */\nTransportEvent._eventId = 0;\n//# sourceMappingURL=TransportEvent.js.map","import { TicksClass } from \"../type/Ticks\";\nimport { TransportEvent } from \"./TransportEvent\";\n/**\n * TransportRepeatEvent is an internal class used by Tone.Transport\n * to schedule repeat events. This class should not be instantiated directly.\n */\nexport class TransportRepeatEvent extends TransportEvent {\n /**\n * @param transport The transport object which the event belongs to\n */\n constructor(transport, opts) {\n super(transport, opts);\n /**\n * The ID of the current timeline event\n */\n this._currentId = -1;\n /**\n * The ID of the next timeline event\n */\n this._nextId = -1;\n /**\n * The time of the next event\n */\n this._nextTick = this.time;\n /**\n * a reference to the bound start method\n */\n this._boundRestart = this._restart.bind(this);\n const options = Object.assign(TransportRepeatEvent.getDefaults(), opts);\n this.duration = new TicksClass(transport.context, options.duration).valueOf();\n this._interval = new TicksClass(transport.context, options.interval).valueOf();\n this._nextTick = options.time;\n this.transport.on(\"start\", this._boundRestart);\n this.transport.on(\"loopStart\", this._boundRestart);\n this.context = this.transport.context;\n this._restart();\n }\n static getDefaults() {\n return Object.assign({}, TransportEvent.getDefaults(), {\n duration: Infinity,\n interval: 1,\n once: false,\n });\n }\n /**\n * Invoke the callback. Returns the tick time which\n * the next event should be scheduled at.\n * @param time The AudioContext time in seconds of the event\n */\n invoke(time) {\n // create more events if necessary\n this._createEvents(time);\n // call the super class\n super.invoke(time);\n }\n /**\n * Push more events onto the timeline to keep up with the position of the timeline\n */\n _createEvents(time) {\n // schedule the next event\n const ticks = this.transport.getTicksAtTime(time);\n if (ticks >= this.time && ticks >= this._nextTick && this._nextTick + this._interval < this.time + this.duration) {\n this._nextTick += this._interval;\n this._currentId = this._nextId;\n this._nextId = this.transport.scheduleOnce(this.invoke.bind(this), new TicksClass(this.context, this._nextTick).toSeconds());\n }\n }\n /**\n * Push more events onto the timeline to keep up with the position of the timeline\n */\n _restart(time) {\n this.transport.clear(this._currentId);\n this.transport.clear(this._nextId);\n this._nextTick = this.time;\n const ticks = this.transport.getTicksAtTime(time);\n if (ticks > this.time) {\n this._nextTick = this.time + Math.ceil((ticks - this.time) / this._interval) * this._interval;\n }\n this._currentId = this.transport.scheduleOnce(this.invoke.bind(this), new TicksClass(this.context, this._nextTick).toSeconds());\n this._nextTick += this._interval;\n this._nextId = this.transport.scheduleOnce(this.invoke.bind(this), new TicksClass(this.context, this._nextTick).toSeconds());\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this.transport.clear(this._currentId);\n this.transport.clear(this._nextId);\n this.transport.off(\"start\", this._boundRestart);\n this.transport.off(\"loopStart\", this._boundRestart);\n return this;\n }\n}\n//# sourceMappingURL=TransportRepeatEvent.js.map","import { TimeClass } from \"../../core/type/Time\";\nimport { TimelineValue } from \"../../core/util/TimelineValue\";\nimport { onContextClose, onContextInit } from \"../context/ContextInitialization\";\nimport { Gain } from \"../context/Gain\";\nimport { ToneWithContext } from \"../context/ToneWithContext\";\nimport { TicksClass } from \"../type/Ticks\";\nimport { TransportTimeClass } from \"../type/TransportTime\";\nimport { optionsFromArguments } from \"../util/Defaults\";\nimport { Emitter } from \"../util/Emitter\";\nimport { readOnly, writable } from \"../util/Interface\";\nimport { IntervalTimeline } from \"../util/IntervalTimeline\";\nimport { Timeline } from \"../util/Timeline\";\nimport { isArray, isDefined } from \"../util/TypeCheck\";\nimport { Clock } from \"./Clock\";\nimport { TransportEvent } from \"./TransportEvent\";\nimport { TransportRepeatEvent } from \"./TransportRepeatEvent\";\n/**\n * Transport for timing musical events.\n * Supports tempo curves and time changes. Unlike browser-based timing (setInterval, requestAnimationFrame)\n * Transport timing events pass in the exact time of the scheduled event\n * in the argument of the callback function. Pass that time value to the object\n * you're scheduling.

\n * A single transport is created for you when the library is initialized.\n *

\n * The transport emits the events: \"start\", \"stop\", \"pause\", and \"loop\" which are\n * called with the time of that event as the argument.\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination();\n * // repeated event every 8th note\n * Tone.Transport.scheduleRepeat((time) => {\n * \t// use the callback time to schedule events\n * \tosc.start(time).stop(time + 0.1);\n * }, \"8n\");\n * // transport must be started before it starts invoking events\n * Tone.Transport.start();\n * @category Core\n */\nexport class Transport extends ToneWithContext {\n constructor() {\n super(optionsFromArguments(Transport.getDefaults(), arguments));\n this.name = \"Transport\";\n //-------------------------------------\n // \tLOOPING\n //-------------------------------------\n /**\n * If the transport loops or not.\n */\n this._loop = new TimelineValue(false);\n /**\n * The loop start position in ticks\n */\n this._loopStart = 0;\n /**\n * The loop end position in ticks\n */\n this._loopEnd = 0;\n //-------------------------------------\n // \tTIMELINE EVENTS\n //-------------------------------------\n /**\n * All the events in an object to keep track by ID\n */\n this._scheduledEvents = {};\n /**\n * The scheduled events.\n */\n this._timeline = new Timeline();\n /**\n * Repeated events\n */\n this._repeatedEvents = new IntervalTimeline();\n /**\n * All of the synced Signals\n */\n this._syncedSignals = [];\n /**\n * The swing amount\n */\n this._swingAmount = 0;\n const options = optionsFromArguments(Transport.getDefaults(), arguments);\n // CLOCK/TEMPO\n this._ppq = options.ppq;\n this._clock = new Clock({\n callback: this._processTick.bind(this),\n context: this.context,\n frequency: 0,\n units: \"bpm\",\n });\n this._bindClockEvents();\n this.bpm = this._clock.frequency;\n this._clock.frequency.multiplier = options.ppq;\n this.bpm.setValueAtTime(options.bpm, 0);\n readOnly(this, \"bpm\");\n this._timeSignature = options.timeSignature;\n // SWING\n this._swingTicks = options.ppq / 2; // 8n\n }\n static getDefaults() {\n return Object.assign(ToneWithContext.getDefaults(), {\n bpm: 120,\n loopEnd: \"4m\",\n loopStart: 0,\n ppq: 192,\n swing: 0,\n swingSubdivision: \"8n\",\n timeSignature: 4,\n });\n }\n //-------------------------------------\n // \tTICKS\n //-------------------------------------\n /**\n * called on every tick\n * @param tickTime clock relative tick time\n */\n _processTick(tickTime, ticks) {\n // do the loop test\n if (this._loop.get(tickTime)) {\n if (ticks >= this._loopEnd) {\n this.emit(\"loopEnd\", tickTime);\n this._clock.setTicksAtTime(this._loopStart, tickTime);\n ticks = this._loopStart;\n this.emit(\"loopStart\", tickTime, this._clock.getSecondsAtTime(tickTime));\n this.emit(\"loop\", tickTime);\n }\n }\n // handle swing\n if (this._swingAmount > 0 &&\n ticks % this._ppq !== 0 && // not on a downbeat\n ticks % (this._swingTicks * 2) !== 0) {\n // add some swing\n const progress = (ticks % (this._swingTicks * 2)) / (this._swingTicks * 2);\n const amount = Math.sin((progress) * Math.PI) * this._swingAmount;\n tickTime += new TicksClass(this.context, this._swingTicks * 2 / 3).toSeconds() * amount;\n }\n // invoke the timeline events scheduled on this tick\n this._timeline.forEachAtTime(ticks, event => event.invoke(tickTime));\n }\n //-------------------------------------\n // \tSCHEDULABLE EVENTS\n //-------------------------------------\n /**\n * Schedule an event along the timeline.\n * @param callback The callback to be invoked at the time.\n * @param time The time to invoke the callback at.\n * @return The id of the event which can be used for canceling the event.\n * @example\n * // schedule an event on the 16th measure\n * Tone.Transport.schedule((time) => {\n * \t// invoked on measure 16\n * \tconsole.log(\"measure 16!\");\n * }, \"16:0:0\");\n */\n schedule(callback, time) {\n const event = new TransportEvent(this, {\n callback,\n time: new TransportTimeClass(this.context, time).toTicks(),\n });\n return this._addEvent(event, this._timeline);\n }\n /**\n * Schedule a repeated event along the timeline. The event will fire\n * at the `interval` starting at the `startTime` and for the specified\n * `duration`.\n * @param callback The callback to invoke.\n * @param interval The duration between successive callbacks. Must be a positive number.\n * @param startTime When along the timeline the events should start being invoked.\n * @param duration How long the event should repeat.\n * @return The ID of the scheduled event. Use this to cancel the event.\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * // a callback invoked every eighth note after the first measure\n * Tone.Transport.scheduleRepeat((time) => {\n * \tosc.start(time).stop(time + 0.1);\n * }, \"8n\", \"1m\");\n */\n scheduleRepeat(callback, interval, startTime, duration = Infinity) {\n const event = new TransportRepeatEvent(this, {\n callback,\n duration: new TimeClass(this.context, duration).toTicks(),\n interval: new TimeClass(this.context, interval).toTicks(),\n time: new TransportTimeClass(this.context, startTime).toTicks(),\n });\n // kick it off if the Transport is started\n // @ts-ignore\n return this._addEvent(event, this._repeatedEvents);\n }\n /**\n * Schedule an event that will be removed after it is invoked.\n * @param callback The callback to invoke once.\n * @param time The time the callback should be invoked.\n * @returns The ID of the scheduled event.\n */\n scheduleOnce(callback, time) {\n const event = new TransportEvent(this, {\n callback,\n once: true,\n time: new TransportTimeClass(this.context, time).toTicks(),\n });\n return this._addEvent(event, this._timeline);\n }\n /**\n * Clear the passed in event id from the timeline\n * @param eventId The id of the event.\n */\n clear(eventId) {\n if (this._scheduledEvents.hasOwnProperty(eventId)) {\n const item = this._scheduledEvents[eventId.toString()];\n item.timeline.remove(item.event);\n item.event.dispose();\n delete this._scheduledEvents[eventId.toString()];\n }\n return this;\n }\n /**\n * Add an event to the correct timeline. Keep track of the\n * timeline it was added to.\n * @returns the event id which was just added\n */\n _addEvent(event, timeline) {\n this._scheduledEvents[event.id.toString()] = {\n event,\n timeline,\n };\n timeline.add(event);\n return event.id;\n }\n /**\n * Remove scheduled events from the timeline after\n * the given time. Repeated events will be removed\n * if their startTime is after the given time\n * @param after Clear all events after this time.\n */\n cancel(after = 0) {\n const computedAfter = this.toTicks(after);\n this._timeline.forEachFrom(computedAfter, event => this.clear(event.id));\n this._repeatedEvents.forEachFrom(computedAfter, event => this.clear(event.id));\n return this;\n }\n //-------------------------------------\n // \tSTART/STOP/PAUSE\n //-------------------------------------\n /**\n * Bind start/stop/pause events from the clock and emit them.\n */\n _bindClockEvents() {\n this._clock.on(\"start\", (time, offset) => {\n offset = new TicksClass(this.context, offset).toSeconds();\n this.emit(\"start\", time, offset);\n });\n this._clock.on(\"stop\", (time) => {\n this.emit(\"stop\", time);\n });\n this._clock.on(\"pause\", (time) => {\n this.emit(\"pause\", time);\n });\n }\n /**\n * Returns the playback state of the source, either \"started\", \"stopped\", or \"paused\"\n */\n get state() {\n return this._clock.getStateAtTime(this.now());\n }\n /**\n * Start the transport and all sources synced to the transport.\n * @param time The time when the transport should start.\n * @param offset The timeline offset to start the transport.\n * @example\n * // start the transport in one second starting at beginning of the 5th measure.\n * Tone.Transport.start(\"+1\", \"4:0:0\");\n */\n start(time, offset) {\n let offsetTicks;\n if (isDefined(offset)) {\n offsetTicks = this.toTicks(offset);\n }\n // start the clock\n this._clock.start(time, offsetTicks);\n return this;\n }\n /**\n * Stop the transport and all sources synced to the transport.\n * @param time The time when the transport should stop.\n * @example\n * Tone.Transport.stop();\n */\n stop(time) {\n this._clock.stop(time);\n return this;\n }\n /**\n * Pause the transport and all sources synced to the transport.\n */\n pause(time) {\n this._clock.pause(time);\n return this;\n }\n /**\n * Toggle the current state of the transport. If it is\n * started, it will stop it, otherwise it will start the Transport.\n * @param time The time of the event\n */\n toggle(time) {\n time = this.toSeconds(time);\n if (this._clock.getStateAtTime(time) !== \"started\") {\n this.start(time);\n }\n else {\n this.stop(time);\n }\n return this;\n }\n //-------------------------------------\n // \tSETTERS/GETTERS\n //-------------------------------------\n /**\n * The time signature as just the numerator over 4.\n * For example 4/4 would be just 4 and 6/8 would be 3.\n * @example\n * // common time\n * Tone.Transport.timeSignature = 4;\n * // 7/8\n * Tone.Transport.timeSignature = [7, 8];\n * // this will be reduced to a single number\n * Tone.Transport.timeSignature; // returns 3.5\n */\n get timeSignature() {\n return this._timeSignature;\n }\n set timeSignature(timeSig) {\n if (isArray(timeSig)) {\n timeSig = (timeSig[0] / timeSig[1]) * 4;\n }\n this._timeSignature = timeSig;\n }\n /**\n * When the Transport.loop = true, this is the starting position of the loop.\n */\n get loopStart() {\n return new TimeClass(this.context, this._loopStart, \"i\").toSeconds();\n }\n set loopStart(startPosition) {\n this._loopStart = this.toTicks(startPosition);\n }\n /**\n * When the Transport.loop = true, this is the ending position of the loop.\n */\n get loopEnd() {\n return new TimeClass(this.context, this._loopEnd, \"i\").toSeconds();\n }\n set loopEnd(endPosition) {\n this._loopEnd = this.toTicks(endPosition);\n }\n /**\n * If the transport loops or not.\n */\n get loop() {\n return this._loop.get(this.now());\n }\n set loop(loop) {\n this._loop.set(loop, this.now());\n }\n /**\n * Set the loop start and stop at the same time.\n * @example\n * // loop over the first measure\n * Tone.Transport.setLoopPoints(0, \"1m\");\n * Tone.Transport.loop = true;\n */\n setLoopPoints(startPosition, endPosition) {\n this.loopStart = startPosition;\n this.loopEnd = endPosition;\n return this;\n }\n /**\n * The swing value. Between 0-1 where 1 equal to the note + half the subdivision.\n */\n get swing() {\n return this._swingAmount;\n }\n set swing(amount) {\n // scale the values to a normal range\n this._swingAmount = amount;\n }\n /**\n * Set the subdivision which the swing will be applied to.\n * The default value is an 8th note. Value must be less\n * than a quarter note.\n */\n get swingSubdivision() {\n return new TicksClass(this.context, this._swingTicks).toNotation();\n }\n set swingSubdivision(subdivision) {\n this._swingTicks = this.toTicks(subdivision);\n }\n /**\n * The Transport's position in Bars:Beats:Sixteenths.\n * Setting the value will jump to that position right away.\n */\n get position() {\n const now = this.now();\n const ticks = this._clock.getTicksAtTime(now);\n return new TicksClass(this.context, ticks).toBarsBeatsSixteenths();\n }\n set position(progress) {\n const ticks = this.toTicks(progress);\n this.ticks = ticks;\n }\n /**\n * The Transport's position in seconds\n * Setting the value will jump to that position right away.\n */\n get seconds() {\n return this._clock.seconds;\n }\n set seconds(s) {\n const now = this.now();\n const ticks = this._clock.frequency.timeToTicks(s, now);\n this.ticks = ticks;\n }\n /**\n * The Transport's loop position as a normalized value. Always\n * returns 0 if the transport if loop is not true.\n */\n get progress() {\n if (this.loop) {\n const now = this.now();\n const ticks = this._clock.getTicksAtTime(now);\n return (ticks - this._loopStart) / (this._loopEnd - this._loopStart);\n }\n else {\n return 0;\n }\n }\n /**\n * The transports current tick position.\n */\n get ticks() {\n return this._clock.ticks;\n }\n set ticks(t) {\n if (this._clock.ticks !== t) {\n const now = this.now();\n // stop everything synced to the transport\n if (this.state === \"started\") {\n const ticks = this._clock.getTicksAtTime(now);\n // schedule to start on the next tick, #573\n const remainingTick = this._clock.frequency.getDurationOfTicks(Math.ceil(ticks) - ticks, now);\n const time = now + remainingTick;\n this.emit(\"stop\", time);\n this._clock.setTicksAtTime(t, time);\n // restart it with the new time\n this.emit(\"start\", time, this._clock.getSecondsAtTime(time));\n }\n else {\n this._clock.setTicksAtTime(t, now);\n }\n }\n }\n /**\n * Get the clock's ticks at the given time.\n * @param time When to get the tick value\n * @return The tick value at the given time.\n */\n getTicksAtTime(time) {\n return Math.round(this._clock.getTicksAtTime(time));\n }\n /**\n * Return the elapsed seconds at the given time.\n * @param time When to get the elapsed seconds\n * @return The number of elapsed seconds\n */\n getSecondsAtTime(time) {\n return this._clock.getSecondsAtTime(time);\n }\n /**\n * Pulses Per Quarter note. This is the smallest resolution\n * the Transport timing supports. This should be set once\n * on initialization and not set again. Changing this value\n * after other objects have been created can cause problems.\n */\n get PPQ() {\n return this._clock.frequency.multiplier;\n }\n set PPQ(ppq) {\n this._clock.frequency.multiplier = ppq;\n }\n //-------------------------------------\n // \tSYNCING\n //-------------------------------------\n /**\n * Returns the time aligned to the next subdivision\n * of the Transport. If the Transport is not started,\n * it will return 0.\n * Note: this will not work precisely during tempo ramps.\n * @param subdivision The subdivision to quantize to\n * @return The context time of the next subdivision.\n * @example\n * // the transport must be started, otherwise returns 0\n * Tone.Transport.start();\n * Tone.Transport.nextSubdivision(\"4n\");\n */\n nextSubdivision(subdivision) {\n subdivision = this.toTicks(subdivision);\n if (this.state !== \"started\") {\n // if the transport's not started, return 0\n return 0;\n }\n else {\n const now = this.now();\n // the remainder of the current ticks and the subdivision\n const transportPos = this.getTicksAtTime(now);\n const remainingTicks = subdivision - transportPos % subdivision;\n return this._clock.nextTickTime(remainingTicks, now);\n }\n }\n /**\n * Attaches the signal to the tempo control signal so that\n * any changes in the tempo will change the signal in the same\n * ratio.\n *\n * @param signal\n * @param ratio Optionally pass in the ratio between the two signals.\n * \t\t\tOtherwise it will be computed based on their current values.\n */\n syncSignal(signal, ratio) {\n if (!ratio) {\n // get the sync ratio\n const now = this.now();\n if (signal.getValueAtTime(now) !== 0) {\n const bpm = this.bpm.getValueAtTime(now);\n const computedFreq = 1 / (60 / bpm / this.PPQ);\n ratio = signal.getValueAtTime(now) / computedFreq;\n }\n else {\n ratio = 0;\n }\n }\n const ratioSignal = new Gain(ratio);\n // @ts-ignore\n this.bpm.connect(ratioSignal);\n // @ts-ignore\n ratioSignal.connect(signal._param);\n this._syncedSignals.push({\n initial: signal.value,\n ratio: ratioSignal,\n signal,\n });\n signal.value = 0;\n return this;\n }\n /**\n * Unsyncs a previously synced signal from the transport's control.\n * See Transport.syncSignal.\n */\n unsyncSignal(signal) {\n for (let i = this._syncedSignals.length - 1; i >= 0; i--) {\n const syncedSignal = this._syncedSignals[i];\n if (syncedSignal.signal === signal) {\n syncedSignal.ratio.dispose();\n syncedSignal.signal.value = syncedSignal.initial;\n this._syncedSignals.splice(i, 1);\n }\n }\n return this;\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this._clock.dispose();\n writable(this, \"bpm\");\n this._timeline.dispose();\n this._repeatedEvents.dispose();\n return this;\n }\n}\nEmitter.mixin(Transport);\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\nonContextInit(context => {\n context.transport = new Transport({ context });\n});\nonContextClose(context => {\n context.transport.dispose();\n});\n//# sourceMappingURL=Transport.js.map","import { Volume } from \"../component/channel/Volume\";\nimport \"../core/context/Destination\";\nimport \"../core/clock/Transport\";\nimport { ToneAudioNode } from \"../core/context/ToneAudioNode\";\nimport { defaultArg } from \"../core/util/Defaults\";\nimport { noOp, readOnly } from \"../core/util/Interface\";\nimport { StateTimeline } from \"../core/util/StateTimeline\";\nimport { isDefined, isUndef } from \"../core/util/TypeCheck\";\nimport { assert, assertContextRunning } from \"../core/util/Debug\";\nimport { GT } from \"../core/util/Math\";\n/**\n * Base class for sources.\n * start/stop of this.context.transport.\n *\n * ```\n * // Multiple state change events can be chained together,\n * // but must be set in the correct order and with ascending times\n * // OK\n * state.start().stop(\"+0.2\");\n * // OK\n * state.start().stop(\"+0.2\").start(\"+0.4\").stop(\"+0.7\")\n * // BAD\n * state.stop(\"+0.2\").start();\n * // BAD\n * state.start(\"+0.3\").stop(\"+0.2\");\n * ```\n */\nexport class Source extends ToneAudioNode {\n constructor(options) {\n super(options);\n /**\n * Sources have no inputs\n */\n this.input = undefined;\n /**\n * Keep track of the scheduled state.\n */\n this._state = new StateTimeline(\"stopped\");\n /**\n * The synced `start` callback function from the transport\n */\n this._synced = false;\n /**\n * Keep track of all of the scheduled event ids\n */\n this._scheduled = [];\n /**\n * Placeholder functions for syncing/unsyncing to transport\n */\n this._syncedStart = noOp;\n this._syncedStop = noOp;\n this._state.memory = 100;\n this._state.increasing = true;\n this._volume = this.output = new Volume({\n context: this.context,\n mute: options.mute,\n volume: options.volume,\n });\n this.volume = this._volume.volume;\n readOnly(this, \"volume\");\n this.onstop = options.onstop;\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n mute: false,\n onstop: noOp,\n volume: 0,\n });\n }\n /**\n * Returns the playback state of the source, either \"started\" or \"stopped\".\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/ahntone_c3.mp3\", () => {\n * \tplayer.start();\n * \tconsole.log(player.state);\n * }).toDestination();\n */\n get state() {\n if (this._synced) {\n if (this.context.transport.state === \"started\") {\n return this._state.getValueAtTime(this.context.transport.seconds);\n }\n else {\n return \"stopped\";\n }\n }\n else {\n return this._state.getValueAtTime(this.now());\n }\n }\n /**\n * Mute the output.\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * // mute the output\n * osc.mute = true;\n */\n get mute() {\n return this._volume.mute;\n }\n set mute(mute) {\n this._volume.mute = mute;\n }\n /**\n * Ensure that the scheduled time is not before the current time.\n * Should only be used when scheduled unsynced.\n */\n _clampToCurrentTime(time) {\n if (this._synced) {\n return time;\n }\n else {\n return Math.max(time, this.context.currentTime);\n }\n }\n /**\n * Start the source at the specified time. If no time is given,\n * start the source now.\n * @param time When the source should be started.\n * @example\n * const source = new Tone.Oscillator().toDestination();\n * source.start(\"+0.5\"); // starts the source 0.5 seconds from now\n */\n start(time, offset, duration) {\n let computedTime = isUndef(time) && this._synced ? this.context.transport.seconds : this.toSeconds(time);\n computedTime = this._clampToCurrentTime(computedTime);\n // if it's started, stop it and restart it\n if (!this._synced && this._state.getValueAtTime(computedTime) === \"started\") {\n // time should be strictly greater than the previous start time\n assert(GT(computedTime, this._state.get(computedTime).time), \"Start time must be strictly greater than previous start time\");\n this._state.cancel(computedTime);\n this._state.setStateAtTime(\"started\", computedTime);\n this.log(\"restart\", computedTime);\n this.restart(computedTime, offset, duration);\n }\n else {\n this.log(\"start\", computedTime);\n this._state.setStateAtTime(\"started\", computedTime);\n if (this._synced) {\n // add the offset time to the event\n const event = this._state.get(computedTime);\n if (event) {\n event.offset = this.toSeconds(defaultArg(offset, 0));\n event.duration = duration ? this.toSeconds(duration) : undefined;\n }\n const sched = this.context.transport.schedule(t => {\n this._start(t, offset, duration);\n }, computedTime);\n this._scheduled.push(sched);\n // if the transport is already started\n // and the time is greater than where the transport is\n if (this.context.transport.state === \"started\" &&\n this.context.transport.getSecondsAtTime(this.immediate()) > computedTime) {\n this._syncedStart(this.now(), this.context.transport.seconds);\n }\n }\n else {\n assertContextRunning(this.context);\n this._start(computedTime, offset, duration);\n }\n }\n return this;\n }\n /**\n * Stop the source at the specified time. If no time is given,\n * stop the source now.\n * @param time When the source should be stopped.\n * @example\n * const source = new Tone.Oscillator().toDestination();\n * source.start();\n * source.stop(\"+0.5\"); // stops the source 0.5 seconds from now\n */\n stop(time) {\n let computedTime = isUndef(time) && this._synced ? this.context.transport.seconds : this.toSeconds(time);\n computedTime = this._clampToCurrentTime(computedTime);\n if (this._state.getValueAtTime(computedTime) === \"started\" || isDefined(this._state.getNextState(\"started\", computedTime))) {\n this.log(\"stop\", computedTime);\n if (!this._synced) {\n this._stop(computedTime);\n }\n else {\n const sched = this.context.transport.schedule(this._stop.bind(this), computedTime);\n this._scheduled.push(sched);\n }\n this._state.cancel(computedTime);\n this._state.setStateAtTime(\"stopped\", computedTime);\n }\n return this;\n }\n /**\n * Restart the source.\n */\n restart(time, offset, duration) {\n time = this.toSeconds(time);\n if (this._state.getValueAtTime(time) === \"started\") {\n this._state.cancel(time);\n this._restart(time, offset, duration);\n }\n return this;\n }\n /**\n * Sync the source to the Transport so that all subsequent\n * calls to `start` and `stop` are synced to the TransportTime\n * instead of the AudioContext time.\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination();\n * // sync the source so that it plays between 0 and 0.3 on the Transport's timeline\n * osc.sync().start(0).stop(0.3);\n * // start the transport.\n * Tone.Transport.start();\n * // set it to loop once a second\n * Tone.Transport.loop = true;\n * Tone.Transport.loopEnd = 1;\n */\n sync() {\n if (!this._synced) {\n this._synced = true;\n this._syncedStart = (time, offset) => {\n if (offset > 0) {\n // get the playback state at that time\n const stateEvent = this._state.get(offset);\n // listen for start events which may occur in the middle of the sync'ed time\n if (stateEvent && stateEvent.state === \"started\" && stateEvent.time !== offset) {\n // get the offset\n const startOffset = offset - this.toSeconds(stateEvent.time);\n let duration;\n if (stateEvent.duration) {\n duration = this.toSeconds(stateEvent.duration) - startOffset;\n }\n this._start(time, this.toSeconds(stateEvent.offset) + startOffset, duration);\n }\n }\n };\n this._syncedStop = time => {\n const seconds = this.context.transport.getSecondsAtTime(Math.max(time - this.sampleTime, 0));\n if (this._state.getValueAtTime(seconds) === \"started\") {\n this._stop(time);\n }\n };\n this.context.transport.on(\"start\", this._syncedStart);\n this.context.transport.on(\"loopStart\", this._syncedStart);\n this.context.transport.on(\"stop\", this._syncedStop);\n this.context.transport.on(\"pause\", this._syncedStop);\n this.context.transport.on(\"loopEnd\", this._syncedStop);\n }\n return this;\n }\n /**\n * Unsync the source to the Transport. See Source.sync\n */\n unsync() {\n if (this._synced) {\n this.context.transport.off(\"stop\", this._syncedStop);\n this.context.transport.off(\"pause\", this._syncedStop);\n this.context.transport.off(\"loopEnd\", this._syncedStop);\n this.context.transport.off(\"start\", this._syncedStart);\n this.context.transport.off(\"loopStart\", this._syncedStart);\n }\n this._synced = false;\n // clear all of the scheduled ids\n this._scheduled.forEach(id => this.context.transport.clear(id));\n this._scheduled = [];\n this._state.cancel(0);\n // stop it also\n this._stop(0);\n return this;\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this.onstop = noOp;\n this.unsync();\n this._volume.dispose();\n this._state.dispose();\n return this;\n }\n}\n//# sourceMappingURL=Source.js.map","import { connect } from \"../../core/context/ToneAudioNode\";\nimport { Param } from \"../../core/context/Param\";\nimport { ToneAudioBuffer } from \"../../core/context/ToneAudioBuffer\";\nimport { defaultArg, optionsFromArguments } from \"../../core/util/Defaults\";\nimport { noOp } from \"../../core/util/Interface\";\nimport { isDefined } from \"../../core/util/TypeCheck\";\nimport { assert } from \"../../core/util/Debug\";\nimport { OneShotSource } from \"../OneShotSource\";\nimport { EQ, GTE, LT } from \"../../core/util/Math\";\n/**\n * Wrapper around the native BufferSourceNode.\n * @category Source\n */\nexport class ToneBufferSource extends OneShotSource {\n constructor() {\n super(optionsFromArguments(ToneBufferSource.getDefaults(), arguments, [\"url\", \"onload\"]));\n this.name = \"ToneBufferSource\";\n /**\n * The oscillator\n */\n this._source = this.context.createBufferSource();\n this._internalChannels = [this._source];\n /**\n * indicators if the source has started/stopped\n */\n this._sourceStarted = false;\n this._sourceStopped = false;\n const options = optionsFromArguments(ToneBufferSource.getDefaults(), arguments, [\"url\", \"onload\"]);\n connect(this._source, this._gainNode);\n this._source.onended = () => this._stopSource();\n /**\n * The playbackRate of the buffer\n */\n this.playbackRate = new Param({\n context: this.context,\n param: this._source.playbackRate,\n units: \"positive\",\n value: options.playbackRate,\n });\n // set some values initially\n this.loop = options.loop;\n this.loopStart = options.loopStart;\n this.loopEnd = options.loopEnd;\n this._buffer = new ToneAudioBuffer(options.url, options.onload, options.onerror);\n this._internalChannels.push(this._source);\n }\n static getDefaults() {\n return Object.assign(OneShotSource.getDefaults(), {\n url: new ToneAudioBuffer(),\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n onload: noOp,\n onerror: noOp,\n playbackRate: 1,\n });\n }\n /**\n * The fadeIn time of the amplitude envelope.\n */\n get fadeIn() {\n return this._fadeIn;\n }\n set fadeIn(t) {\n this._fadeIn = t;\n }\n /**\n * The fadeOut time of the amplitude envelope.\n */\n get fadeOut() {\n return this._fadeOut;\n }\n set fadeOut(t) {\n this._fadeOut = t;\n }\n /**\n * The curve applied to the fades, either \"linear\" or \"exponential\"\n */\n get curve() {\n return this._curve;\n }\n set curve(t) {\n this._curve = t;\n }\n /**\n * Start the buffer\n * @param time When the player should start.\n * @param offset The offset from the beginning of the sample to start at.\n * @param duration How long the sample should play. If no duration is given, it will default to the full length of the sample (minus any offset)\n * @param gain The gain to play the buffer back at.\n */\n start(time, offset, duration, gain = 1) {\n assert(this.buffer.loaded, \"buffer is either not set or not loaded\");\n const computedTime = this.toSeconds(time);\n // apply the gain envelope\n this._startGain(computedTime, gain);\n // if it's a loop the default offset is the loopstart point\n if (this.loop) {\n offset = defaultArg(offset, this.loopStart);\n }\n else {\n // otherwise the default offset is 0\n offset = defaultArg(offset, 0);\n }\n // make sure the offset is not less than 0\n let computedOffset = Math.max(this.toSeconds(offset), 0);\n // start the buffer source\n if (this.loop) {\n // modify the offset if it's greater than the loop time\n const loopEnd = this.toSeconds(this.loopEnd) || this.buffer.duration;\n const loopStart = this.toSeconds(this.loopStart);\n const loopDuration = loopEnd - loopStart;\n // move the offset back\n if (GTE(computedOffset, loopEnd)) {\n computedOffset = ((computedOffset - loopStart) % loopDuration) + loopStart;\n }\n // when the offset is very close to the duration, set it to 0\n if (EQ(computedOffset, this.buffer.duration)) {\n computedOffset = 0;\n }\n }\n // this.buffer.loaded would have return false if the AudioBuffer was undefined\n this._source.buffer = this.buffer.get();\n this._source.loopEnd = this.toSeconds(this.loopEnd) || this.buffer.duration;\n if (LT(computedOffset, this.buffer.duration)) {\n this._sourceStarted = true;\n this._source.start(computedTime, computedOffset);\n }\n // if a duration is given, schedule a stop\n if (isDefined(duration)) {\n let computedDur = this.toSeconds(duration);\n // make sure it's never negative\n computedDur = Math.max(computedDur, 0);\n this.stop(computedTime + computedDur);\n }\n return this;\n }\n _stopSource(time) {\n if (!this._sourceStopped && this._sourceStarted) {\n this._sourceStopped = true;\n this._source.stop(this.toSeconds(time));\n this._onended();\n }\n }\n /**\n * If loop is true, the loop will start at this position.\n */\n get loopStart() {\n return this._source.loopStart;\n }\n set loopStart(loopStart) {\n this._source.loopStart = this.toSeconds(loopStart);\n }\n /**\n * If loop is true, the loop will end at this position.\n */\n get loopEnd() {\n return this._source.loopEnd;\n }\n set loopEnd(loopEnd) {\n this._source.loopEnd = this.toSeconds(loopEnd);\n }\n /**\n * The audio buffer belonging to the player.\n */\n get buffer() {\n return this._buffer;\n }\n set buffer(buffer) {\n this._buffer.set(buffer);\n }\n /**\n * If the buffer should loop once it's over.\n */\n get loop() {\n return this._source.loop;\n }\n set loop(loop) {\n this._source.loop = loop;\n if (this._sourceStarted) {\n this.cancelStop();\n }\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this._source.onended = null;\n this._source.disconnect();\n this._buffer.dispose();\n this.playbackRate.dispose();\n return this;\n }\n}\n//# sourceMappingURL=ToneBufferSource.js.map","import { __awaiter } from \"tslib\";\nimport { OfflineContext } from \"../../core/context/OfflineContext\";\n/**\n * Render a segment of the oscillator to an offline context and return the results as an array\n */\nexport function generateWaveform(instance, length) {\n return __awaiter(this, void 0, void 0, function* () {\n const duration = length / instance.context.sampleRate;\n const context = new OfflineContext(1, duration, instance.context.sampleRate);\n const clone = new instance.constructor(Object.assign(instance.get(), {\n // should do 2 iterations\n frequency: 2 / duration,\n // zero out the detune\n detune: 0,\n context\n })).toDestination();\n clone.start(0);\n const buffer = yield context.render();\n return buffer.getChannelData(0);\n });\n}\n//# sourceMappingURL=OscillatorInterface.js.map","import { connect } from \"../../core/context/ToneAudioNode\";\nimport { Param } from \"../../core/context/Param\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { OneShotSource } from \"../OneShotSource\";\nimport { readOnly } from \"../../core/util/Interface\";\n/**\n * Wrapper around the native fire-and-forget OscillatorNode.\n * Adds the ability to reschedule the stop method.\n * ***[[Oscillator]] is better for most use-cases***\n * @category Source\n */\nexport class ToneOscillatorNode extends OneShotSource {\n constructor() {\n super(optionsFromArguments(ToneOscillatorNode.getDefaults(), arguments, [\"frequency\", \"type\"]));\n this.name = \"ToneOscillatorNode\";\n /**\n * The oscillator\n */\n this._oscillator = this.context.createOscillator();\n this._internalChannels = [this._oscillator];\n const options = optionsFromArguments(ToneOscillatorNode.getDefaults(), arguments, [\"frequency\", \"type\"]);\n connect(this._oscillator, this._gainNode);\n this.type = options.type;\n this.frequency = new Param({\n context: this.context,\n param: this._oscillator.frequency,\n units: \"frequency\",\n value: options.frequency,\n });\n this.detune = new Param({\n context: this.context,\n param: this._oscillator.detune,\n units: \"cents\",\n value: options.detune,\n });\n readOnly(this, [\"frequency\", \"detune\"]);\n }\n static getDefaults() {\n return Object.assign(OneShotSource.getDefaults(), {\n detune: 0,\n frequency: 440,\n type: \"sine\",\n });\n }\n /**\n * Start the oscillator node at the given time\n * @param time When to start the oscillator\n */\n start(time) {\n const computedTime = this.toSeconds(time);\n this.log(\"start\", computedTime);\n this._startGain(computedTime);\n this._oscillator.start(computedTime);\n return this;\n }\n _stopSource(time) {\n this._oscillator.stop(time);\n }\n /**\n * Sets an arbitrary custom periodic waveform given a PeriodicWave.\n * @param periodicWave PeriodicWave should be created with context.createPeriodicWave\n */\n setPeriodicWave(periodicWave) {\n this._oscillator.setPeriodicWave(periodicWave);\n return this;\n }\n /**\n * The oscillator type. Either 'sine', 'sawtooth', 'square', or 'triangle'\n */\n get type() {\n return this._oscillator.type;\n }\n set type(type) {\n this._oscillator.type = type;\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n if (this.state === \"started\") {\n this.stop();\n }\n this._oscillator.disconnect();\n this.frequency.dispose();\n this.detune.dispose();\n return this;\n }\n}\n//# sourceMappingURL=ToneOscillatorNode.js.map","import { __awaiter } from \"tslib\";\nimport { deepEquals, optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { isDefined } from \"../../core/util/TypeCheck\";\nimport { Signal } from \"../../signal/Signal\";\nimport { Source } from \"../Source\";\nimport { generateWaveform } from \"./OscillatorInterface\";\nimport { ToneOscillatorNode } from \"./ToneOscillatorNode\";\nimport { assertRange } from \"../../core/util/Debug\";\nimport { clamp } from \"../../core/util/Math\";\n/**\n * Oscillator supports a number of features including\n * phase rotation, multiple oscillator types (see Oscillator.type),\n * and Transport syncing (see Oscillator.syncFrequency).\n *\n * @example\n * // make and start a 440hz sine tone\n * const osc = new Tone.Oscillator(440, \"sine\").toDestination().start();\n * @category Source\n */\nexport class Oscillator extends Source {\n constructor() {\n super(optionsFromArguments(Oscillator.getDefaults(), arguments, [\"frequency\", \"type\"]));\n this.name = \"Oscillator\";\n /**\n * the main oscillator\n */\n this._oscillator = null;\n const options = optionsFromArguments(Oscillator.getDefaults(), arguments, [\"frequency\", \"type\"]);\n this.frequency = new Signal({\n context: this.context,\n units: \"frequency\",\n value: options.frequency,\n });\n readOnly(this, \"frequency\");\n this.detune = new Signal({\n context: this.context,\n units: \"cents\",\n value: options.detune,\n });\n readOnly(this, \"detune\");\n this._partials = options.partials;\n this._partialCount = options.partialCount;\n this._type = options.type;\n if (options.partialCount && options.type !== \"custom\") {\n this._type = this.baseType + options.partialCount.toString();\n }\n this.phase = options.phase;\n }\n static getDefaults() {\n return Object.assign(Source.getDefaults(), {\n detune: 0,\n frequency: 440,\n partialCount: 0,\n partials: [],\n phase: 0,\n type: \"sine\",\n });\n }\n /**\n * start the oscillator\n */\n _start(time) {\n const computedTime = this.toSeconds(time);\n // new oscillator with previous values\n const oscillator = new ToneOscillatorNode({\n context: this.context,\n onended: () => this.onstop(this),\n });\n this._oscillator = oscillator;\n if (this._wave) {\n this._oscillator.setPeriodicWave(this._wave);\n }\n else {\n this._oscillator.type = this._type;\n }\n // connect the control signal to the oscillator frequency & detune\n this._oscillator.connect(this.output);\n this.frequency.connect(this._oscillator.frequency);\n this.detune.connect(this._oscillator.detune);\n // start the oscillator\n this._oscillator.start(computedTime);\n }\n /**\n * stop the oscillator\n */\n _stop(time) {\n const computedTime = this.toSeconds(time);\n if (this._oscillator) {\n this._oscillator.stop(computedTime);\n }\n }\n /**\n * Restart the oscillator. Does not stop the oscillator, but instead\n * just cancels any scheduled 'stop' from being invoked.\n */\n _restart(time) {\n const computedTime = this.toSeconds(time);\n this.log(\"restart\", computedTime);\n if (this._oscillator) {\n this._oscillator.cancelStop();\n }\n this._state.cancel(computedTime);\n return this;\n }\n /**\n * Sync the signal to the Transport's bpm. Any changes to the transports bpm,\n * will also affect the oscillators frequency.\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * osc.frequency.value = 440;\n * // the ratio between the bpm and the frequency will be maintained\n * osc.syncFrequency();\n * // double the tempo\n * Tone.Transport.bpm.value *= 2;\n * // the frequency of the oscillator is doubled to 880\n */\n syncFrequency() {\n this.context.transport.syncSignal(this.frequency);\n return this;\n }\n /**\n * Unsync the oscillator's frequency from the Transport.\n * See Oscillator.syncFrequency\n */\n unsyncFrequency() {\n this.context.transport.unsyncSignal(this.frequency);\n return this;\n }\n /**\n * Get a cached periodic wave. Avoids having to recompute\n * the oscillator values when they have already been computed\n * with the same values.\n */\n _getCachedPeriodicWave() {\n if (this._type === \"custom\") {\n const oscProps = Oscillator._periodicWaveCache.find(description => {\n return description.phase === this._phase &&\n deepEquals(description.partials, this._partials);\n });\n return oscProps;\n }\n else {\n const oscProps = Oscillator._periodicWaveCache.find(description => {\n return description.type === this._type &&\n description.phase === this._phase;\n });\n this._partialCount = oscProps ? oscProps.partialCount : this._partialCount;\n return oscProps;\n }\n }\n get type() {\n return this._type;\n }\n set type(type) {\n this._type = type;\n const isBasicType = [\"sine\", \"square\", \"sawtooth\", \"triangle\"].indexOf(type) !== -1;\n if (this._phase === 0 && isBasicType) {\n this._wave = undefined;\n this._partialCount = 0;\n // just go with the basic approach\n if (this._oscillator !== null) {\n // already tested that it's a basic type\n this._oscillator.type = type;\n }\n }\n else {\n // first check if the value is cached\n const cache = this._getCachedPeriodicWave();\n if (isDefined(cache)) {\n const { partials, wave } = cache;\n this._wave = wave;\n this._partials = partials;\n if (this._oscillator !== null) {\n this._oscillator.setPeriodicWave(this._wave);\n }\n }\n else {\n const [real, imag] = this._getRealImaginary(type, this._phase);\n const periodicWave = this.context.createPeriodicWave(real, imag);\n this._wave = periodicWave;\n if (this._oscillator !== null) {\n this._oscillator.setPeriodicWave(this._wave);\n }\n // set the cache\n Oscillator._periodicWaveCache.push({\n imag,\n partialCount: this._partialCount,\n partials: this._partials,\n phase: this._phase,\n real,\n type: this._type,\n wave: this._wave,\n });\n if (Oscillator._periodicWaveCache.length > 100) {\n Oscillator._periodicWaveCache.shift();\n }\n }\n }\n }\n get baseType() {\n return this._type.replace(this.partialCount.toString(), \"\");\n }\n set baseType(baseType) {\n if (this.partialCount && this._type !== \"custom\" && baseType !== \"custom\") {\n this.type = baseType + this.partialCount;\n }\n else {\n this.type = baseType;\n }\n }\n get partialCount() {\n return this._partialCount;\n }\n set partialCount(p) {\n assertRange(p, 0);\n let type = this._type;\n const partial = /^(sine|triangle|square|sawtooth)(\\d+)$/.exec(this._type);\n if (partial) {\n type = partial[1];\n }\n if (this._type !== \"custom\") {\n if (p === 0) {\n this.type = type;\n }\n else {\n this.type = type + p.toString();\n }\n }\n else {\n // extend or shorten the partials array\n const fullPartials = new Float32Array(p);\n // copy over the partials array\n this._partials.forEach((v, i) => fullPartials[i] = v);\n this._partials = Array.from(fullPartials);\n this.type = this._type;\n }\n }\n /**\n * Returns the real and imaginary components based\n * on the oscillator type.\n * @returns [real: Float32Array, imaginary: Float32Array]\n */\n _getRealImaginary(type, phase) {\n const fftSize = 4096;\n let periodicWaveSize = fftSize / 2;\n const real = new Float32Array(periodicWaveSize);\n const imag = new Float32Array(periodicWaveSize);\n let partialCount = 1;\n if (type === \"custom\") {\n partialCount = this._partials.length + 1;\n this._partialCount = this._partials.length;\n periodicWaveSize = partialCount;\n // if the partial count is 0, don't bother doing any computation\n if (this._partials.length === 0) {\n return [real, imag];\n }\n }\n else {\n const partial = /^(sine|triangle|square|sawtooth)(\\d+)$/.exec(type);\n if (partial) {\n partialCount = parseInt(partial[2], 10) + 1;\n this._partialCount = parseInt(partial[2], 10);\n type = partial[1];\n partialCount = Math.max(partialCount, 2);\n periodicWaveSize = partialCount;\n }\n else {\n this._partialCount = 0;\n }\n this._partials = [];\n }\n for (let n = 1; n < periodicWaveSize; ++n) {\n const piFactor = 2 / (n * Math.PI);\n let b;\n switch (type) {\n case \"sine\":\n b = (n <= partialCount) ? 1 : 0;\n this._partials[n - 1] = b;\n break;\n case \"square\":\n b = (n & 1) ? 2 * piFactor : 0;\n this._partials[n - 1] = b;\n break;\n case \"sawtooth\":\n b = piFactor * ((n & 1) ? 1 : -1);\n this._partials[n - 1] = b;\n break;\n case \"triangle\":\n if (n & 1) {\n b = 2 * (piFactor * piFactor) * ((((n - 1) >> 1) & 1) ? -1 : 1);\n }\n else {\n b = 0;\n }\n this._partials[n - 1] = b;\n break;\n case \"custom\":\n b = this._partials[n - 1];\n break;\n default:\n throw new TypeError(\"Oscillator: invalid type: \" + type);\n }\n if (b !== 0) {\n real[n] = -b * Math.sin(phase * n);\n imag[n] = b * Math.cos(phase * n);\n }\n else {\n real[n] = 0;\n imag[n] = 0;\n }\n }\n return [real, imag];\n }\n /**\n * Compute the inverse FFT for a given phase.\n */\n _inverseFFT(real, imag, phase) {\n let sum = 0;\n const len = real.length;\n for (let i = 0; i < len; i++) {\n sum += real[i] * Math.cos(i * phase) + imag[i] * Math.sin(i * phase);\n }\n return sum;\n }\n /**\n * Returns the initial value of the oscillator when stopped.\n * E.g. a \"sine\" oscillator with phase = 90 would return an initial value of -1.\n */\n getInitialValue() {\n const [real, imag] = this._getRealImaginary(this._type, 0);\n let maxValue = 0;\n const twoPi = Math.PI * 2;\n const testPositions = 32;\n // check for peaks in 16 places\n for (let i = 0; i < testPositions; i++) {\n maxValue = Math.max(this._inverseFFT(real, imag, (i / testPositions) * twoPi), maxValue);\n }\n return clamp(-this._inverseFFT(real, imag, this._phase) / maxValue, -1, 1);\n }\n get partials() {\n return this._partials.slice(0, this.partialCount);\n }\n set partials(partials) {\n this._partials = partials;\n this._partialCount = this._partials.length;\n if (partials.length) {\n this.type = \"custom\";\n }\n }\n get phase() {\n return this._phase * (180 / Math.PI);\n }\n set phase(phase) {\n this._phase = phase * Math.PI / 180;\n // reset the type\n this.type = this._type;\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n dispose() {\n super.dispose();\n if (this._oscillator !== null) {\n this._oscillator.dispose();\n }\n this._wave = undefined;\n this.frequency.dispose();\n this.detune.dispose();\n return this;\n }\n}\n/**\n * Cache the periodic waves to avoid having to redo computations\n */\nOscillator._periodicWaveCache = [];\n//# sourceMappingURL=Oscillator.js.map","import { optionsFromArguments } from \"../core/util/Defaults\";\nimport { ToneAudioNode } from \"../core/context/ToneAudioNode\";\nimport { connectSignal } from \"./Signal\";\n/**\n * A signal operator has an input and output and modifies the signal.\n */\nexport class SignalOperator extends ToneAudioNode {\n constructor() {\n super(Object.assign(optionsFromArguments(SignalOperator.getDefaults(), arguments, [\"context\"])));\n }\n connect(destination, outputNum = 0, inputNum = 0) {\n connectSignal(this, destination, outputNum, inputNum);\n return this;\n }\n}\n//# sourceMappingURL=SignalOperator.js.map","import { optionsFromArguments } from \"../core/util/Defaults\";\nimport { isArray, isFunction } from \"../core/util/TypeCheck\";\nimport { assert } from \"../core/util/Debug\";\nimport { Signal } from \"./Signal\";\nimport { SignalOperator } from \"./SignalOperator\";\n/**\n * Wraps the native Web Audio API\n * [WaveShaperNode](http://webaudio.github.io/web-audio-api/#the-waveshapernode-interface).\n *\n * @example\n * const osc = new Tone.Oscillator().toDestination().start();\n * // multiply the output of the signal by 2 using the waveshaper's function\n * const timesTwo = new Tone.WaveShaper((val) => val * 2, 2048).connect(osc.frequency);\n * const signal = new Tone.Signal(440).connect(timesTwo);\n * @category Signal\n */\nexport class WaveShaper extends SignalOperator {\n constructor() {\n super(Object.assign(optionsFromArguments(WaveShaper.getDefaults(), arguments, [\"mapping\", \"length\"])));\n this.name = \"WaveShaper\";\n /**\n * the waveshaper node\n */\n this._shaper = this.context.createWaveShaper();\n /**\n * The input to the waveshaper node.\n */\n this.input = this._shaper;\n /**\n * The output from the waveshaper node\n */\n this.output = this._shaper;\n const options = optionsFromArguments(WaveShaper.getDefaults(), arguments, [\"mapping\", \"length\"]);\n if (isArray(options.mapping) || options.mapping instanceof Float32Array) {\n this.curve = Float32Array.from(options.mapping);\n }\n else if (isFunction(options.mapping)) {\n this.setMap(options.mapping, options.length);\n }\n }\n static getDefaults() {\n return Object.assign(Signal.getDefaults(), {\n length: 1024,\n });\n }\n /**\n * Uses a mapping function to set the value of the curve.\n * @param mapping The function used to define the values.\n * The mapping function take two arguments:\n * the first is the value at the current position\n * which goes from -1 to 1 over the number of elements\n * in the curve array. The second argument is the array position.\n * @example\n * const shaper = new Tone.WaveShaper();\n * // map the input signal from [-1, 1] to [0, 10]\n * shaper.setMap((val, index) => (val + 1) * 5);\n */\n setMap(mapping, length = 1024) {\n const array = new Float32Array(length);\n for (let i = 0, len = length; i < len; i++) {\n const normalized = (i / (len - 1)) * 2 - 1;\n array[i] = mapping(normalized, i);\n }\n this.curve = array;\n return this;\n }\n /**\n * The array to set as the waveshaper curve. For linear curves\n * array length does not make much difference, but for complex curves\n * longer arrays will provide smoother interpolation.\n */\n get curve() {\n return this._shaper.curve;\n }\n set curve(mapping) {\n this._shaper.curve = mapping;\n }\n /**\n * Specifies what type of oversampling (if any) should be used when\n * applying the shaping curve. Can either be \"none\", \"2x\" or \"4x\".\n */\n get oversample() {\n return this._shaper.oversample;\n }\n set oversample(oversampling) {\n const isOverSampleType = [\"none\", \"2x\", \"4x\"].some(str => str.includes(oversampling));\n assert(isOverSampleType, \"oversampling must be either 'none', '2x', or '4x'\");\n this._shaper.oversample = oversampling;\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this._shaper.disconnect();\n return this;\n }\n}\n//# sourceMappingURL=WaveShaper.js.map","import { SignalOperator } from \"./SignalOperator\";\nimport { WaveShaper } from \"./WaveShaper\";\n/**\n * AudioToGain converts an input in AudioRange [-1,1] to NormalRange [0,1].\n * See [[GainToAudio]].\n * @category Signal\n */\nexport class AudioToGain extends SignalOperator {\n constructor() {\n super(...arguments);\n this.name = \"AudioToGain\";\n /**\n * The node which converts the audio ranges\n */\n this._norm = new WaveShaper({\n context: this.context,\n mapping: x => (x + 1) / 2,\n });\n /**\n * The AudioRange input [-1, 1]\n */\n this.input = this._norm;\n /**\n * The GainRange output [0, 1]\n */\n this.output = this._norm;\n }\n /**\n * clean up\n */\n dispose() {\n super.dispose();\n this._norm.dispose();\n return this;\n }\n}\n//# sourceMappingURL=AudioToGain.js.map","import { Gain } from \"../core/context/Gain\";\nimport { optionsFromArguments } from \"../core/util/Defaults\";\nimport { Signal } from \"./Signal\";\n/**\n * Multiply two incoming signals. Or, if a number is given in the constructor,\n * multiplies the incoming signal by that value.\n *\n * @example\n * // multiply two signals\n * const mult = new Tone.Multiply();\n * const sigA = new Tone.Signal(3);\n * const sigB = new Tone.Signal(4);\n * sigA.connect(mult);\n * sigB.connect(mult.factor);\n * // output of mult is 12.\n * @example\n * // multiply a signal and a number\n * const mult = new Tone.Multiply(10);\n * const sig = new Tone.Signal(2).connect(mult);\n * // the output of mult is 20.\n * @category Signal\n */\nexport class Multiply extends Signal {\n constructor() {\n super(Object.assign(optionsFromArguments(Multiply.getDefaults(), arguments, [\"value\"])));\n this.name = \"Multiply\";\n /**\n * Indicates if the value should be overridden on connection\n */\n this.override = false;\n const options = optionsFromArguments(Multiply.getDefaults(), arguments, [\"value\"]);\n this._mult = this.input = this.output = new Gain({\n context: this.context,\n minValue: options.minValue,\n maxValue: options.maxValue,\n });\n this.factor = this._param = this._mult.gain;\n this.factor.setValueAtTime(options.value, 0);\n }\n static getDefaults() {\n return Object.assign(Signal.getDefaults(), {\n value: 0,\n });\n }\n dispose() {\n super.dispose();\n this._mult.dispose();\n return this;\n }\n}\n//# sourceMappingURL=Multiply.js.map","import { __awaiter } from \"tslib\";\nimport { Gain } from \"../../core/context/Gain\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { AudioToGain } from \"../../signal/AudioToGain\";\nimport { Multiply } from \"../../signal/Multiply\";\nimport { Source } from \"../Source\";\nimport { Oscillator } from \"./Oscillator\";\nimport { generateWaveform } from \"./OscillatorInterface\";\n/**\n * An amplitude modulated oscillator node. It is implemented with\n * two oscillators, one which modulators the other's amplitude\n * through a gain node.\n * ```\n * +-------------+ +----------+\n * | Carrier Osc +>------> GainNode |\n * +-------------+ | +--->Output\n * +---> gain |\n * +---------------+ | +----------+\n * | Modulator Osc +>---+\n * +---------------+\n * ```\n * @example\n * return Tone.Offline(() => {\n * \tconst amOsc = new Tone.AMOscillator(30, \"sine\", \"square\").toDestination().start();\n * }, 0.2, 1);\n * @category Source\n */\nexport class AMOscillator extends Source {\n constructor() {\n super(optionsFromArguments(AMOscillator.getDefaults(), arguments, [\"frequency\", \"type\", \"modulationType\"]));\n this.name = \"AMOscillator\";\n /**\n * convert the -1,1 output to 0,1\n */\n this._modulationScale = new AudioToGain({ context: this.context });\n /**\n * the node where the modulation happens\n */\n this._modulationNode = new Gain({\n context: this.context,\n });\n const options = optionsFromArguments(AMOscillator.getDefaults(), arguments, [\"frequency\", \"type\", \"modulationType\"]);\n this._carrier = new Oscillator({\n context: this.context,\n detune: options.detune,\n frequency: options.frequency,\n onstop: () => this.onstop(this),\n phase: options.phase,\n type: options.type,\n });\n this.frequency = this._carrier.frequency,\n this.detune = this._carrier.detune;\n this._modulator = new Oscillator({\n context: this.context,\n phase: options.phase,\n type: options.modulationType,\n });\n this.harmonicity = new Multiply({\n context: this.context,\n units: \"positive\",\n value: options.harmonicity,\n });\n // connections\n this.frequency.chain(this.harmonicity, this._modulator.frequency);\n this._modulator.chain(this._modulationScale, this._modulationNode.gain);\n this._carrier.chain(this._modulationNode, this.output);\n readOnly(this, [\"frequency\", \"detune\", \"harmonicity\"]);\n }\n static getDefaults() {\n return Object.assign(Oscillator.getDefaults(), {\n harmonicity: 1,\n modulationType: \"square\",\n });\n }\n /**\n * start the oscillator\n */\n _start(time) {\n this._modulator.start(time);\n this._carrier.start(time);\n }\n /**\n * stop the oscillator\n */\n _stop(time) {\n this._modulator.stop(time);\n this._carrier.stop(time);\n }\n _restart(time) {\n this._modulator.restart(time);\n this._carrier.restart(time);\n }\n /**\n * The type of the carrier oscillator\n */\n get type() {\n return this._carrier.type;\n }\n set type(type) {\n this._carrier.type = type;\n }\n get baseType() {\n return this._carrier.baseType;\n }\n set baseType(baseType) {\n this._carrier.baseType = baseType;\n }\n get partialCount() {\n return this._carrier.partialCount;\n }\n set partialCount(partialCount) {\n this._carrier.partialCount = partialCount;\n }\n /**\n * The type of the modulator oscillator\n */\n get modulationType() {\n return this._modulator.type;\n }\n set modulationType(type) {\n this._modulator.type = type;\n }\n get phase() {\n return this._carrier.phase;\n }\n set phase(phase) {\n this._carrier.phase = phase;\n this._modulator.phase = phase;\n }\n get partials() {\n return this._carrier.partials;\n }\n set partials(partials) {\n this._carrier.partials = partials;\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this.frequency.dispose();\n this.detune.dispose();\n this.harmonicity.dispose();\n this._carrier.dispose();\n this._modulator.dispose();\n this._modulationNode.dispose();\n this._modulationScale.dispose();\n return this;\n }\n}\n//# sourceMappingURL=AMOscillator.js.map","import { __awaiter } from \"tslib\";\nimport { Gain } from \"../../core/context/Gain\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { Multiply } from \"../../signal/Multiply\";\nimport { Signal } from \"../../signal/Signal\";\nimport { Source } from \"../Source\";\nimport { Oscillator } from \"./Oscillator\";\nimport { generateWaveform } from \"./OscillatorInterface\";\n/**\n * FMOscillator implements a frequency modulation synthesis\n * ```\n * +-------------+\n * +---------------+ +-------------+ | Carrier Osc |\n * | Modulator Osc +>-------> GainNode | | +--->Output\n * +---------------+ | +>----> frequency |\n * +--> gain | +-------------+\n * | +-------------+\n * +-----------------+ |\n * | modulationIndex +>--+\n * +-----------------+\n * ```\n *\n * @example\n * return Tone.Offline(() => {\n * \tconst fmOsc = new Tone.FMOscillator({\n * \t\tfrequency: 200,\n * \t\ttype: \"square\",\n * \t\tmodulationType: \"triangle\",\n * \t\tharmonicity: 0.2,\n * \t\tmodulationIndex: 3\n * \t}).toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class FMOscillator extends Source {\n constructor() {\n super(optionsFromArguments(FMOscillator.getDefaults(), arguments, [\"frequency\", \"type\", \"modulationType\"]));\n this.name = \"FMOscillator\";\n /**\n * the node where the modulation happens\n */\n this._modulationNode = new Gain({\n context: this.context,\n gain: 0,\n });\n const options = optionsFromArguments(FMOscillator.getDefaults(), arguments, [\"frequency\", \"type\", \"modulationType\"]);\n this._carrier = new Oscillator({\n context: this.context,\n detune: options.detune,\n frequency: 0,\n onstop: () => this.onstop(this),\n phase: options.phase,\n type: options.type,\n });\n this.detune = this._carrier.detune;\n this.frequency = new Signal({\n context: this.context,\n units: \"frequency\",\n value: options.frequency,\n });\n this._modulator = new Oscillator({\n context: this.context,\n phase: options.phase,\n type: options.modulationType,\n });\n this.harmonicity = new Multiply({\n context: this.context,\n units: \"positive\",\n value: options.harmonicity,\n });\n this.modulationIndex = new Multiply({\n context: this.context,\n units: \"positive\",\n value: options.modulationIndex,\n });\n // connections\n this.frequency.connect(this._carrier.frequency);\n this.frequency.chain(this.harmonicity, this._modulator.frequency);\n this.frequency.chain(this.modulationIndex, this._modulationNode);\n this._modulator.connect(this._modulationNode.gain);\n this._modulationNode.connect(this._carrier.frequency);\n this._carrier.connect(this.output);\n this.detune.connect(this._modulator.detune);\n readOnly(this, [\"modulationIndex\", \"frequency\", \"detune\", \"harmonicity\"]);\n }\n static getDefaults() {\n return Object.assign(Oscillator.getDefaults(), {\n harmonicity: 1,\n modulationIndex: 2,\n modulationType: \"square\",\n });\n }\n /**\n * start the oscillator\n */\n _start(time) {\n this._modulator.start(time);\n this._carrier.start(time);\n }\n /**\n * stop the oscillator\n */\n _stop(time) {\n this._modulator.stop(time);\n this._carrier.stop(time);\n }\n _restart(time) {\n this._modulator.restart(time);\n this._carrier.restart(time);\n return this;\n }\n get type() {\n return this._carrier.type;\n }\n set type(type) {\n this._carrier.type = type;\n }\n get baseType() {\n return this._carrier.baseType;\n }\n set baseType(baseType) {\n this._carrier.baseType = baseType;\n }\n get partialCount() {\n return this._carrier.partialCount;\n }\n set partialCount(partialCount) {\n this._carrier.partialCount = partialCount;\n }\n /**\n * The type of the modulator oscillator\n */\n get modulationType() {\n return this._modulator.type;\n }\n set modulationType(type) {\n this._modulator.type = type;\n }\n get phase() {\n return this._carrier.phase;\n }\n set phase(phase) {\n this._carrier.phase = phase;\n this._modulator.phase = phase;\n }\n get partials() {\n return this._carrier.partials;\n }\n set partials(partials) {\n this._carrier.partials = partials;\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this.frequency.dispose();\n this.harmonicity.dispose();\n this._carrier.dispose();\n this._modulator.dispose();\n this._modulationNode.dispose();\n this.modulationIndex.dispose();\n return this;\n }\n}\n//# sourceMappingURL=FMOscillator.js.map","import { __awaiter } from \"tslib\";\nimport { Gain } from \"../../core/context/Gain\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { Signal } from \"../../signal/Signal\";\nimport { WaveShaper } from \"../../signal/WaveShaper\";\nimport { Source } from \"../Source\";\nimport { Oscillator } from \"./Oscillator\";\nimport { generateWaveform } from \"./OscillatorInterface\";\n/**\n * PulseOscillator is an oscillator with control over pulse width,\n * also known as the duty cycle. At 50% duty cycle (width = 0) the wave is\n * a square wave.\n * [Read more](https://wigglewave.wordpress.com/2014/08/16/pulse-waveforms-and-harmonics/).\n * ```\n * width = -0.25 width = 0.0 width = 0.25\n *\n * +-----+ +-------+ + +-------+ +-+\n * | | | | | | |\n * | | | | | | |\n * +-+ +-------+ + +-------+ +-----+\n *\n *\n * width = -0.5 width = 0.5\n *\n * +---+ +-------+ +---+\n * | | | |\n * | | | |\n * +---+ +-------+ +---+\n *\n *\n * width = -0.75 width = 0.75\n *\n * +-+ +-------+ +-----+\n * | | | |\n * | | | |\n * +-----+ +-------+ +-+\n * ```\n * @example\n * return Tone.Offline(() => {\n * \tconst pulse = new Tone.PulseOscillator(50, 0.4).toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class PulseOscillator extends Source {\n constructor() {\n super(optionsFromArguments(PulseOscillator.getDefaults(), arguments, [\"frequency\", \"width\"]));\n this.name = \"PulseOscillator\";\n /**\n * gate the width amount\n */\n this._widthGate = new Gain({\n context: this.context,\n gain: 0,\n });\n /**\n * Threshold the signal to turn it into a square\n */\n this._thresh = new WaveShaper({\n context: this.context,\n mapping: val => val <= 0 ? -1 : 1,\n });\n const options = optionsFromArguments(PulseOscillator.getDefaults(), arguments, [\"frequency\", \"width\"]);\n this.width = new Signal({\n context: this.context,\n units: \"audioRange\",\n value: options.width,\n });\n this._triangle = new Oscillator({\n context: this.context,\n detune: options.detune,\n frequency: options.frequency,\n onstop: () => this.onstop(this),\n phase: options.phase,\n type: \"triangle\",\n });\n this.frequency = this._triangle.frequency;\n this.detune = this._triangle.detune;\n // connections\n this._triangle.chain(this._thresh, this.output);\n this.width.chain(this._widthGate, this._thresh);\n readOnly(this, [\"width\", \"frequency\", \"detune\"]);\n }\n static getDefaults() {\n return Object.assign(Source.getDefaults(), {\n detune: 0,\n frequency: 440,\n phase: 0,\n type: \"pulse\",\n width: 0.2,\n });\n }\n /**\n * start the oscillator\n */\n _start(time) {\n time = this.toSeconds(time);\n this._triangle.start(time);\n this._widthGate.gain.setValueAtTime(1, time);\n }\n /**\n * stop the oscillator\n */\n _stop(time) {\n time = this.toSeconds(time);\n this._triangle.stop(time);\n // the width is still connected to the output.\n // that needs to be stopped also\n this._widthGate.gain.cancelScheduledValues(time);\n this._widthGate.gain.setValueAtTime(0, time);\n }\n _restart(time) {\n this._triangle.restart(time);\n this._widthGate.gain.cancelScheduledValues(time);\n this._widthGate.gain.setValueAtTime(1, time);\n }\n /**\n * The phase of the oscillator in degrees.\n */\n get phase() {\n return this._triangle.phase;\n }\n set phase(phase) {\n this._triangle.phase = phase;\n }\n /**\n * The type of the oscillator. Always returns \"pulse\".\n */\n get type() {\n return \"pulse\";\n }\n /**\n * The baseType of the oscillator. Always returns \"pulse\".\n */\n get baseType() {\n return \"pulse\";\n }\n /**\n * The partials of the waveform. Cannot set partials for this waveform type\n */\n get partials() {\n return [];\n }\n /**\n * No partials for this waveform type.\n */\n get partialCount() {\n return 0;\n }\n /**\n * *Internal use* The carrier oscillator type is fed through the\n * waveshaper node to create the pulse. Using different carrier oscillators\n * changes oscillator's behavior.\n */\n set carrierType(type) {\n this._triangle.type = type;\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n /**\n * Clean up method.\n */\n dispose() {\n super.dispose();\n this._triangle.dispose();\n this.width.dispose();\n this._widthGate.dispose();\n this._thresh.dispose();\n return this;\n }\n}\n//# sourceMappingURL=PulseOscillator.js.map","import { __awaiter } from \"tslib\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { noOp, readOnly } from \"../../core/util/Interface\";\nimport { Signal } from \"../../signal/Signal\";\nimport { Source } from \"../Source\";\nimport { Oscillator } from \"./Oscillator\";\nimport { generateWaveform } from \"./OscillatorInterface\";\nimport { assertRange } from \"../../core/util/Debug\";\n/**\n * FatOscillator is an array of oscillators with detune spread between the oscillators\n * @example\n * const fatOsc = new Tone.FatOscillator(\"Ab3\", \"sawtooth\", 40).toDestination().start();\n * @category Source\n */\nexport class FatOscillator extends Source {\n constructor() {\n super(optionsFromArguments(FatOscillator.getDefaults(), arguments, [\"frequency\", \"type\", \"spread\"]));\n this.name = \"FatOscillator\";\n /**\n * The array of oscillators\n */\n this._oscillators = [];\n const options = optionsFromArguments(FatOscillator.getDefaults(), arguments, [\"frequency\", \"type\", \"spread\"]);\n this.frequency = new Signal({\n context: this.context,\n units: \"frequency\",\n value: options.frequency,\n });\n this.detune = new Signal({\n context: this.context,\n units: \"cents\",\n value: options.detune,\n });\n this._spread = options.spread;\n this._type = options.type;\n this._phase = options.phase;\n this._partials = options.partials;\n this._partialCount = options.partialCount;\n // set the count initially\n this.count = options.count;\n readOnly(this, [\"frequency\", \"detune\"]);\n }\n static getDefaults() {\n return Object.assign(Oscillator.getDefaults(), {\n count: 3,\n spread: 20,\n type: \"sawtooth\",\n });\n }\n /**\n * start the oscillator\n */\n _start(time) {\n time = this.toSeconds(time);\n this._forEach(osc => osc.start(time));\n }\n /**\n * stop the oscillator\n */\n _stop(time) {\n time = this.toSeconds(time);\n this._forEach(osc => osc.stop(time));\n }\n _restart(time) {\n this._forEach(osc => osc.restart(time));\n }\n /**\n * Iterate over all of the oscillators\n */\n _forEach(iterator) {\n for (let i = 0; i < this._oscillators.length; i++) {\n iterator(this._oscillators[i], i);\n }\n }\n /**\n * The type of the oscillator\n */\n get type() {\n return this._type;\n }\n set type(type) {\n this._type = type;\n this._forEach(osc => osc.type = type);\n }\n /**\n * The detune spread between the oscillators. If \"count\" is\n * set to 3 oscillators and the \"spread\" is set to 40,\n * the three oscillators would be detuned like this: [-20, 0, 20]\n * for a total detune spread of 40 cents.\n * @example\n * const fatOsc = new Tone.FatOscillator().toDestination().start();\n * fatOsc.spread = 70;\n */\n get spread() {\n return this._spread;\n }\n set spread(spread) {\n this._spread = spread;\n if (this._oscillators.length > 1) {\n const start = -spread / 2;\n const step = spread / (this._oscillators.length - 1);\n this._forEach((osc, i) => osc.detune.value = start + step * i);\n }\n }\n /**\n * The number of detuned oscillators. Must be an integer greater than 1.\n * @example\n * const fatOsc = new Tone.FatOscillator(\"C#3\", \"sawtooth\").toDestination().start();\n * // use 4 sawtooth oscillators\n * fatOsc.count = 4;\n */\n get count() {\n return this._oscillators.length;\n }\n set count(count) {\n assertRange(count, 1);\n if (this._oscillators.length !== count) {\n // dispose the previous oscillators\n this._forEach(osc => osc.dispose());\n this._oscillators = [];\n for (let i = 0; i < count; i++) {\n const osc = new Oscillator({\n context: this.context,\n volume: -6 - count * 1.1,\n type: this._type,\n phase: this._phase + (i / count) * 360,\n partialCount: this._partialCount,\n onstop: i === 0 ? () => this.onstop(this) : noOp,\n });\n if (this.type === \"custom\") {\n osc.partials = this._partials;\n }\n this.frequency.connect(osc.frequency);\n this.detune.connect(osc.detune);\n osc.detune.overridden = false;\n osc.connect(this.output);\n this._oscillators[i] = osc;\n }\n // set the spread\n this.spread = this._spread;\n if (this.state === \"started\") {\n this._forEach(osc => osc.start());\n }\n }\n }\n get phase() {\n return this._phase;\n }\n set phase(phase) {\n this._phase = phase;\n this._forEach((osc, i) => osc.phase = this._phase + (i / this.count) * 360);\n }\n get baseType() {\n return this._oscillators[0].baseType;\n }\n set baseType(baseType) {\n this._forEach(osc => osc.baseType = baseType);\n this._type = this._oscillators[0].type;\n }\n get partials() {\n return this._oscillators[0].partials;\n }\n set partials(partials) {\n this._partials = partials;\n this._partialCount = this._partials.length;\n if (partials.length) {\n this._type = \"custom\";\n this._forEach(osc => osc.partials = partials);\n }\n }\n get partialCount() {\n return this._oscillators[0].partialCount;\n }\n set partialCount(partialCount) {\n this._partialCount = partialCount;\n this._forEach(osc => osc.partialCount = partialCount);\n this._type = this._oscillators[0].type;\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this.frequency.dispose();\n this.detune.dispose();\n this._forEach(osc => osc.dispose());\n return this;\n }\n}\n//# sourceMappingURL=FatOscillator.js.map","import { __awaiter } from \"tslib\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { Multiply } from \"../../signal/Multiply\";\nimport { Source } from \"../Source\";\nimport { Oscillator } from \"./Oscillator\";\nimport { generateWaveform } from \"./OscillatorInterface\";\nimport { PulseOscillator } from \"./PulseOscillator\";\n/**\n * PWMOscillator modulates the width of a Tone.PulseOscillator\n * at the modulationFrequency. This has the effect of continuously\n * changing the timbre of the oscillator by altering the harmonics\n * generated.\n * @example\n * return Tone.Offline(() => {\n * \tconst pwm = new Tone.PWMOscillator(60, 0.3).toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class PWMOscillator extends Source {\n constructor() {\n super(optionsFromArguments(PWMOscillator.getDefaults(), arguments, [\"frequency\", \"modulationFrequency\"]));\n this.name = \"PWMOscillator\";\n this.sourceType = \"pwm\";\n /**\n * Scale the oscillator so it doesn't go silent\n * at the extreme values.\n */\n this._scale = new Multiply({\n context: this.context,\n value: 2,\n });\n const options = optionsFromArguments(PWMOscillator.getDefaults(), arguments, [\"frequency\", \"modulationFrequency\"]);\n this._pulse = new PulseOscillator({\n context: this.context,\n frequency: options.modulationFrequency,\n });\n // change the pulse oscillator type\n this._pulse.carrierType = \"sine\";\n this.modulationFrequency = this._pulse.frequency;\n this._modulator = new Oscillator({\n context: this.context,\n detune: options.detune,\n frequency: options.frequency,\n onstop: () => this.onstop(this),\n phase: options.phase,\n });\n this.frequency = this._modulator.frequency;\n this.detune = this._modulator.detune;\n // connections\n this._modulator.chain(this._scale, this._pulse.width);\n this._pulse.connect(this.output);\n readOnly(this, [\"modulationFrequency\", \"frequency\", \"detune\"]);\n }\n static getDefaults() {\n return Object.assign(Source.getDefaults(), {\n detune: 0,\n frequency: 440,\n modulationFrequency: 0.4,\n phase: 0,\n type: \"pwm\",\n });\n }\n /**\n * start the oscillator\n */\n _start(time) {\n time = this.toSeconds(time);\n this._modulator.start(time);\n this._pulse.start(time);\n }\n /**\n * stop the oscillator\n */\n _stop(time) {\n time = this.toSeconds(time);\n this._modulator.stop(time);\n this._pulse.stop(time);\n }\n /**\n * restart the oscillator\n */\n _restart(time) {\n this._modulator.restart(time);\n this._pulse.restart(time);\n }\n /**\n * The type of the oscillator. Always returns \"pwm\".\n */\n get type() {\n return \"pwm\";\n }\n /**\n * The baseType of the oscillator. Always returns \"pwm\".\n */\n get baseType() {\n return \"pwm\";\n }\n /**\n * The partials of the waveform. Cannot set partials for this waveform type\n */\n get partials() {\n return [];\n }\n /**\n * No partials for this waveform type.\n */\n get partialCount() {\n return 0;\n }\n /**\n * The phase of the oscillator in degrees.\n */\n get phase() {\n return this._modulator.phase;\n }\n set phase(phase) {\n this._modulator.phase = phase;\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n /**\n * Clean up.\n */\n dispose() {\n super.dispose();\n this._pulse.dispose();\n this._scale.dispose();\n this._modulator.dispose();\n return this;\n }\n}\n//# sourceMappingURL=PWMOscillator.js.map","import { __awaiter } from \"tslib\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { isNumber, isString } from \"../../core/util/TypeCheck\";\nimport { Signal } from \"../../signal/Signal\";\nimport { Source } from \"../Source\";\nimport { AMOscillator } from \"./AMOscillator\";\nimport { FatOscillator } from \"./FatOscillator\";\nimport { FMOscillator } from \"./FMOscillator\";\nimport { Oscillator } from \"./Oscillator\";\nimport { generateWaveform } from \"./OscillatorInterface\";\nimport { PulseOscillator } from \"./PulseOscillator\";\nimport { PWMOscillator } from \"./PWMOscillator\";\nconst OmniOscillatorSourceMap = {\n am: AMOscillator,\n fat: FatOscillator,\n fm: FMOscillator,\n oscillator: Oscillator,\n pulse: PulseOscillator,\n pwm: PWMOscillator,\n};\n/**\n * OmniOscillator aggregates all of the oscillator types into one.\n * @example\n * return Tone.Offline(() => {\n * \tconst omniOsc = new Tone.OmniOscillator(\"C#4\", \"pwm\").toDestination().start();\n * }, 0.1, 1);\n * @category Source\n */\nexport class OmniOscillator extends Source {\n constructor() {\n super(optionsFromArguments(OmniOscillator.getDefaults(), arguments, [\"frequency\", \"type\"]));\n this.name = \"OmniOscillator\";\n const options = optionsFromArguments(OmniOscillator.getDefaults(), arguments, [\"frequency\", \"type\"]);\n this.frequency = new Signal({\n context: this.context,\n units: \"frequency\",\n value: options.frequency,\n });\n this.detune = new Signal({\n context: this.context,\n units: \"cents\",\n value: options.detune,\n });\n readOnly(this, [\"frequency\", \"detune\"]);\n // set the options\n this.set(options);\n }\n static getDefaults() {\n return Object.assign(Oscillator.getDefaults(), FMOscillator.getDefaults(), AMOscillator.getDefaults(), FatOscillator.getDefaults(), PulseOscillator.getDefaults(), PWMOscillator.getDefaults());\n }\n /**\n * start the oscillator\n */\n _start(time) {\n this._oscillator.start(time);\n }\n /**\n * start the oscillator\n */\n _stop(time) {\n this._oscillator.stop(time);\n }\n _restart(time) {\n this._oscillator.restart(time);\n return this;\n }\n /**\n * The type of the oscillator. Can be any of the basic types: sine, square, triangle, sawtooth. Or\n * prefix the basic types with \"fm\", \"am\", or \"fat\" to use the FMOscillator, AMOscillator or FatOscillator\n * types. The oscillator could also be set to \"pwm\" or \"pulse\". All of the parameters of the\n * oscillator's class are accessible when the oscillator is set to that type, but throws an error\n * when it's not.\n * @example\n * const omniOsc = new Tone.OmniOscillator().toDestination().start();\n * omniOsc.type = \"pwm\";\n * // modulationFrequency is parameter which is available\n * // only when the type is \"pwm\".\n * omniOsc.modulationFrequency.value = 0.5;\n */\n get type() {\n let prefix = \"\";\n if ([\"am\", \"fm\", \"fat\"].some(p => this._sourceType === p)) {\n prefix = this._sourceType;\n }\n return prefix + this._oscillator.type;\n }\n set type(type) {\n if (type.substr(0, 2) === \"fm\") {\n this._createNewOscillator(\"fm\");\n this._oscillator = this._oscillator;\n this._oscillator.type = type.substr(2);\n }\n else if (type.substr(0, 2) === \"am\") {\n this._createNewOscillator(\"am\");\n this._oscillator = this._oscillator;\n this._oscillator.type = type.substr(2);\n }\n else if (type.substr(0, 3) === \"fat\") {\n this._createNewOscillator(\"fat\");\n this._oscillator = this._oscillator;\n this._oscillator.type = type.substr(3);\n }\n else if (type === \"pwm\") {\n this._createNewOscillator(\"pwm\");\n this._oscillator = this._oscillator;\n }\n else if (type === \"pulse\") {\n this._createNewOscillator(\"pulse\");\n }\n else {\n this._createNewOscillator(\"oscillator\");\n this._oscillator = this._oscillator;\n this._oscillator.type = type;\n }\n }\n /**\n * The value is an empty array when the type is not \"custom\".\n * This is not available on \"pwm\" and \"pulse\" oscillator types.\n * See [[Oscillator.partials]]\n */\n get partials() {\n return this._oscillator.partials;\n }\n set partials(partials) {\n if (!this._getOscType(this._oscillator, \"pulse\") && !this._getOscType(this._oscillator, \"pwm\")) {\n this._oscillator.partials = partials;\n }\n }\n get partialCount() {\n return this._oscillator.partialCount;\n }\n set partialCount(partialCount) {\n if (!this._getOscType(this._oscillator, \"pulse\") && !this._getOscType(this._oscillator, \"pwm\")) {\n this._oscillator.partialCount = partialCount;\n }\n }\n set(props) {\n // make sure the type is set first\n if (Reflect.has(props, \"type\") && props.type) {\n this.type = props.type;\n }\n // then set the rest\n super.set(props);\n return this;\n }\n /**\n * connect the oscillator to the frequency and detune signals\n */\n _createNewOscillator(oscType) {\n if (oscType !== this._sourceType) {\n this._sourceType = oscType;\n const OscConstructor = OmniOscillatorSourceMap[oscType];\n // short delay to avoid clicks on the change\n const now = this.now();\n if (this._oscillator) {\n const oldOsc = this._oscillator;\n oldOsc.stop(now);\n // dispose the old one\n this.context.setTimeout(() => oldOsc.dispose(), this.blockTime);\n }\n this._oscillator = new OscConstructor({\n context: this.context,\n });\n this.frequency.connect(this._oscillator.frequency);\n this.detune.connect(this._oscillator.detune);\n this._oscillator.connect(this.output);\n this._oscillator.onstop = () => this.onstop(this);\n if (this.state === \"started\") {\n this._oscillator.start(now);\n }\n }\n }\n get phase() {\n return this._oscillator.phase;\n }\n set phase(phase) {\n this._oscillator.phase = phase;\n }\n /**\n * The source type of the oscillator.\n * @example\n * const omniOsc = new Tone.OmniOscillator(440, \"fmsquare\");\n * console.log(omniOsc.sourceType); // 'fm'\n */\n get sourceType() {\n return this._sourceType;\n }\n set sourceType(sType) {\n // the basetype defaults to sine\n let baseType = \"sine\";\n if (this._oscillator.type !== \"pwm\" && this._oscillator.type !== \"pulse\") {\n baseType = this._oscillator.type;\n }\n // set the type\n if (sType === \"fm\") {\n this.type = \"fm\" + baseType;\n }\n else if (sType === \"am\") {\n this.type = \"am\" + baseType;\n }\n else if (sType === \"fat\") {\n this.type = \"fat\" + baseType;\n }\n else if (sType === \"oscillator\") {\n this.type = baseType;\n }\n else if (sType === \"pulse\") {\n this.type = \"pulse\";\n }\n else if (sType === \"pwm\") {\n this.type = \"pwm\";\n }\n }\n _getOscType(osc, sourceType) {\n return osc instanceof OmniOscillatorSourceMap[sourceType];\n }\n /**\n * The base type of the oscillator. See [[Oscillator.baseType]]\n * @example\n * const omniOsc = new Tone.OmniOscillator(440, \"fmsquare4\");\n * console.log(omniOsc.sourceType, omniOsc.baseType, omniOsc.partialCount);\n */\n get baseType() {\n return this._oscillator.baseType;\n }\n set baseType(baseType) {\n if (!this._getOscType(this._oscillator, \"pulse\") &&\n !this._getOscType(this._oscillator, \"pwm\") &&\n baseType !== \"pulse\" && baseType !== \"pwm\") {\n this._oscillator.baseType = baseType;\n }\n }\n /**\n * The width of the oscillator when sourceType === \"pulse\".\n * See [[PWMOscillator.width]]\n */\n get width() {\n if (this._getOscType(this._oscillator, \"pulse\")) {\n return this._oscillator.width;\n }\n else {\n return undefined;\n }\n }\n /**\n * The number of detuned oscillators when sourceType === \"fat\".\n * See [[FatOscillator.count]]\n */\n get count() {\n if (this._getOscType(this._oscillator, \"fat\")) {\n return this._oscillator.count;\n }\n else {\n return undefined;\n }\n }\n set count(count) {\n if (this._getOscType(this._oscillator, \"fat\") && isNumber(count)) {\n this._oscillator.count = count;\n }\n }\n /**\n * The detune spread between the oscillators when sourceType === \"fat\".\n * See [[FatOscillator.count]]\n */\n get spread() {\n if (this._getOscType(this._oscillator, \"fat\")) {\n return this._oscillator.spread;\n }\n else {\n return undefined;\n }\n }\n set spread(spread) {\n if (this._getOscType(this._oscillator, \"fat\") && isNumber(spread)) {\n this._oscillator.spread = spread;\n }\n }\n /**\n * The type of the modulator oscillator. Only if the oscillator is set to \"am\" or \"fm\" types.\n * See [[AMOscillator]] or [[FMOscillator]]\n */\n get modulationType() {\n if (this._getOscType(this._oscillator, \"fm\") || this._getOscType(this._oscillator, \"am\")) {\n return this._oscillator.modulationType;\n }\n else {\n return undefined;\n }\n }\n set modulationType(mType) {\n if ((this._getOscType(this._oscillator, \"fm\") || this._getOscType(this._oscillator, \"am\")) && isString(mType)) {\n this._oscillator.modulationType = mType;\n }\n }\n /**\n * The modulation index when the sourceType === \"fm\"\n * See [[FMOscillator]].\n */\n get modulationIndex() {\n if (this._getOscType(this._oscillator, \"fm\")) {\n return this._oscillator.modulationIndex;\n }\n else {\n return undefined;\n }\n }\n /**\n * Harmonicity is the frequency ratio between the carrier and the modulator oscillators.\n * See [[AMOscillator]] or [[FMOscillator]]\n */\n get harmonicity() {\n if (this._getOscType(this._oscillator, \"fm\") || this._getOscType(this._oscillator, \"am\")) {\n return this._oscillator.harmonicity;\n }\n else {\n return undefined;\n }\n }\n /**\n * The modulationFrequency Signal of the oscillator when sourceType === \"pwm\"\n * see [[PWMOscillator]]\n * @min 0.1\n * @max 5\n */\n get modulationFrequency() {\n if (this._getOscType(this._oscillator, \"pwm\")) {\n return this._oscillator.modulationFrequency;\n }\n else {\n return undefined;\n }\n }\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n return generateWaveform(this, length);\n });\n }\n dispose() {\n super.dispose();\n this.detune.dispose();\n this.frequency.dispose();\n this._oscillator.dispose();\n return this;\n }\n}\n//# sourceMappingURL=OmniOscillator.js.map","import { assertRange } from \"./Debug\";\n/**\n * Assert that the number is in the given range.\n */\nexport function range(min, max = Infinity) {\n const valueMap = new WeakMap();\n return function (target, propertyKey) {\n Reflect.defineProperty(target, propertyKey, {\n configurable: true,\n enumerable: true,\n get: function () {\n return valueMap.get(this);\n },\n set: function (newValue) {\n assertRange(newValue, min, max);\n valueMap.set(this, newValue);\n }\n });\n };\n}\n/**\n * Convert the time to seconds and assert that the time is in between the two\n * values when being set.\n */\nexport function timeRange(min, max = Infinity) {\n const valueMap = new WeakMap();\n return function (target, propertyKey) {\n Reflect.defineProperty(target, propertyKey, {\n configurable: true,\n enumerable: true,\n get: function () {\n return valueMap.get(this);\n },\n set: function (newValue) {\n assertRange(this.toSeconds(newValue), min, max);\n valueMap.set(this, newValue);\n }\n });\n };\n}\n//# sourceMappingURL=Decorator.js.map","import { __awaiter, __decorate } from \"tslib\";\nimport { ToneAudioBuffer } from \"../../core/context/ToneAudioBuffer\";\nimport { defaultArg, optionsFromArguments } from \"../../core/util/Defaults\";\nimport { noOp } from \"../../core/util/Interface\";\nimport { isUndef } from \"../../core/util/TypeCheck\";\nimport { Source } from \"../Source\";\nimport { ToneBufferSource } from \"./ToneBufferSource\";\nimport { assertRange } from \"../../core/util/Debug\";\nimport { timeRange } from \"../../core/util/Decorator\";\n/**\n * Player is an audio file player with start, loop, and stop functions.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/gong_1.mp3\").toDestination();\n * // play as soon as the buffer is loaded\n * player.autostart = true;\n * @category Source\n */\nexport class Player extends Source {\n constructor() {\n super(optionsFromArguments(Player.getDefaults(), arguments, [\"url\", \"onload\"]));\n this.name = \"Player\";\n /**\n * All of the active buffer source nodes\n */\n this._activeSources = new Set();\n const options = optionsFromArguments(Player.getDefaults(), arguments, [\"url\", \"onload\"]);\n this._buffer = new ToneAudioBuffer({\n onload: this._onload.bind(this, options.onload),\n onerror: options.onerror,\n reverse: options.reverse,\n url: options.url,\n });\n this.autostart = options.autostart;\n this._loop = options.loop;\n this._loopStart = options.loopStart;\n this._loopEnd = options.loopEnd;\n this._playbackRate = options.playbackRate;\n this.fadeIn = options.fadeIn;\n this.fadeOut = options.fadeOut;\n }\n static getDefaults() {\n return Object.assign(Source.getDefaults(), {\n autostart: false,\n fadeIn: 0,\n fadeOut: 0,\n loop: false,\n loopEnd: 0,\n loopStart: 0,\n onload: noOp,\n onerror: noOp,\n playbackRate: 1,\n reverse: false,\n });\n }\n /**\n * Load the audio file as an audio buffer.\n * Decodes the audio asynchronously and invokes\n * the callback once the audio buffer loads.\n * Note: this does not need to be called if a url\n * was passed in to the constructor. Only use this\n * if you want to manually load a new url.\n * @param url The url of the buffer to load. Filetype support depends on the browser.\n */\n load(url) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._buffer.load(url);\n this._onload();\n return this;\n });\n }\n /**\n * Internal callback when the buffer is loaded.\n */\n _onload(callback = noOp) {\n callback();\n if (this.autostart) {\n this.start();\n }\n }\n /**\n * Internal callback when the buffer is done playing.\n */\n _onSourceEnd(source) {\n // invoke the onstop function\n this.onstop(this);\n // delete the source from the active sources\n this._activeSources.delete(source);\n if (this._activeSources.size === 0 && !this._synced &&\n this._state.getValueAtTime(this.now()) === \"started\") {\n // remove the 'implicitEnd' event and replace with an explicit end\n this._state.cancel(this.now());\n this._state.setStateAtTime(\"stopped\", this.now());\n }\n }\n /**\n * Play the buffer at the given startTime. Optionally add an offset\n * and/or duration which will play the buffer from a position\n * within the buffer for the given duration.\n *\n * @param time When the player should start.\n * @param offset The offset from the beginning of the sample to start at.\n * @param duration How long the sample should play. If no duration is given, it will default to the full length of the sample (minus any offset)\n */\n start(time, offset, duration) {\n super.start(time, offset, duration);\n return this;\n }\n /**\n * Internal start method\n */\n _start(startTime, offset, duration) {\n // if it's a loop the default offset is the loopStart point\n if (this._loop) {\n offset = defaultArg(offset, this._loopStart);\n }\n else {\n // otherwise the default offset is 0\n offset = defaultArg(offset, 0);\n }\n // compute the values in seconds\n const computedOffset = this.toSeconds(offset);\n // compute the duration which is either the passed in duration of the buffer.duration - offset\n const origDuration = duration;\n duration = defaultArg(duration, Math.max(this._buffer.duration - computedOffset, 0));\n let computedDuration = this.toSeconds(duration);\n // scale it by the playback rate\n computedDuration = computedDuration / this._playbackRate;\n // get the start time\n startTime = this.toSeconds(startTime);\n // make the source\n const source = new ToneBufferSource({\n url: this._buffer,\n context: this.context,\n fadeIn: this.fadeIn,\n fadeOut: this.fadeOut,\n loop: this._loop,\n loopEnd: this._loopEnd,\n loopStart: this._loopStart,\n onended: this._onSourceEnd.bind(this),\n playbackRate: this._playbackRate,\n }).connect(this.output);\n // set the looping properties\n if (!this._loop && !this._synced) {\n // cancel the previous stop\n this._state.cancel(startTime + computedDuration);\n // if it's not looping, set the state change at the end of the sample\n this._state.setStateAtTime(\"stopped\", startTime + computedDuration, {\n implicitEnd: true,\n });\n }\n // add it to the array of active sources\n this._activeSources.add(source);\n // start it\n if (this._loop && isUndef(origDuration)) {\n source.start(startTime, computedOffset);\n }\n else {\n // subtract the fade out time\n source.start(startTime, computedOffset, computedDuration - this.toSeconds(this.fadeOut));\n }\n }\n /**\n * Stop playback.\n */\n _stop(time) {\n const computedTime = this.toSeconds(time);\n this._activeSources.forEach(source => source.stop(computedTime));\n }\n /**\n * Stop and then restart the player from the beginning (or offset)\n * @param time When the player should start.\n * @param offset The offset from the beginning of the sample to start at.\n * @param duration How long the sample should play. If no duration is given,\n * \t\t\t\t\tit will default to the full length of the sample (minus any offset)\n */\n restart(time, offset, duration) {\n super.restart(time, offset, duration);\n return this;\n }\n _restart(time, offset, duration) {\n this._stop(time);\n this._start(time, offset, duration);\n }\n /**\n * Seek to a specific time in the player's buffer. If the\n * source is no longer playing at that time, it will stop.\n * @param offset The time to seek to.\n * @param when The time for the seek event to occur.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/gurgling_theremin_1.mp3\", () => {\n * \tplayer.start();\n * \t// seek to the offset in 1 second from now\n * \tplayer.seek(0.4, \"+1\");\n * }).toDestination();\n */\n seek(offset, when) {\n const computedTime = this.toSeconds(when);\n if (this._state.getValueAtTime(computedTime) === \"started\") {\n const computedOffset = this.toSeconds(offset);\n // if it's currently playing, stop it\n this._stop(computedTime);\n // restart it at the given time\n this._start(computedTime, computedOffset);\n }\n return this;\n }\n /**\n * Set the loop start and end. Will only loop if loop is set to true.\n * @param loopStart The loop start time\n * @param loopEnd The loop end time\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/malevoices_aa2_F3.mp3\").toDestination();\n * // loop between the given points\n * player.setLoopPoints(0.2, 0.3);\n * player.loop = true;\n * player.autostart = true;\n */\n setLoopPoints(loopStart, loopEnd) {\n this.loopStart = loopStart;\n this.loopEnd = loopEnd;\n return this;\n }\n /**\n * If loop is true, the loop will start at this position.\n */\n get loopStart() {\n return this._loopStart;\n }\n set loopStart(loopStart) {\n this._loopStart = loopStart;\n if (this.buffer.loaded) {\n assertRange(this.toSeconds(loopStart), 0, this.buffer.duration);\n }\n // get the current source\n this._activeSources.forEach(source => {\n source.loopStart = loopStart;\n });\n }\n /**\n * If loop is true, the loop will end at this position.\n */\n get loopEnd() {\n return this._loopEnd;\n }\n set loopEnd(loopEnd) {\n this._loopEnd = loopEnd;\n if (this.buffer.loaded) {\n assertRange(this.toSeconds(loopEnd), 0, this.buffer.duration);\n }\n // get the current source\n this._activeSources.forEach(source => {\n source.loopEnd = loopEnd;\n });\n }\n /**\n * The audio buffer belonging to the player.\n */\n get buffer() {\n return this._buffer;\n }\n set buffer(buffer) {\n this._buffer.set(buffer);\n }\n /**\n * If the buffer should loop once it's over.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/drum-samples/breakbeat.mp3\").toDestination();\n * player.loop = true;\n * player.autostart = true;\n */\n get loop() {\n return this._loop;\n }\n set loop(loop) {\n // if no change, do nothing\n if (this._loop === loop) {\n return;\n }\n this._loop = loop;\n // set the loop of all of the sources\n this._activeSources.forEach(source => {\n source.loop = loop;\n });\n if (loop) {\n // remove the next stopEvent\n const stopEvent = this._state.getNextState(\"stopped\", this.now());\n if (stopEvent) {\n this._state.cancel(stopEvent.time);\n }\n }\n }\n /**\n * Normal speed is 1. The pitch will change with the playback rate.\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/femalevoices_aa2_A5.mp3\").toDestination();\n * // play at 1/4 speed\n * player.playbackRate = 0.25;\n * // play as soon as the buffer is loaded\n * player.autostart = true;\n */\n get playbackRate() {\n return this._playbackRate;\n }\n set playbackRate(rate) {\n this._playbackRate = rate;\n const now = this.now();\n // cancel the stop event since it's at a different time now\n const stopEvent = this._state.getNextState(\"stopped\", now);\n if (stopEvent && stopEvent.implicitEnd) {\n this._state.cancel(stopEvent.time);\n this._activeSources.forEach(source => source.cancelStop());\n }\n // set all the sources\n this._activeSources.forEach(source => {\n source.playbackRate.setValueAtTime(rate, now);\n });\n }\n /**\n * If the buffer should be reversed\n * @example\n * const player = new Tone.Player(\"https://tonejs.github.io/audio/berklee/chime_1.mp3\").toDestination();\n * player.autostart = true;\n * player.reverse = true;\n */\n get reverse() {\n return this._buffer.reverse;\n }\n set reverse(rev) {\n this._buffer.reverse = rev;\n }\n /**\n * If the buffer is loaded\n */\n get loaded() {\n return this._buffer.loaded;\n }\n dispose() {\n super.dispose();\n // disconnect all of the players\n this._activeSources.forEach(source => source.dispose());\n this._activeSources.clear();\n this._buffer.dispose();\n return this;\n }\n}\n__decorate([\n timeRange(0)\n], Player.prototype, \"fadeIn\", void 0);\n__decorate([\n timeRange(0)\n], Player.prototype, \"fadeOut\", void 0);\n//# sourceMappingURL=Player.js.map","import { __awaiter, __decorate } from \"tslib\";\nimport { ToneAudioNode } from \"../../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { isArray, isObject, isString } from \"../../core/util/TypeCheck\";\nimport { connectSignal, Signal } from \"../../signal/Signal\";\nimport { OfflineContext } from \"../../core/context/OfflineContext\";\nimport { assert } from \"../../core/util/Debug\";\nimport { range, timeRange } from \"../../core/util/Decorator\";\n/**\n * Envelope is an [ADSR](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope)\n * envelope generator. Envelope outputs a signal which\n * can be connected to an AudioParam or Tone.Signal.\n * ```\n * /\\\n * / \\\n * / \\\n * / \\\n * / \\___________\n * / \\\n * / \\\n * / \\\n * / \\\n * ```\n * @example\n * return Tone.Offline(() => {\n * \tconst env = new Tone.Envelope({\n * \t\tattack: 0.1,\n * \t\tdecay: 0.2,\n * \t\tsustain: 0.5,\n * \t\trelease: 0.8,\n * \t}).toDestination();\n * \tenv.triggerAttackRelease(0.5);\n * }, 1.5, 1);\n * @category Component\n */\nexport class Envelope extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Envelope.getDefaults(), arguments, [\"attack\", \"decay\", \"sustain\", \"release\"]));\n this.name = \"Envelope\";\n /**\n * the signal which is output.\n */\n this._sig = new Signal({\n context: this.context,\n value: 0,\n });\n /**\n * The output signal of the envelope\n */\n this.output = this._sig;\n /**\n * Envelope has no input\n */\n this.input = undefined;\n const options = optionsFromArguments(Envelope.getDefaults(), arguments, [\"attack\", \"decay\", \"sustain\", \"release\"]);\n this.attack = options.attack;\n this.decay = options.decay;\n this.sustain = options.sustain;\n this.release = options.release;\n this.attackCurve = options.attackCurve;\n this.releaseCurve = options.releaseCurve;\n this.decayCurve = options.decayCurve;\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n attack: 0.01,\n attackCurve: \"linear\",\n decay: 0.1,\n decayCurve: \"exponential\",\n release: 1,\n releaseCurve: \"exponential\",\n sustain: 0.5,\n });\n }\n /**\n * Read the current value of the envelope. Useful for\n * synchronizing visual output to the envelope.\n */\n get value() {\n return this.getValueAtTime(this.now());\n }\n /**\n * Get the curve\n * @param curve\n * @param direction In/Out\n * @return The curve name\n */\n _getCurve(curve, direction) {\n if (isString(curve)) {\n return curve;\n }\n else {\n // look up the name in the curves array\n let curveName;\n for (curveName in EnvelopeCurves) {\n if (EnvelopeCurves[curveName][direction] === curve) {\n return curveName;\n }\n }\n // return the custom curve\n return curve;\n }\n }\n /**\n * Assign a the curve to the given name using the direction\n * @param name\n * @param direction In/Out\n * @param curve\n */\n _setCurve(name, direction, curve) {\n // check if it's a valid type\n if (isString(curve) && Reflect.has(EnvelopeCurves, curve)) {\n const curveDef = EnvelopeCurves[curve];\n if (isObject(curveDef)) {\n if (name !== \"_decayCurve\") {\n this[name] = curveDef[direction];\n }\n }\n else {\n this[name] = curveDef;\n }\n }\n else if (isArray(curve) && name !== \"_decayCurve\") {\n this[name] = curve;\n }\n else {\n throw new Error(\"Envelope: invalid curve: \" + curve);\n }\n }\n /**\n * The shape of the attack.\n * Can be any of these strings:\n * * \"linear\"\n * * \"exponential\"\n * * \"sine\"\n * * \"cosine\"\n * * \"bounce\"\n * * \"ripple\"\n * * \"step\"\n *\n * Can also be an array which describes the curve. Values\n * in the array are evenly subdivided and linearly\n * interpolated over the duration of the attack.\n * @example\n * return Tone.Offline(() => {\n * \tconst env = new Tone.Envelope(0.4).toDestination();\n * \tenv.attackCurve = \"linear\";\n * \tenv.triggerAttack();\n * }, 1, 1);\n */\n get attackCurve() {\n return this._getCurve(this._attackCurve, \"In\");\n }\n set attackCurve(curve) {\n this._setCurve(\"_attackCurve\", \"In\", curve);\n }\n /**\n * The shape of the release. See the attack curve types.\n * @example\n * return Tone.Offline(() => {\n * \tconst env = new Tone.Envelope({\n * \t\trelease: 0.8\n * \t}).toDestination();\n * \tenv.triggerAttack();\n * \t// release curve could also be defined by an array\n * \tenv.releaseCurve = [1, 0.3, 0.4, 0.2, 0.7, 0];\n * \tenv.triggerRelease(0.2);\n * }, 1, 1);\n */\n get releaseCurve() {\n return this._getCurve(this._releaseCurve, \"Out\");\n }\n set releaseCurve(curve) {\n this._setCurve(\"_releaseCurve\", \"Out\", curve);\n }\n /**\n * The shape of the decay either \"linear\" or \"exponential\"\n * @example\n * return Tone.Offline(() => {\n * \tconst env = new Tone.Envelope({\n * \t\tsustain: 0.1,\n * \t\tdecay: 0.5\n * \t}).toDestination();\n * \tenv.decayCurve = \"linear\";\n * \tenv.triggerAttack();\n * }, 1, 1);\n */\n get decayCurve() {\n return this._decayCurve;\n }\n set decayCurve(curve) {\n assert([\"linear\", \"exponential\"].some(c => c === curve), `Invalid envelope curve: ${curve}`);\n this._decayCurve = curve;\n }\n /**\n * Trigger the attack/decay portion of the ADSR envelope.\n * @param time When the attack should start.\n * @param velocity The velocity of the envelope scales the vales.\n * number between 0-1\n * @example\n * const env = new Tone.AmplitudeEnvelope().toDestination();\n * const osc = new Tone.Oscillator().connect(env).start();\n * // trigger the attack 0.5 seconds from now with a velocity of 0.2\n * env.triggerAttack(\"+0.5\", 0.2);\n */\n triggerAttack(time, velocity = 1) {\n this.log(\"triggerAttack\", time, velocity);\n time = this.toSeconds(time);\n const originalAttack = this.toSeconds(this.attack);\n let attack = originalAttack;\n const decay = this.toSeconds(this.decay);\n // check if it's not a complete attack\n const currentValue = this.getValueAtTime(time);\n if (currentValue > 0) {\n // subtract the current value from the attack time\n const attackRate = 1 / attack;\n const remainingDistance = 1 - currentValue;\n // the attack is now the remaining time\n attack = remainingDistance / attackRate;\n }\n // attack\n if (attack < this.sampleTime) {\n this._sig.cancelScheduledValues(time);\n // case where the attack time is 0 should set instantly\n this._sig.setValueAtTime(velocity, time);\n }\n else if (this._attackCurve === \"linear\") {\n this._sig.linearRampTo(velocity, attack, time);\n }\n else if (this._attackCurve === \"exponential\") {\n this._sig.targetRampTo(velocity, attack, time);\n }\n else {\n this._sig.cancelAndHoldAtTime(time);\n let curve = this._attackCurve;\n // find the starting position in the curve\n for (let i = 1; i < curve.length; i++) {\n // the starting index is between the two values\n if (curve[i - 1] <= currentValue && currentValue <= curve[i]) {\n curve = this._attackCurve.slice(i);\n // the first index is the current value\n curve[0] = currentValue;\n break;\n }\n }\n this._sig.setValueCurveAtTime(curve, time, attack, velocity);\n }\n // decay\n if (decay && this.sustain < 1) {\n const decayValue = velocity * this.sustain;\n const decayStart = time + attack;\n this.log(\"decay\", decayStart);\n if (this._decayCurve === \"linear\") {\n this._sig.linearRampToValueAtTime(decayValue, decay + decayStart);\n }\n else {\n this._sig.exponentialApproachValueAtTime(decayValue, decayStart, decay);\n }\n }\n return this;\n }\n /**\n * Triggers the release of the envelope.\n * @param time When the release portion of the envelope should start.\n * @example\n * const env = new Tone.AmplitudeEnvelope().toDestination();\n * const osc = new Tone.Oscillator({\n * \ttype: \"sawtooth\"\n * }).connect(env).start();\n * env.triggerAttack();\n * // trigger the release half a second after the attack\n * env.triggerRelease(\"+0.5\");\n */\n triggerRelease(time) {\n this.log(\"triggerRelease\", time);\n time = this.toSeconds(time);\n const currentValue = this.getValueAtTime(time);\n if (currentValue > 0) {\n const release = this.toSeconds(this.release);\n if (release < this.sampleTime) {\n this._sig.setValueAtTime(0, time);\n }\n else if (this._releaseCurve === \"linear\") {\n this._sig.linearRampTo(0, release, time);\n }\n else if (this._releaseCurve === \"exponential\") {\n this._sig.targetRampTo(0, release, time);\n }\n else {\n assert(isArray(this._releaseCurve), \"releaseCurve must be either 'linear', 'exponential' or an array\");\n this._sig.cancelAndHoldAtTime(time);\n this._sig.setValueCurveAtTime(this._releaseCurve, time, release, currentValue);\n }\n }\n return this;\n }\n /**\n * Get the scheduled value at the given time. This will\n * return the unconverted (raw) value.\n * @example\n * const env = new Tone.Envelope(0.5, 1, 0.4, 2);\n * env.triggerAttackRelease(2);\n * setInterval(() => console.log(env.getValueAtTime(Tone.now())), 100);\n */\n getValueAtTime(time) {\n return this._sig.getValueAtTime(time);\n }\n /**\n * triggerAttackRelease is shorthand for triggerAttack, then waiting\n * some duration, then triggerRelease.\n * @param duration The duration of the sustain.\n * @param time When the attack should be triggered.\n * @param velocity The velocity of the envelope.\n * @example\n * const env = new Tone.AmplitudeEnvelope().toDestination();\n * const osc = new Tone.Oscillator().connect(env).start();\n * // trigger the release 0.5 seconds after the attack\n * env.triggerAttackRelease(0.5);\n */\n triggerAttackRelease(duration, time, velocity = 1) {\n time = this.toSeconds(time);\n this.triggerAttack(time, velocity);\n this.triggerRelease(time + this.toSeconds(duration));\n return this;\n }\n /**\n * Cancels all scheduled envelope changes after the given time.\n */\n cancel(after) {\n this._sig.cancelScheduledValues(this.toSeconds(after));\n return this;\n }\n /**\n * Connect the envelope to a destination node.\n */\n connect(destination, outputNumber = 0, inputNumber = 0) {\n connectSignal(this, destination, outputNumber, inputNumber);\n return this;\n }\n /**\n * Render the envelope curve to an array of the given length.\n * Good for visualizing the envelope curve. Rescales the duration of the\n * envelope to fit the length.\n */\n asArray(length = 1024) {\n return __awaiter(this, void 0, void 0, function* () {\n const duration = length / this.context.sampleRate;\n const context = new OfflineContext(1, duration, this.context.sampleRate);\n // normalize the ADSR for the given duration with 20% sustain time\n const attackPortion = this.toSeconds(this.attack) + this.toSeconds(this.decay);\n const envelopeDuration = attackPortion + this.toSeconds(this.release);\n const sustainTime = envelopeDuration * 0.1;\n const totalDuration = envelopeDuration + sustainTime;\n // @ts-ignore\n const clone = new this.constructor(Object.assign(this.get(), {\n attack: duration * this.toSeconds(this.attack) / totalDuration,\n decay: duration * this.toSeconds(this.decay) / totalDuration,\n release: duration * this.toSeconds(this.release) / totalDuration,\n context\n }));\n clone._sig.toDestination();\n clone.triggerAttackRelease(duration * (attackPortion + sustainTime) / totalDuration, 0);\n const buffer = yield context.render();\n return buffer.getChannelData(0);\n });\n }\n dispose() {\n super.dispose();\n this._sig.dispose();\n return this;\n }\n}\n__decorate([\n timeRange(0)\n], Envelope.prototype, \"attack\", void 0);\n__decorate([\n timeRange(0)\n], Envelope.prototype, \"decay\", void 0);\n__decorate([\n range(0, 1)\n], Envelope.prototype, \"sustain\", void 0);\n__decorate([\n timeRange(0)\n], Envelope.prototype, \"release\", void 0);\n/**\n * Generate some complex envelope curves.\n */\nconst EnvelopeCurves = (() => {\n const curveLen = 128;\n let i;\n let k;\n // cosine curve\n const cosineCurve = [];\n for (i = 0; i < curveLen; i++) {\n cosineCurve[i] = Math.sin((i / (curveLen - 1)) * (Math.PI / 2));\n }\n // ripple curve\n const rippleCurve = [];\n const rippleCurveFreq = 6.4;\n for (i = 0; i < curveLen - 1; i++) {\n k = (i / (curveLen - 1));\n const sineWave = Math.sin(k * (Math.PI * 2) * rippleCurveFreq - Math.PI / 2) + 1;\n rippleCurve[i] = sineWave / 10 + k * 0.83;\n }\n rippleCurve[curveLen - 1] = 1;\n // stairs curve\n const stairsCurve = [];\n const steps = 5;\n for (i = 0; i < curveLen; i++) {\n stairsCurve[i] = Math.ceil((i / (curveLen - 1)) * steps) / steps;\n }\n // in-out easing curve\n const sineCurve = [];\n for (i = 0; i < curveLen; i++) {\n k = i / (curveLen - 1);\n sineCurve[i] = 0.5 * (1 - Math.cos(Math.PI * k));\n }\n // a bounce curve\n const bounceCurve = [];\n for (i = 0; i < curveLen; i++) {\n k = i / (curveLen - 1);\n const freq = Math.pow(k, 3) * 4 + 0.2;\n const val = Math.cos(freq * Math.PI * 2 * k);\n bounceCurve[i] = Math.abs(val * (1 - k));\n }\n /**\n * Invert a value curve to make it work for the release\n */\n function invertCurve(curve) {\n const out = new Array(curve.length);\n for (let j = 0; j < curve.length; j++) {\n out[j] = 1 - curve[j];\n }\n return out;\n }\n /**\n * reverse the curve\n */\n function reverseCurve(curve) {\n return curve.slice(0).reverse();\n }\n /**\n * attack and release curve arrays\n */\n return {\n bounce: {\n In: invertCurve(bounceCurve),\n Out: bounceCurve,\n },\n cosine: {\n In: cosineCurve,\n Out: reverseCurve(cosineCurve),\n },\n exponential: \"exponential\",\n linear: \"linear\",\n ripple: {\n In: rippleCurve,\n Out: invertCurve(rippleCurve),\n },\n sine: {\n In: sineCurve,\n Out: invertCurve(sineCurve),\n },\n step: {\n In: stairsCurve,\n Out: invertCurve(stairsCurve),\n },\n };\n})();\n//# sourceMappingURL=Envelope.js.map","import { Volume } from \"../component/channel/Volume\";\nimport { ToneAudioNode } from \"../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../core/util/Defaults\";\nimport { readOnly } from \"../core/util/Interface\";\n/**\n * Base-class for all instruments\n */\nexport class Instrument extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Instrument.getDefaults(), arguments));\n /**\n * Keep track of all events scheduled to the transport\n * when the instrument is 'synced'\n */\n this._scheduledEvents = [];\n /**\n * If the instrument is currently synced\n */\n this._synced = false;\n this._original_triggerAttack = this.triggerAttack;\n this._original_triggerRelease = this.triggerRelease;\n const options = optionsFromArguments(Instrument.getDefaults(), arguments);\n this._volume = this.output = new Volume({\n context: this.context,\n volume: options.volume,\n });\n this.volume = this._volume.volume;\n readOnly(this, \"volume\");\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n volume: 0,\n });\n }\n /**\n * Sync the instrument to the Transport. All subsequent calls of\n * [[triggerAttack]] and [[triggerRelease]] will be scheduled along the transport.\n * @example\n * const fmSynth = new Tone.FMSynth().toDestination();\n * fmSynth.volume.value = -6;\n * fmSynth.sync();\n * // schedule 3 notes when the transport first starts\n * fmSynth.triggerAttackRelease(\"C4\", \"8n\", 0);\n * fmSynth.triggerAttackRelease(\"E4\", \"8n\", \"8n\");\n * fmSynth.triggerAttackRelease(\"G4\", \"8n\", \"4n\");\n * // start the transport to hear the notes\n * Tone.Transport.start();\n */\n sync() {\n if (this._syncState()) {\n this._syncMethod(\"triggerAttack\", 1);\n this._syncMethod(\"triggerRelease\", 0);\n }\n return this;\n }\n /**\n * set _sync\n */\n _syncState() {\n let changed = false;\n if (!this._synced) {\n this._synced = true;\n changed = true;\n }\n return changed;\n }\n /**\n * Wrap the given method so that it can be synchronized\n * @param method Which method to wrap and sync\n * @param timePosition What position the time argument appears in\n */\n _syncMethod(method, timePosition) {\n const originalMethod = this[\"_original_\" + method] = this[method];\n this[method] = (...args) => {\n const time = args[timePosition];\n const id = this.context.transport.schedule((t) => {\n args[timePosition] = t;\n originalMethod.apply(this, args);\n }, time);\n this._scheduledEvents.push(id);\n };\n }\n /**\n * Unsync the instrument from the Transport\n */\n unsync() {\n this._scheduledEvents.forEach(id => this.context.transport.clear(id));\n this._scheduledEvents = [];\n if (this._synced) {\n this._synced = false;\n this.triggerAttack = this._original_triggerAttack;\n this.triggerRelease = this._original_triggerRelease;\n }\n return this;\n }\n /**\n * Trigger the attack and then the release after the duration.\n * @param note The note to trigger.\n * @param duration How long the note should be held for before\n * triggering the release. This value must be greater than 0.\n * @param time When the note should be triggered.\n * @param velocity The velocity the note should be triggered at.\n * @example\n * const synth = new Tone.Synth().toDestination();\n * // trigger \"C4\" for the duration of an 8th note\n * synth.triggerAttackRelease(\"C4\", \"8n\");\n */\n triggerAttackRelease(note, duration, time, velocity) {\n const computedTime = this.toSeconds(time);\n const computedDuration = this.toSeconds(duration);\n this.triggerAttack(note, computedTime, velocity);\n this.triggerRelease(computedTime + computedDuration);\n return this;\n }\n /**\n * clean up\n * @returns {Instrument} this\n */\n dispose() {\n super.dispose();\n this._volume.dispose();\n this.unsync();\n this._scheduledEvents = [];\n return this;\n }\n}\n//# sourceMappingURL=Instrument.js.map","import { __decorate } from \"tslib\";\nimport { FrequencyClass } from \"../core/type/Frequency\";\nimport { optionsFromArguments } from \"../core/util/Defaults\";\nimport { noOp } from \"../core/util/Interface\";\nimport { Instrument } from \"../instrument/Instrument\";\nimport { timeRange } from \"../core/util/Decorator\";\n/**\n * Abstract base class for other monophonic instruments to extend.\n */\nexport class Monophonic extends Instrument {\n constructor() {\n super(optionsFromArguments(Monophonic.getDefaults(), arguments));\n const options = optionsFromArguments(Monophonic.getDefaults(), arguments);\n this.portamento = options.portamento;\n this.onsilence = options.onsilence;\n }\n static getDefaults() {\n return Object.assign(Instrument.getDefaults(), {\n detune: 0,\n onsilence: noOp,\n portamento: 0,\n });\n }\n /**\n * Trigger the attack of the note optionally with a given velocity.\n * @param note The note to trigger.\n * @param time When the note should start.\n * @param velocity The velocity scaler determines how \"loud\" the note will be triggered.\n * @example\n * const synth = new Tone.Synth().toDestination();\n * // trigger the note a half second from now at half velocity\n * synth.triggerAttack(\"C4\", \"+0.5\", 0.5);\n */\n triggerAttack(note, time, velocity = 1) {\n this.log(\"triggerAttack\", note, time, velocity);\n const seconds = this.toSeconds(time);\n this._triggerEnvelopeAttack(seconds, velocity);\n this.setNote(note, seconds);\n return this;\n }\n /**\n * Trigger the release portion of the envelope\n * @param time If no time is given, the release happens immediatly\n * @example\n * const synth = new Tone.Synth().toDestination();\n * synth.triggerAttack(\"C4\");\n * // trigger the release a second from now\n * synth.triggerRelease(\"+1\");\n */\n triggerRelease(time) {\n this.log(\"triggerRelease\", time);\n const seconds = this.toSeconds(time);\n this._triggerEnvelopeRelease(seconds);\n return this;\n }\n /**\n * Set the note at the given time. If no time is given, the note\n * will set immediately.\n * @param note The note to change to.\n * @param time The time when the note should be set.\n * @example\n * const synth = new Tone.Synth().toDestination();\n * synth.triggerAttack(\"C4\");\n * // change to F#6 in one quarter note from now.\n * synth.setNote(\"F#6\", \"+4n\");\n */\n setNote(note, time) {\n const computedTime = this.toSeconds(time);\n const computedFrequency = note instanceof FrequencyClass ? note.toFrequency() : note;\n if (this.portamento > 0 && this.getLevelAtTime(computedTime) > 0.05) {\n const portTime = this.toSeconds(this.portamento);\n this.frequency.exponentialRampTo(computedFrequency, portTime, computedTime);\n }\n else {\n this.frequency.setValueAtTime(computedFrequency, computedTime);\n }\n return this;\n }\n}\n__decorate([\n timeRange(0)\n], Monophonic.prototype, \"portamento\", void 0);\n//# sourceMappingURL=Monophonic.js.map","import { Gain } from \"../../core/context/Gain\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { Envelope } from \"./Envelope\";\n/**\n * AmplitudeEnvelope is a Tone.Envelope connected to a gain node.\n * Unlike Tone.Envelope, which outputs the envelope's value, AmplitudeEnvelope accepts\n * an audio signal as the input and will apply the envelope to the amplitude\n * of the signal.\n * Read more about ADSR Envelopes on [Wikipedia](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope).\n *\n * @example\n * return Tone.Offline(() => {\n * \tconst ampEnv = new Tone.AmplitudeEnvelope({\n * \t\tattack: 0.1,\n * \t\tdecay: 0.2,\n * \t\tsustain: 1.0,\n * \t\trelease: 0.8\n * \t}).toDestination();\n * \t// create an oscillator and connect it\n * \tconst osc = new Tone.Oscillator().connect(ampEnv).start();\n * \t// trigger the envelopes attack and release \"8t\" apart\n * \tampEnv.triggerAttackRelease(\"8t\");\n * }, 1.5, 1);\n * @category Component\n */\nexport class AmplitudeEnvelope extends Envelope {\n constructor() {\n super(optionsFromArguments(AmplitudeEnvelope.getDefaults(), arguments, [\"attack\", \"decay\", \"sustain\", \"release\"]));\n this.name = \"AmplitudeEnvelope\";\n this._gainNode = new Gain({\n context: this.context,\n gain: 0,\n });\n this.output = this._gainNode;\n this.input = this._gainNode;\n this._sig.connect(this._gainNode.gain);\n this.output = this._gainNode;\n this.input = this._gainNode;\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this._gainNode.dispose();\n return this;\n }\n}\n//# sourceMappingURL=AmplitudeEnvelope.js.map","import { AmplitudeEnvelope } from \"../component/envelope/AmplitudeEnvelope\";\nimport { Envelope } from \"../component/envelope/Envelope\";\nimport { ToneAudioNode } from \"../core/context/ToneAudioNode\";\nimport { omitFromObject, optionsFromArguments } from \"../core/util/Defaults\";\nimport { readOnly } from \"../core/util/Interface\";\nimport { OmniOscillator } from \"../source/oscillator/OmniOscillator\";\nimport { Source } from \"../source/Source\";\nimport { Monophonic } from \"./Monophonic\";\n/**\n * Synth is composed simply of a [[OmniOscillator]] routed through an [[AmplitudeEnvelope]].\n * ```\n * +----------------+ +-------------------+\n * | OmniOscillator +>--> AmplitudeEnvelope +>--> Output\n * +----------------+ +-------------------+\n * ```\n * @example\n * const synth = new Tone.Synth().toDestination();\n * synth.triggerAttackRelease(\"C4\", \"8n\");\n * @category Instrument\n */\nexport class Synth extends Monophonic {\n constructor() {\n super(optionsFromArguments(Synth.getDefaults(), arguments));\n this.name = \"Synth\";\n const options = optionsFromArguments(Synth.getDefaults(), arguments);\n this.oscillator = new OmniOscillator(Object.assign({\n context: this.context,\n detune: options.detune,\n onstop: () => this.onsilence(this),\n }, options.oscillator));\n this.frequency = this.oscillator.frequency;\n this.detune = this.oscillator.detune;\n this.envelope = new AmplitudeEnvelope(Object.assign({\n context: this.context,\n }, options.envelope));\n // connect the oscillators to the output\n this.oscillator.chain(this.envelope, this.output);\n readOnly(this, [\"oscillator\", \"frequency\", \"detune\", \"envelope\"]);\n }\n static getDefaults() {\n return Object.assign(Monophonic.getDefaults(), {\n envelope: Object.assign(omitFromObject(Envelope.getDefaults(), Object.keys(ToneAudioNode.getDefaults())), {\n attack: 0.005,\n decay: 0.1,\n release: 1,\n sustain: 0.3,\n }),\n oscillator: Object.assign(omitFromObject(OmniOscillator.getDefaults(), [...Object.keys(Source.getDefaults()), \"frequency\", \"detune\"]), {\n type: \"triangle\",\n }),\n });\n }\n /**\n * start the attack portion of the envelope\n * @param time the time the attack should start\n * @param velocity the velocity of the note (0-1)\n */\n _triggerEnvelopeAttack(time, velocity) {\n // the envelopes\n this.envelope.triggerAttack(time, velocity);\n this.oscillator.start(time);\n // if there is no release portion, stop the oscillator\n if (this.envelope.sustain === 0) {\n const computedAttack = this.toSeconds(this.envelope.attack);\n const computedDecay = this.toSeconds(this.envelope.decay);\n this.oscillator.stop(time + computedAttack + computedDecay);\n }\n }\n /**\n * start the release portion of the envelope\n * @param time the time the release should start\n */\n _triggerEnvelopeRelease(time) {\n this.envelope.triggerRelease(time);\n this.oscillator.stop(time + this.toSeconds(this.envelope.release));\n }\n getLevelAtTime(time) {\n time = this.toSeconds(time);\n return this.envelope.getValueAtTime(time);\n }\n /**\n * clean up\n */\n dispose() {\n super.dispose();\n this.oscillator.dispose();\n this.envelope.dispose();\n return this;\n }\n}\n//# sourceMappingURL=Synth.js.map","import { __decorate } from \"tslib\";\nimport { FrequencyClass } from \"../core/type/Frequency\";\nimport { deepMerge, optionsFromArguments } from \"../core/util/Defaults\";\nimport { readOnly } from \"../core/util/Interface\";\nimport { Monophonic } from \"./Monophonic\";\nimport { Synth } from \"./Synth\";\nimport { range, timeRange } from \"../core/util/Decorator\";\n/**\n * MembraneSynth makes kick and tom sounds using a single oscillator\n * with an amplitude envelope and frequency ramp. A Tone.OmniOscillator\n * is routed through a Tone.AmplitudeEnvelope to the output. The drum\n * quality of the sound comes from the frequency envelope applied\n * during MembraneSynth.triggerAttack(note). The frequency envelope\n * starts at note * .octaves and ramps to note\n * over the duration of .pitchDecay.\n * @example\n * const synth = new Tone.MembraneSynth().toDestination();\n * synth.triggerAttackRelease(\"C2\", \"8n\");\n * @category Instrument\n */\nexport class MembraneSynth extends Synth {\n constructor() {\n super(optionsFromArguments(MembraneSynth.getDefaults(), arguments));\n this.name = \"MembraneSynth\";\n /**\n * Portamento is ignored in this synth. use pitch decay instead.\n */\n this.portamento = 0;\n const options = optionsFromArguments(MembraneSynth.getDefaults(), arguments);\n this.pitchDecay = options.pitchDecay;\n this.octaves = options.octaves;\n readOnly(this, [\"oscillator\", \"envelope\"]);\n }\n static getDefaults() {\n return deepMerge(Monophonic.getDefaults(), Synth.getDefaults(), {\n envelope: {\n attack: 0.001,\n attackCurve: \"exponential\",\n decay: 0.4,\n release: 1.4,\n sustain: 0.01,\n },\n octaves: 10,\n oscillator: {\n type: \"sine\",\n },\n pitchDecay: 0.05,\n });\n }\n setNote(note, time) {\n const seconds = this.toSeconds(time);\n const hertz = this.toFrequency(note instanceof FrequencyClass ? note.toFrequency() : note);\n const maxNote = hertz * this.octaves;\n this.oscillator.frequency.setValueAtTime(maxNote, seconds);\n this.oscillator.frequency.exponentialRampToValueAtTime(hertz, seconds + this.toSeconds(this.pitchDecay));\n return this;\n }\n dispose() {\n super.dispose();\n return this;\n }\n}\n__decorate([\n range(0)\n], MembraneSynth.prototype, \"octaves\", void 0);\n__decorate([\n timeRange(0)\n], MembraneSynth.prototype, \"pitchDecay\", void 0);\n//# sourceMappingURL=MembraneSynth.js.map","/**\n * All of the classes or functions which are loaded into the AudioWorkletGlobalScope\n */\nconst workletContext = new Set();\n/**\n * Add a class to the AudioWorkletGlobalScope\n */\nexport function addToWorklet(classOrFunction) {\n workletContext.add(classOrFunction);\n}\n/**\n * Register a processor in the AudioWorkletGlobalScope with the given name\n */\nexport function registerProcessor(name, classDesc) {\n const processor = /* javascript */ `registerProcessor(\"${name}\", ${classDesc})`;\n workletContext.add(processor);\n}\n/**\n * Get all of the modules which have been registered to the AudioWorkletGlobalScope\n */\nexport function getWorkletGlobalScope() {\n return Array.from(workletContext).join(\"\\n\");\n}\n//# sourceMappingURL=WorkletGlobalScope.js.map","import { addToWorklet } from \"./WorkletGlobalScope\";\nconst toneAudioWorkletProcessor = /* javascript */ `\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the [[ToneAudioWorklet]]. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it's disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === \"dispose\") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n`;\naddToWorklet(toneAudioWorkletProcessor);\n//# sourceMappingURL=ToneAudioWorkletProcessor.worklet.js.map","import \"./ToneAudioWorkletProcessor.worklet\";\nimport { addToWorklet } from \"./WorkletGlobalScope\";\nexport const singleIOProcess = /* javascript */ `\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n`;\naddToWorklet(singleIOProcess);\n//# sourceMappingURL=SingleIOProcessor.worklet.js.map","import { addToWorklet } from \"./WorkletGlobalScope\";\nconst delayLine = /* javascript */ `\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n`;\naddToWorklet(delayLine);\n//# sourceMappingURL=DelayLine.worklet.js.map","import \"../../core/worklet/SingleIOProcessor.worklet\";\nimport \"../../core/worklet/DelayLine.worklet\";\nimport { registerProcessor } from \"../../core/worklet/WorkletGlobalScope\";\nexport const workletName = \"feedback-comb-filter\";\nconst feedbackCombFilter = /* javascript */ `\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"delayTime\",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: \"k-rate\"\n\t\t\t}, {\n\t\t\t\tname: \"feedback\",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: \"k-rate\"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n`;\nregisterProcessor(workletName, feedbackCombFilter);\n//# sourceMappingURL=FeedbackCombFilter.worklet.js.map","import { __decorate } from \"tslib\";\nimport { ToneAudioBuffers } from \"../core/context/ToneAudioBuffers\";\nimport { ftomf, intervalToFrequencyRatio } from \"../core/type/Conversions\";\nimport { FrequencyClass } from \"../core/type/Frequency\";\nimport { optionsFromArguments } from \"../core/util/Defaults\";\nimport { noOp } from \"../core/util/Interface\";\nimport { isArray, isNote, isNumber } from \"../core/util/TypeCheck\";\nimport { Instrument } from \"../instrument/Instrument\";\nimport { ToneBufferSource } from \"../source/buffer/ToneBufferSource\";\nimport { timeRange } from \"../core/util/Decorator\";\nimport { assert } from \"../core/util/Debug\";\n/**\n * Pass in an object which maps the note's pitch or midi value to the url,\n * then you can trigger the attack and release of that note like other instruments.\n * By automatically repitching the samples, it is possible to play pitches which\n * were not explicitly included which can save loading time.\n *\n * For sample or buffer playback where repitching is not necessary,\n * use [[Player]].\n * @example\n * const sampler = new Tone.Sampler({\n * \turls: {\n * \t\tA1: \"A1.mp3\",\n * \t\tA2: \"A2.mp3\",\n * \t},\n * \tbaseUrl: \"https://tonejs.github.io/audio/casio/\",\n * \tonload: () => {\n * \t\tsampler.triggerAttackRelease([\"C1\", \"E1\", \"G1\", \"B1\"], 0.5);\n * \t}\n * }).toDestination();\n * @category Instrument\n */\nexport class Sampler extends Instrument {\n constructor() {\n super(optionsFromArguments(Sampler.getDefaults(), arguments, [\"urls\", \"onload\", \"baseUrl\"], \"urls\"));\n this.name = \"Sampler\";\n /**\n * The object of all currently playing BufferSources\n */\n this._activeSources = new Map();\n const options = optionsFromArguments(Sampler.getDefaults(), arguments, [\"urls\", \"onload\", \"baseUrl\"], \"urls\");\n const urlMap = {};\n Object.keys(options.urls).forEach((note) => {\n const noteNumber = parseInt(note, 10);\n assert(isNote(note)\n || (isNumber(noteNumber) && isFinite(noteNumber)), `url key is neither a note or midi pitch: ${note}`);\n if (isNote(note)) {\n // convert the note name to MIDI\n const mid = new FrequencyClass(this.context, note).toMidi();\n urlMap[mid] = options.urls[note];\n }\n else if (isNumber(noteNumber) && isFinite(noteNumber)) {\n // otherwise if it's numbers assume it's midi\n urlMap[noteNumber] = options.urls[noteNumber];\n }\n });\n this._buffers = new ToneAudioBuffers({\n urls: urlMap,\n onload: options.onload,\n baseUrl: options.baseUrl,\n onerror: options.onerror,\n });\n this.attack = options.attack;\n this.release = options.release;\n this.curve = options.curve;\n // invoke the callback if it's already loaded\n if (this._buffers.loaded) {\n // invoke onload deferred\n Promise.resolve().then(options.onload);\n }\n }\n static getDefaults() {\n return Object.assign(Instrument.getDefaults(), {\n attack: 0,\n baseUrl: \"\",\n curve: \"exponential\",\n onload: noOp,\n onerror: noOp,\n release: 0.1,\n urls: {},\n });\n }\n /**\n * Returns the difference in steps between the given midi note at the closets sample.\n */\n _findClosest(midi) {\n // searches within 8 octaves of the given midi note\n const MAX_INTERVAL = 96;\n let interval = 0;\n while (interval < MAX_INTERVAL) {\n // check above and below\n if (this._buffers.has(midi + interval)) {\n return -interval;\n }\n else if (this._buffers.has(midi - interval)) {\n return interval;\n }\n interval++;\n }\n throw new Error(`No available buffers for note: ${midi}`);\n }\n /**\n * @param notes\tThe note to play, or an array of notes.\n * @param time When to play the note\n * @param velocity The velocity to play the sample back.\n */\n triggerAttack(notes, time, velocity = 1) {\n this.log(\"triggerAttack\", notes, time, velocity);\n if (!Array.isArray(notes)) {\n notes = [notes];\n }\n notes.forEach(note => {\n const midiFloat = ftomf(new FrequencyClass(this.context, note).toFrequency());\n const midi = Math.round(midiFloat);\n const remainder = midiFloat - midi;\n // find the closest note pitch\n const difference = this._findClosest(midi);\n const closestNote = midi - difference;\n const buffer = this._buffers.get(closestNote);\n const playbackRate = intervalToFrequencyRatio(difference + remainder);\n // play that note\n const source = new ToneBufferSource({\n url: buffer,\n context: this.context,\n curve: this.curve,\n fadeIn: this.attack,\n fadeOut: this.release,\n playbackRate,\n }).connect(this.output);\n source.start(time, 0, buffer.duration / playbackRate, velocity);\n // add it to the active sources\n if (!isArray(this._activeSources.get(midi))) {\n this._activeSources.set(midi, []);\n }\n this._activeSources.get(midi).push(source);\n // remove it when it's done\n source.onended = () => {\n if (this._activeSources && this._activeSources.has(midi)) {\n const sources = this._activeSources.get(midi);\n const index = sources.indexOf(source);\n if (index !== -1) {\n sources.splice(index, 1);\n }\n }\n };\n });\n return this;\n }\n /**\n * @param notes\tThe note to release, or an array of notes.\n * @param time \tWhen to release the note.\n */\n triggerRelease(notes, time) {\n this.log(\"triggerRelease\", notes, time);\n if (!Array.isArray(notes)) {\n notes = [notes];\n }\n notes.forEach(note => {\n const midi = new FrequencyClass(this.context, note).toMidi();\n // find the note\n if (this._activeSources.has(midi) && this._activeSources.get(midi).length) {\n const sources = this._activeSources.get(midi);\n time = this.toSeconds(time);\n sources.forEach(source => {\n source.stop(time);\n });\n this._activeSources.set(midi, []);\n }\n });\n return this;\n }\n /**\n * Release all currently active notes.\n * @param time \tWhen to release the notes.\n */\n releaseAll(time) {\n const computedTime = this.toSeconds(time);\n this._activeSources.forEach(sources => {\n while (sources.length) {\n const source = sources.shift();\n source.stop(computedTime);\n }\n });\n return this;\n }\n sync() {\n if (this._syncState()) {\n this._syncMethod(\"triggerAttack\", 1);\n this._syncMethod(\"triggerRelease\", 1);\n }\n return this;\n }\n /**\n * Invoke the attack phase, then after the duration, invoke the release.\n * @param notes\tThe note to play and release, or an array of notes.\n * @param duration The time the note should be held\n * @param time When to start the attack\n * @param velocity The velocity of the attack\n */\n triggerAttackRelease(notes, duration, time, velocity = 1) {\n const computedTime = this.toSeconds(time);\n this.triggerAttack(notes, computedTime, velocity);\n if (isArray(duration)) {\n assert(isArray(notes), \"notes must be an array when duration is array\");\n notes.forEach((note, index) => {\n const d = duration[Math.min(index, duration.length - 1)];\n this.triggerRelease(note, computedTime + this.toSeconds(d));\n });\n }\n else {\n this.triggerRelease(notes, computedTime + this.toSeconds(duration));\n }\n return this;\n }\n /**\n * Add a note to the sampler.\n * @param note The buffer's pitch.\n * @param url Either the url of the buffer, or a buffer which will be added with the given name.\n * @param callback The callback to invoke when the url is loaded.\n */\n add(note, url, callback) {\n assert(isNote(note) || isFinite(note), `note must be a pitch or midi: ${note}`);\n if (isNote(note)) {\n // convert the note name to MIDI\n const mid = new FrequencyClass(this.context, note).toMidi();\n this._buffers.add(mid, url, callback);\n }\n else {\n // otherwise if it's numbers assume it's midi\n this._buffers.add(note, url, callback);\n }\n return this;\n }\n /**\n * If the buffers are loaded or not\n */\n get loaded() {\n return this._buffers.loaded;\n }\n /**\n * Clean up\n */\n dispose() {\n super.dispose();\n this._buffers.dispose();\n this._activeSources.forEach(sources => {\n sources.forEach(source => source.dispose());\n });\n this._activeSources.clear();\n return this;\n }\n}\n__decorate([\n timeRange(0)\n], Sampler.prototype, \"attack\", void 0);\n__decorate([\n timeRange(0)\n], Sampler.prototype, \"release\", void 0);\n//# sourceMappingURL=Sampler.js.map","import { Param } from \"../../core/context/Param\";\nimport { ToneAudioNode } from \"../../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { readOnly } from \"../../core/util/Interface\";\n/**\n * Panner is an equal power Left/Right Panner. It is a wrapper around the StereoPannerNode.\n * @example\n * return Tone.Offline(() => {\n * // move the input signal from right to left\n * \tconst panner = new Tone.Panner(1).toDestination();\n * \tpanner.pan.rampTo(-1, 0.5);\n * \tconst osc = new Tone.Oscillator(100).connect(panner).start();\n * }, 0.5, 2);\n * @category Component\n */\nexport class Panner extends ToneAudioNode {\n constructor() {\n super(Object.assign(optionsFromArguments(Panner.getDefaults(), arguments, [\"pan\"])));\n this.name = \"Panner\";\n /**\n * the panner node\n */\n this._panner = this.context.createStereoPanner();\n this.input = this._panner;\n this.output = this._panner;\n const options = optionsFromArguments(Panner.getDefaults(), arguments, [\"pan\"]);\n this.pan = new Param({\n context: this.context,\n param: this._panner.pan,\n value: options.pan,\n minValue: -1,\n maxValue: 1,\n });\n // this is necessary for standardized-audio-context\n // doesn't make any difference for the native AudioContext\n // https://github.com/chrisguttandin/standardized-audio-context/issues/647\n this._panner.channelCount = options.channelCount;\n this._panner.channelCountMode = \"explicit\";\n // initial value\n readOnly(this, \"pan\");\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n pan: 0,\n channelCount: 1,\n });\n }\n dispose() {\n super.dispose();\n this._panner.disconnect();\n this.pan.dispose();\n return this;\n }\n}\n//# sourceMappingURL=Panner.js.map","import \"../core/worklet/SingleIOProcessor.worklet\";\nimport { registerProcessor } from \"../core/worklet/WorkletGlobalScope\";\nexport const workletName = \"bit-crusher\";\nexport const bitCrusherWorklet = /* javascript */ `\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n`;\nregisterProcessor(workletName, bitCrusherWorklet);\n//# sourceMappingURL=BitCrusher.worklet.js.map","import { Gain } from \"../../core/context/Gain\";\nimport { ToneAudioNode } from \"../../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\n/**\n * Solo lets you isolate a specific audio stream. When an instance is set to `solo=true`,\n * it will mute all other instances of Solo.\n * @example\n * const soloA = new Tone.Solo().toDestination();\n * const oscA = new Tone.Oscillator(\"C4\", \"sawtooth\").connect(soloA);\n * const soloB = new Tone.Solo().toDestination();\n * const oscB = new Tone.Oscillator(\"E4\", \"square\").connect(soloB);\n * soloA.solo = true;\n * // no audio will pass through soloB\n * @category Component\n */\nexport class Solo extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Solo.getDefaults(), arguments, [\"solo\"]));\n this.name = \"Solo\";\n const options = optionsFromArguments(Solo.getDefaults(), arguments, [\"solo\"]);\n this.input = this.output = new Gain({\n context: this.context,\n });\n if (!Solo._allSolos.has(this.context)) {\n Solo._allSolos.set(this.context, new Set());\n }\n Solo._allSolos.get(this.context).add(this);\n // set initially\n this.solo = options.solo;\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n solo: false,\n });\n }\n /**\n * Isolates this instance and mutes all other instances of Solo.\n * Only one instance can be soloed at a time. A soloed\n * instance will report `solo=false` when another instance is soloed.\n */\n get solo() {\n return this._isSoloed();\n }\n set solo(solo) {\n if (solo) {\n this._addSolo();\n }\n else {\n this._removeSolo();\n }\n Solo._allSolos.get(this.context).forEach(instance => instance._updateSolo());\n }\n /**\n * If the current instance is muted, i.e. another instance is soloed\n */\n get muted() {\n return this.input.gain.value === 0;\n }\n /**\n * Add this to the soloed array\n */\n _addSolo() {\n if (!Solo._soloed.has(this.context)) {\n Solo._soloed.set(this.context, new Set());\n }\n Solo._soloed.get(this.context).add(this);\n }\n /**\n * Remove this from the soloed array\n */\n _removeSolo() {\n if (Solo._soloed.has(this.context)) {\n Solo._soloed.get(this.context).delete(this);\n }\n }\n /**\n * Is this on the soloed array\n */\n _isSoloed() {\n return Solo._soloed.has(this.context) && Solo._soloed.get(this.context).has(this);\n }\n /**\n * Returns true if no one is soloed\n */\n _noSolos() {\n // either does not have any soloed added\n return !Solo._soloed.has(this.context) ||\n // or has a solo set but doesn't include any items\n (Solo._soloed.has(this.context) && Solo._soloed.get(this.context).size === 0);\n }\n /**\n * Solo the current instance and unsolo all other instances.\n */\n _updateSolo() {\n if (this._isSoloed()) {\n this.input.gain.value = 1;\n }\n else if (this._noSolos()) {\n // no one is soloed\n this.input.gain.value = 1;\n }\n else {\n this.input.gain.value = 0;\n }\n }\n dispose() {\n super.dispose();\n Solo._allSolos.get(this.context).delete(this);\n this._removeSolo();\n return this;\n }\n}\n/**\n * Hold all of the solo'ed tracks belonging to a specific context\n */\nSolo._allSolos = new Map();\n/**\n * Hold the currently solo'ed instance(s)\n */\nSolo._soloed = new Map();\n//# sourceMappingURL=Solo.js.map","import { readOnly } from \"../../core/util/Interface\";\nimport { ToneAudioNode } from \"../../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { Panner } from \"./Panner\";\nimport { Volume } from \"./Volume\";\n/**\n * PanVol is a Tone.Panner and Tone.Volume in one.\n * @example\n * // pan the incoming signal left and drop the volume\n * const panVol = new Tone.PanVol(-0.25, -12).toDestination();\n * const osc = new Tone.Oscillator().connect(panVol).start();\n * @category Component\n */\nexport class PanVol extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(PanVol.getDefaults(), arguments, [\"pan\", \"volume\"]));\n this.name = \"PanVol\";\n const options = optionsFromArguments(PanVol.getDefaults(), arguments, [\"pan\", \"volume\"]);\n this._panner = this.input = new Panner({\n context: this.context,\n pan: options.pan,\n channelCount: options.channelCount,\n });\n this.pan = this._panner.pan;\n this._volume = this.output = new Volume({\n context: this.context,\n volume: options.volume,\n });\n this.volume = this._volume.volume;\n // connections\n this._panner.connect(this._volume);\n this.mute = options.mute;\n readOnly(this, [\"pan\", \"volume\"]);\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n mute: false,\n pan: 0,\n volume: 0,\n channelCount: 1,\n });\n }\n /**\n * Mute/unmute the volume\n */\n get mute() {\n return this._volume.mute;\n }\n set mute(mute) {\n this._volume.mute = mute;\n }\n dispose() {\n super.dispose();\n this._panner.dispose();\n this.pan.dispose();\n this._volume.dispose();\n this.volume.dispose();\n return this;\n }\n}\n//# sourceMappingURL=PanVol.js.map","import { ToneAudioNode } from \"../../core/context/ToneAudioNode\";\nimport { optionsFromArguments } from \"../../core/util/Defaults\";\nimport { Solo } from \"./Solo\";\nimport { PanVol } from \"./PanVol\";\nimport { readOnly } from \"../../core/util/Interface\";\nimport { Gain } from \"../../core/context/Gain\";\n/**\n * Channel provides a channel strip interface with volume, pan, solo and mute controls.\n * See [[PanVol]] and [[Solo]]\n * @example\n * // pan the incoming signal left and drop the volume 12db\n * const channel = new Tone.Channel(-0.25, -12);\n * @category Component\n */\nexport class Channel extends ToneAudioNode {\n constructor() {\n super(optionsFromArguments(Channel.getDefaults(), arguments, [\"volume\", \"pan\"]));\n this.name = \"Channel\";\n const options = optionsFromArguments(Channel.getDefaults(), arguments, [\"volume\", \"pan\"]);\n this._solo = this.input = new Solo({\n solo: options.solo,\n context: this.context,\n });\n this._panVol = this.output = new PanVol({\n context: this.context,\n pan: options.pan,\n volume: options.volume,\n mute: options.mute,\n channelCount: options.channelCount\n });\n this.pan = this._panVol.pan;\n this.volume = this._panVol.volume;\n this._solo.connect(this._panVol);\n readOnly(this, [\"pan\", \"volume\"]);\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n pan: 0,\n volume: 0,\n mute: false,\n solo: false,\n channelCount: 1,\n });\n }\n /**\n * Solo/unsolo the channel. Soloing is only relative to other [[Channels]] and [[Solo]] instances\n */\n get solo() {\n return this._solo.solo;\n }\n set solo(solo) {\n this._solo.solo = solo;\n }\n /**\n * If the current instance is muted, i.e. another instance is soloed,\n * or the channel is muted\n */\n get muted() {\n return this._solo.muted || this.mute;\n }\n /**\n * Mute/unmute the volume\n */\n get mute() {\n return this._panVol.mute;\n }\n set mute(mute) {\n this._panVol.mute = mute;\n }\n /**\n * Get the gain node belonging to the bus name. Create it if\n * it doesn't exist\n * @param name The bus name\n */\n _getBus(name) {\n if (!Channel.buses.has(name)) {\n Channel.buses.set(name, new Gain({ context: this.context }));\n }\n return Channel.buses.get(name);\n }\n /**\n * Send audio to another channel using a string. `send` is a lot like\n * [[connect]], except it uses a string instead of an object. This can\n * be useful in large applications to decouple sections since [[send]]\n * and [[receive]] can be invoked separately in order to connect an object\n * @param name The channel name to send the audio\n * @param volume The amount of the signal to send.\n * \tDefaults to 0db, i.e. send the entire signal\n * @returns Returns the gain node of this connection.\n */\n send(name, volume = 0) {\n const bus = this._getBus(name);\n const sendKnob = new Gain({\n context: this.context,\n units: \"decibels\",\n gain: volume,\n });\n this.connect(sendKnob);\n sendKnob.connect(bus);\n return sendKnob;\n }\n /**\n * Receive audio from a channel which was connected with [[send]].\n * @param name The channel name to receive audio from.\n */\n receive(name) {\n const bus = this._getBus(name);\n bus.connect(this);\n return this;\n }\n dispose() {\n super.dispose();\n this._panVol.dispose();\n this.pan.dispose();\n this.volume.dispose();\n this._solo.dispose();\n return this;\n }\n}\n/**\n * Store the send/receive channels by name.\n */\nChannel.buses = new Map();\n//# sourceMappingURL=Channel.js.map","import { ToneAudioNode } from \"./ToneAudioNode\";\nimport { Param } from \"./Param\";\nimport { onContextClose, onContextInit } from \"./ContextInitialization\";\n/**\n * Tone.Listener is a thin wrapper around the AudioListener. Listener combined\n * with [[Panner3D]] makes up the Web Audio API's 3D panning system. Panner3D allows you\n * to place sounds in 3D and Listener allows you to navigate the 3D sound environment from\n * a first-person perspective. There is only one listener per audio context.\n */\nexport class Listener extends ToneAudioNode {\n constructor() {\n super(...arguments);\n this.name = \"Listener\";\n this.positionX = new Param({\n context: this.context,\n param: this.context.rawContext.listener.positionX,\n });\n this.positionY = new Param({\n context: this.context,\n param: this.context.rawContext.listener.positionY,\n });\n this.positionZ = new Param({\n context: this.context,\n param: this.context.rawContext.listener.positionZ,\n });\n this.forwardX = new Param({\n context: this.context,\n param: this.context.rawContext.listener.forwardX,\n });\n this.forwardY = new Param({\n context: this.context,\n param: this.context.rawContext.listener.forwardY,\n });\n this.forwardZ = new Param({\n context: this.context,\n param: this.context.rawContext.listener.forwardZ,\n });\n this.upX = new Param({\n context: this.context,\n param: this.context.rawContext.listener.upX,\n });\n this.upY = new Param({\n context: this.context,\n param: this.context.rawContext.listener.upY,\n });\n this.upZ = new Param({\n context: this.context,\n param: this.context.rawContext.listener.upZ,\n });\n }\n static getDefaults() {\n return Object.assign(ToneAudioNode.getDefaults(), {\n positionX: 0,\n positionY: 0,\n positionZ: 0,\n forwardX: 0,\n forwardY: 0,\n forwardZ: -1,\n upX: 0,\n upY: 1,\n upZ: 0,\n });\n }\n dispose() {\n super.dispose();\n this.positionX.dispose();\n this.positionY.dispose();\n this.positionZ.dispose();\n this.forwardX.dispose();\n this.forwardY.dispose();\n this.forwardZ.dispose();\n this.upX.dispose();\n this.upY.dispose();\n this.upZ.dispose();\n return this;\n }\n}\n//-------------------------------------\n// \tINITIALIZATION\n//-------------------------------------\nonContextInit(context => {\n context.listener = new Listener({ context });\n});\nonContextClose(context => {\n context.listener.dispose();\n});\n//# sourceMappingURL=Listener.js.map","export { getContext, setContext } from \"./core/Global\";\nexport * from \"./classes\";\nexport * from \"./version\";\nimport { getContext } from \"./core/Global\";\nimport { ToneAudioBuffer } from \"./core/context/ToneAudioBuffer\";\nexport { start } from \"./core/Global\";\nexport { supported } from \"./core/context/AudioContext\";\n/**\n * The current audio context time of the global [[Context]].\n * See [[Context.now]]\n * @category Core\n */\nexport function now() {\n return getContext().now();\n}\n/**\n * The current audio context time of the global [[Context]] without the [[Context.lookAhead]]\n * See [[Context.immediate]]\n * @category Core\n */\nexport function immediate() {\n return getContext().immediate();\n}\n/**\n * The Transport object belonging to the global Tone.js Context.\n * See [[Transport]]\n * @category Core\n */\nexport const Transport = getContext().transport;\n/**\n * The Transport object belonging to the global Tone.js Context.\n * See [[Transport]]\n * @category Core\n */\nexport function getTransport() {\n return getContext().transport;\n}\n/**\n * The Destination (output) belonging to the global Tone.js Context.\n * See [[Destination]]\n * @category Core\n */\nexport const Destination = getContext().destination;\n/**\n * @deprecated Use [[Destination]]\n */\nexport const Master = getContext().destination;\n/**\n * The Destination (output) belonging to the global Tone.js Context.\n * See [[Destination]]\n * @category Core\n */\nexport function getDestination() {\n return getContext().destination;\n}\n/**\n * The [[Listener]] belonging to the global Tone.js Context.\n * @category Core\n */\nexport const Listener = getContext().listener;\n/**\n * The [[Listener]] belonging to the global Tone.js Context.\n * @category Core\n */\nexport function getListener() {\n return getContext().listener;\n}\n/**\n * Draw is used to synchronize the draw frame with the Transport's callbacks.\n * See [[Draw]]\n * @category Core\n */\nexport const Draw = getContext().draw;\n/**\n * Get the singleton attached to the global context.\n * Draw is used to synchronize the draw frame with the Transport's callbacks.\n * See [[Draw]]\n * @category Core\n */\nexport function getDraw() {\n return getContext().draw;\n}\n/**\n * A reference to the global context\n * See [[Context]]\n */\nexport const context = getContext();\n/**\n * Promise which resolves when all of the loading promises are resolved.\n * Alias for static [[ToneAudioBuffer.loaded]] method.\n * @category Core\n */\nexport function loaded() {\n return ToneAudioBuffer.loaded();\n}\n// this fills in name changes from 13.x to 14.x\nimport { ToneAudioBuffers } from \"./core/context/ToneAudioBuffers\";\nimport { ToneBufferSource } from \"./source/buffer/ToneBufferSource\";\nexport const Buffer = ToneAudioBuffer;\nexport const Buffers = ToneAudioBuffers;\nexport const BufferSource = ToneBufferSource;\n//# sourceMappingURL=index.js.map","\nThe Synth component is a basic sound Synthesizer based on [Tone.js](https://tonejs.github.io/).\n\n```vue\n\n \n\n \n \n \n\n \n \n \n \n \n \n\n \n\n```\n\n\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./Synth.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./Synth.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./Synth.vue?vue&type=template&id=7592e858&scoped=true&\"\nimport script from \"./Synth.vue?vue&type=script&lang=js&\"\nexport * from \"./Synth.vue?vue&type=script&lang=js&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"7592e858\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./Synth.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _iterableToArrayLimit(arr, i) {\n var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;"],"sourceRoot":""} \ No newline at end of file diff --git a/experiments/pilot-02b/js/chunk-vendors.0f25f71e.js b/experiments/pilot-02b/js/chunk-vendors.0f25f71e.js new file mode 100644 index 0000000..988180b --- /dev/null +++ b/experiments/pilot-02b/js/chunk-vendors.0f25f71e.js @@ -0,0 +1,47 @@ +(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-vendors"],{"0055":function(t,e,n){"use strict";n("4092")},"00fd":function(t,e,n){var r=n("9e69"),i=Object.prototype,o=i.hasOwnProperty,a=i.toString,s=r?r.toStringTag:void 0;function u(t){var e=o.call(t,s),n=t[s];try{t[s]=void 0;var r=!0}catch(u){}var i=a.call(t);return r&&(e?t[s]=n:delete t[s]),i}t.exports=u},"0155":function(t,e){},"0234":function(t,e,n){"use strict";function r(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function i(t){for(var e=1;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())},t.prototype.getTime=function(){return this._time},t.prototype.setPosition=function(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t},t.prototype.getPosition=function(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)},t.prototype.play=function(){this.state=c,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")},t.prototype.reverse=function(){this.state=l,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")},t.prototype.seek=function(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")},t.prototype.reset=function(){this.pause(),this._time=0,this.update(),this.fire("onReset")},t.prototype.finish=function(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")},t.prototype.update=function(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")},t.prototype.onEnterFrame=function(){var t=this.getTimer()-this._startTime;this.state===c?this.setTime(t):this.state===l&&this.setTime(this.duration-t)},t.prototype.pause=function(){this.state=u,this.fire("onPause")},t.prototype.getTimer=function(){return(new Date).getTime()},t}(),p=function(){function t(n){var o,u,c=this,l=n.node,h=l._id,p=n.easing||e.Easings.Linear,v=!!n.yoyo;o="undefined"===typeof n.duration?.3:0===n.duration?.001:n.duration,this.node=l,this._id=f++;var g=l.getLayer()||(l instanceof a.Konva["Stage"]?l.getLayers():null);for(u in g||r.Util.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new i.Animation((function(){c.tween.onEnterFrame()}),g),this.tween=new d(u,(function(t){c._tweenFunc(t)}),p,0,1,1e3*o,v),this._addListeners(),t.attrs[h]||(t.attrs[h]={}),t.attrs[h][this._id]||(t.attrs[h][this._id]={}),t.tweens[h]||(t.tweens[h]={}),n)void 0===s[u]&&this._addAttr(u,n[u]);this.reset(),this.onFinish=n.onFinish,this.onReset=n.onReset,this.onUpdate=n.onUpdate}return t.prototype._addAttr=function(e,n){var i,o,a,s,u,c,l,f,d=this.node,p=d._id;if(a=t.tweens[p][e],a&&delete t.attrs[p][a][e],i=d.getAttr(e),r.Util._isArray(n))if(o=[],u=Math.max(n.length,i.length),"points"===e&&n.length!==i.length&&(n.length>i.length?(l=i,i=r.Util._prepareArrayForTween(i,n,d.closed())):(c=n,n=r.Util._prepareArrayForTween(n,i,d.closed()))),0===e.indexOf("fill"))for(s=0;s0?{antialiased:!0}:{}},e.prototype.drawScene=function(t,e){var n=this.getLayer(),r=t||n&&n.getCanvas();return this._fire(d,{node:this}),this.clearBeforeDraw()&&r.getContext().clear(),o.Container.prototype.drawScene.call(this,r,e),this._fire(p,{node:this}),this},e.prototype.drawHit=function(t,e){var n=this.getLayer(),r=t||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),o.Container.prototype.drawHit.call(this,r,e),this},e.prototype.enableHitGraph=function(){return this.hitGraphEnabled(!0),this},e.prototype.disableHitGraph=function(){return this.hitGraphEnabled(!1),this},e.prototype.setHitGraphEnabled=function(t){i.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)},e.prototype.getHitGraphEnabled=function(t){return i.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()},e.prototype.toggleHitCanvas=function(){if(this.parent){var t=this.parent,e=!!this.hitCanvas._canvas.parentNode;e?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}},e}(o.Container);e.Layer=m,m.prototype.nodeType="Layer",f._registerNode(m),s.Factory.addGetterSetter(m,"imageSmoothingEnabled",!0),s.Factory.addGetterSetter(m,"clearBeforeDraw",!0),s.Factory.addGetterSetter(m,"hitGraphEnabled",!0,c.getBooleanValidator()),i.Collection.mapMethods(m)},"100e":function(t,e,n){var r=n("cd9d"),i=n("2286"),o=n("c1c9");function a(t,e){return o(i(t,e,r),t+"")}t.exports=a},"122f":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Threshold=void 0;var r=n("f0b4"),i=n("4971"),o=n("4546"),a=function(t){var e,n=255*this.threshold(),r=t.data,i=r.length;for(e=0;e4;o&&(i=this.getTensionPoints());var a,s,u=r.length;o?(a=r[u-2]-(i[i.length-2]+i[i.length-4])/2,s=r[u-1]-(i[i.length-1]+i[i.length-3])/2):(a=r[u-2]-r[u-4],s=r[u-1]-r[u-3]);var c=(Math.atan2(s,a)+n)%n,l=this.pointerLength(),f=this.pointerWidth();e.save(),e.beginPath(),e.translate(r[u-2],r[u-1]),e.rotate(c),e.moveTo(0,0),e.lineTo(-l,f/2),e.lineTo(-l,-f/2),e.closePath(),e.restore(),this.pointerAtBeginning()&&(e.save(),e.translate(r[0],r[1]),o?(a=(i[0]+i[2])/2-r[0],s=(i[1]+i[3])/2-r[1]):(a=r[2]-r[0],s=r[3]-r[1]),e.rotate((Math.atan2(-s,-a)+n)%n),e.moveTo(0,0),e.lineTo(-l,f/2),e.lineTo(-l,-f/2),e.closePath(),e.restore());var h=this.dashEnabled();h&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),h&&(this.attrs.dashEnabled=!0)},e.prototype.getSelfRect=function(){var e=t.prototype.getSelfRect.call(this),n=this.pointerWidth()/2;return{x:e.x-n,y:e.y-n,width:e.width+2*n,height:e.height+2*n}},e}(a.Line);e.Arrow=c,c.prototype.className="Arrow",u._registerNode(c),o.Factory.addGetterSetter(c,"pointerLength",10,s.getNumberValidator()),o.Factory.addGetterSetter(c,"pointerWidth",10,s.getNumberValidator()),o.Factory.addGetterSetter(c,"pointerAtBeginning",!1),i.Collection.mapMethods(c)},"1c3c":function(t,e,n){var r=n("9e69"),i=n("2474"),o=n("9638"),a=n("a2be"),s=n("edfa"),u=n("ac41"),c=1,l=2,f="[object Boolean]",h="[object Date]",d="[object Error]",p="[object Map]",v="[object Number]",g="[object RegExp]",m="[object Set]",y="[object String]",b="[object Symbol]",_="[object ArrayBuffer]",w="[object DataView]",x=r?r.prototype:void 0,S=x?x.valueOf:void 0;function k(t,e,n,r,x,k,C){switch(n){case w:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case _:return!(t.byteLength!=e.byteLength||!k(new i(t),new i(e)));case f:case h:case v:return o(+t,+e);case d:return t.name==e.name&&t.message==e.message;case g:case y:return t==e+"";case p:var O=s;case m:var P=r&c;if(O||(O=u),t.size!=e.size&&!P)return!1;var T=C.get(t);if(T)return T==e;r|=l,C.set(t,e);var A=a(O(t),O(e),r,x,k,C);return C["delete"](t),A;case b:if(S)return S.call(t)==S.call(e)}return!1}t.exports=k},"1c49":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Kaleidoscope=void 0;var r=n("f0b4"),i=n("4971"),o=n("9cb8"),a=n("4546"),s=function(t,e,n){var r,i,o,a,s=t.data,u=e.data,c=t.width,l=t.height,f=n.polarCenterX||c/2,h=n.polarCenterY||l/2,d=0,p=0,v=0,g=0,m=Math.sqrt(f*f+h*h);i=c-f,o=l-h,a=Math.sqrt(i*i+o*o),m=a>m?a:m;var y,b,_,w,x=l,S=c,k=360/S*Math.PI/180;for(b=0;bb?u:b;var _,w,x,S,k=h,C=f,O=n.polarRotation||0;for(i=0;ip&&(S=x,k=0,C=-1),n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?a:a.$sub[0]:null;return{output:o,params:s}}},computed:{run:function(){var t=this,e=this.lazyParentModel(),n=Array.isArray(e)&&e.__ob__;if(n){var r=e.__ob__.dep;r.depend();var i=r.constructor.target;if(!this._indirectWatcher){var o=i.constructor;this._indirectWatcher=new o(this,(function(){return t.runRule(e)}),null,{lazy:!0})}var a=this.getModel();if(!this._indirectWatcher.dirty&&this._lastModel===a)return this._indirectWatcher.depend(),i.value;this._lastModel=a,this._indirectWatcher.evaluate(),this._indirectWatcher.depend()}else this._indirectWatcher&&(this._indirectWatcher.teardown(),this._indirectWatcher=null);return this._indirectWatcher?this._indirectWatcher.value:this.runRule(e)},$params:function(){return this.run.params},proxy:function(){var t=this.run.output;return t[w]?!!t.v:!!t},$pending:function(){var t=this.run.output;return!!t[w]&&t.p}},destroyed:function(){this._indirectWatcher&&(this._indirectWatcher.teardown(),this._indirectWatcher=null)}}),a=e.extend({data:function(){return{dirty:!1,validations:null,lazyModel:null,model:null,prop:null,lazyParentModel:null,rootModel:null}},methods:h(h({},C),{},{refProxy:function(t){return this.getRef(t).proxy},getRef:function(t){return this.refs[t]},isNested:function(t){return"function"!==typeof this.validations[t]}}),computed:h(h({},S),{},{nestedKeys:function(){return this.keys.filter(this.isNested)},ruleKeys:function(){var t=this;return this.keys.filter((function(e){return!t.isNested(e)}))},keys:function(){return Object.keys(this.validations).filter((function(t){return"$params"!==t}))},proxy:function(){var t=this,e=g(this.keys,(function(e){return{enumerable:!0,configurable:!0,get:function(){return t.refProxy(e)}}})),n=g(O,(function(e){return{enumerable:!0,configurable:!0,get:function(){return t[e]}}})),r=g(P,(function(e){return{enumerable:!1,configurable:!0,get:function(){return t[e]}}})),i=this.hasIter()?{$iter:{enumerable:!0,value:Object.defineProperties({},h({},e))}}:{};return Object.defineProperties({},h(h(h(h({},e),i),{},{$model:{enumerable:!0,get:function(){var e=t.lazyParentModel();return null!=e?e[t.prop]:null},set:function(e){var n=t.lazyParentModel();null!=n&&(n[t.prop]=e,t.$touch())}}},n),r))},children:function(){var t=this;return[].concat(o(this.nestedKeys.map((function(e){return c(t,e)}))),o(this.ruleKeys.map((function(e){return l(t,e)})))).filter(Boolean)}})}),s=a.extend({methods:{isNested:function(t){return"undefined"!==typeof this.validations[t]()},getRef:function(t){var e=this;return{get proxy(){return e.validations[t]()||!1}}}}}),u=a.extend({computed:{keys:function(){var t=this.getModel();return y(t)?Object.keys(t):[]},tracker:function(){var t=this,e=this.validations.$trackBy;return e?function(n){return"".concat(_(t.rootModel,t.getModelKey(n),e))}:function(t){return"".concat(t)}},getModelLazy:function(){var t=this;return function(){return t.getModel()}},children:function(){var t=this,e=this.validations,n=this.getModel(),i=h({},e);delete i["$trackBy"];var o={};return this.keys.map((function(e){var s=t.tracker(e);return o.hasOwnProperty(s)?null:(o[s]=!0,(0,r.h)(a,s,{validations:i,prop:e,lazyParentModel:t.getModelLazy,model:n[e],rootModel:t.rootModel}))})).filter(Boolean)}},methods:{isNested:function(){return!0},getRef:function(t){return this.refs[this.tracker(t)]},hasIter:function(){return!0}}}),c=function(t,e){if("$each"===e)return(0,r.h)(u,e,{validations:t.validations[e],lazyParentModel:t.lazyParentModel,prop:e,lazyModel:t.getModel,rootModel:t.rootModel});var n=t.validations[e];if(Array.isArray(n)){var i=t.rootModel,o=g(n,(function(t){return function(){return _(i,i.$v,t)}}),(function(t){return Array.isArray(t)?t.join("."):t}));return(0,r.h)(s,e,{validations:o,lazyParentModel:v,prop:e,lazyModel:v,rootModel:i})}return(0,r.h)(a,e,{validations:n,lazyParentModel:t.getModel,prop:e,lazyModel:t.getModelKey,rootModel:t.rootModel})},l=function(t,e){return(0,r.h)(n,e,{rule:t.validations[e],lazyParentModel:t.lazyParentModel,lazyModel:t.getModel,rootModel:t.rootModel})};return T={VBase:e,Validation:a},T},E=null;function j(t){if(E)return E;var e=t.constructor;while(e.super)e=e.super;return E=e,e}var M=function(t,e){var n=j(t),i=A(n),o=i.Validation,a=i.VBase,s=new a({computed:{children:function(){var n="function"===typeof e?e.call(t):e;return[(0,r.h)(o,"$v",{validations:n,lazyParentModel:v,prop:"$v",model:t,rootModel:t})]}}});return s},R={data:function(){var t=this.$options.validations;return t&&(this._vuelidate=M(this,t)),{}},beforeCreate:function(){var t=this.$options,e=t.validations;e&&(t.computed||(t.computed={}),t.computed.$v||(t.computed.$v=function(){return this._vuelidate?this._vuelidate.refs.$v.proxy:null}))},beforeDestroy:function(){this._vuelidate&&(this._vuelidate.$destroy(),this._vuelidate=null)}};function D(t){t.mixin(R)}e.validationMixin=R;var I=D;e.default=I},"1efc":function(t,e){function n(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}t.exports=n},"1f21":function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0}),e.Circle=void 0;var i=n("9cb8"),o=n("f0b4"),a=n("fce6"),s=n("4546"),u=n("d777"),c=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r(e,t),e.prototype._sceneFunc=function(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,2*Math.PI,!1),t.closePath(),t.fillStrokeShape(this)},e.prototype.getWidth=function(){return 2*this.radius()},e.prototype.getHeight=function(){return 2*this.radius()},e.prototype.setWidth=function(t){this.radius()!==t/2&&this.radius(t/2)},e.prototype.setHeight=function(t){this.radius()!==t/2&&this.radius(t/2)},e}(a.Shape);e.Circle=c,c.prototype._centroid=!0,c.prototype.className="Circle",c.prototype._attrsAffectingSize=["radius"],u._registerNode(c),o.Factory.addGetterSetter(c,"radius",0,s.getNumberValidator()),i.Collection.mapMethods(c)},"1fb5":function(t,e,n){"use strict";e.byteLength=l,e.toByteArray=h,e.fromByteArray=v;for(var r=[],i=[],o="undefined"!==typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");-1===n&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function l(t){var e=c(t),n=e[0],r=e[1];return 3*(n+r)/4-r}function f(t,e,n){return 3*(e+n)/4-n}function h(t){var e,n,r=c(t),a=r[0],s=r[1],u=new o(f(t,a,s)),l=0,h=s>0?a-4:a;for(n=0;n>16&255,u[l++]=e>>8&255,u[l++]=255&e;return 2===s&&(e=i[t.charCodeAt(n)]<<2|i[t.charCodeAt(n+1)]>>4,u[l++]=255&e),1===s&&(e=i[t.charCodeAt(n)]<<10|i[t.charCodeAt(n+1)]<<4|i[t.charCodeAt(n+2)]>>2,u[l++]=e>>8&255,u[l++]=255&e),u}function d(t){return r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}function p(t,e,n){for(var r,i=[],o=e;ou?u:s+a));return 1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},"1fc8":function(t,e,n){var r=n("4245");function i(t,e){var n=r(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this}t.exports=i},2013:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Posterize=void 0;var r=n("f0b4"),i=n("4971"),o=n("4546"),a=function(t){var e,n=Math.round(254*this.levels())+1,r=t.data,i=r.length,o=255/n;for(e=0;e=1){var n=e[0].p0;t.moveTo(n.x,n.y)}for(var r=0;r0&&(a+=t.dataArray[c].pathLength);var l=0;"center"===r&&(l=Math.max(0,a/2-o/2)),"right"===r&&(l=Math.max(0,a-o));for(var f,h,d,p=u.stringToArray(this.text()),v=this.text().split(" ").length-1,g=-1,m=0,y=function(){m=0;for(var e=t.dataArray,n=g+1;n0)return g=n,e[n];"M"===e[n].command&&(f={x:e[n].points[0],y:e[n].points[1]})}return{}},b=function(e){var i=t._getTextSize(e).width+n;" "===e&&"justify"===r&&(i+=(a-o)/v);var u=0,c=0;h=void 0;while(Math.abs(i-u)/i>.01&&c<20){c++;var l=u;while(void 0===d)d=y(),d&&l+d.pathLengthi?h=s.Path.getPointOnLine(i,f.x,f.y,d.points[0],d.points[1],f.x,f.y):d=void 0;break;case"A":var g=d.points[4],b=d.points[5],_=d.points[4]+b;0===m?m=g+1e-8:i>u?m+=Math.PI/180*b/Math.abs(b):m-=Math.PI/360*b/Math.abs(b),(b<0&&m<_||b>=0&&m>_)&&(m=_,p=!0),h=s.Path.getPointOnEllipticalArc(d.points[0],d.points[1],d.points[2],d.points[3],m,d.points[6]);break;case"C":0===m?m=i>d.pathLength?1e-8:i/d.pathLength:i>u?m+=(i-u)/d.pathLength/2:m=Math.max(m-(u-i)/d.pathLength/2,0),m>1&&(m=1,p=!0),h=s.Path.getPointOnCubicBezier(m,d.start.x,d.start.y,d.points[0],d.points[1],d.points[2],d.points[3],d.points[4],d.points[5]);break;case"Q":0===m?m=i/d.pathLength:i>u?m+=(i-u)/d.pathLength:m-=(u-i)/d.pathLength,m>1&&(m=1,p=!0),h=s.Path.getPointOnQuadraticBezier(m,d.start.x,d.start.y,d.points[0],d.points[1],d.points[2],d.points[3]);break}void 0!==h&&(u=s.Path.getLineLength(f.x,f.y,h.x,h.y)),p&&(p=!1,d=void 0)}},_="C",w=t._getTextSize(_).width+n,x=l/w-1,S=0;S=0&&Math.floor(e)===e&&isFinite(t)}function g(t){return a(t)&&"function"===typeof t.then&&"function"===typeof t.catch}function m(t){return null==t?"":Array.isArray(t)||d(t)&&t.toString===h?JSON.stringify(t,null,2):String(t)}function y(t){var e=parseFloat(t);return isNaN(e)?t:e}function b(t,e){for(var n=Object.create(null),r=t.split(","),i=0;i-1)return t.splice(n,1)}}var x=Object.prototype.hasOwnProperty;function S(t,e){return x.call(t,e)}function k(t){var e=Object.create(null);return function(n){var r=e[n];return r||(e[n]=t(n))}}var C=/-(\w)/g,O=k((function(t){return t.replace(C,(function(t,e){return e?e.toUpperCase():""}))})),P=k((function(t){return t.charAt(0).toUpperCase()+t.slice(1)})),T=/\B([A-Z])/g,A=k((function(t){return t.replace(T,"-$1").toLowerCase()}));function E(t,e){function n(n){var r=arguments.length;return r?r>1?t.apply(e,arguments):t.call(e,n):t.call(e)}return n._length=t.length,n}function j(t,e){return t.bind(e)}var M=Function.prototype.bind?j:E;function R(t,e){e=e||0;var n=t.length-e,r=new Array(n);while(n--)r[n]=t[n+e];return r}function D(t,e){for(var n in e)t[n]=e[n];return t}function I(t){for(var e={},n=0;n0,rt=tt&&tt.indexOf("edge/")>0;tt&&tt.indexOf("android");var it=tt&&/iphone|ipad|ipod|ios/.test(tt);tt&&/chrome\/\d+/.test(tt),tt&&/phantomjs/.test(tt);var ot,at=tt&&tt.match(/firefox\/(\d+)/),st={}.watch,ut=!1;if(Q)try{var ct={};Object.defineProperty(ct,"passive",{get:function(){ut=!0}}),window.addEventListener("test-passive",null,ct)}catch(eu){}var lt=function(){return void 0===ot&&(ot=!Q&&"undefined"!==typeof t&&(t["process"]&&"server"===t["process"].env.VUE_ENV)),ot},ft=Q&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function ht(t){return"function"===typeof t&&/native code/.test(t.toString())}var dt,pt="undefined"!==typeof Symbol&&ht(Symbol)&&"undefined"!==typeof Reflect&&ht(Reflect.ownKeys);dt="undefined"!==typeof Set&&ht(Set)?Set:function(){function t(){this.set=Object.create(null)}return t.prototype.has=function(t){return!0===this.set[t]},t.prototype.add=function(t){this.set[t]=!0},t.prototype.clear=function(){this.set=Object.create(null)},t}();var vt=null;function gt(){return vt&&{proxy:vt}}function mt(t){void 0===t&&(t=null),t||vt&&vt._scope.off(),vt=t,t&&t._scope.on()}var yt=function(){function t(t,e,n,r,i,o,a,s){this.tag=t,this.data=e,this.children=n,this.text=r,this.elm=i,this.ns=void 0,this.context=o,this.fnContext=void 0,this.fnOptions=void 0,this.fnScopeId=void 0,this.key=e&&e.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1,this.asyncFactory=s,this.asyncMeta=void 0,this.isAsyncPlaceholder=!1}return Object.defineProperty(t.prototype,"child",{get:function(){return this.componentInstance},enumerable:!1,configurable:!0}),t}(),bt=function(t){void 0===t&&(t="");var e=new yt;return e.text=t,e.isComment=!0,e};function _t(t){return new yt(void 0,void 0,void 0,String(t))}function wt(t){var e=new yt(t.tag,t.data,t.children&&t.children.slice(),t.text,t.elm,t.context,t.componentOptions,t.asyncFactory);return e.ns=t.ns,e.isStatic=t.isStatic,e.key=t.key,e.isComment=t.isComment,e.fnContext=t.fnContext,e.fnOptions=t.fnOptions,e.fnScopeId=t.fnScopeId,e.asyncMeta=t.asyncMeta,e.isCloned=!0,e}var xt=0,St=function(){function t(){this.id=xt++,this.subs=[]}return t.prototype.addSub=function(t){this.subs.push(t)},t.prototype.removeSub=function(t){w(this.subs,t)},t.prototype.depend=function(e){t.target&&t.target.addDep(this)},t.prototype.notify=function(t){var e=this.subs.slice();for(var n=0,r=e.length;n1)return n&&l(e)?e.call(r):e}else 0}var De=k((function(t){var e="&"===t.charAt(0);t=e?t.slice(1):t;var n="~"===t.charAt(0);t=n?t.slice(1):t;var r="!"===t.charAt(0);return t=r?t.slice(1):t,{name:t,once:n,capture:r,passive:e}}));function Ie(t,e){function n(){var t=n.fns;if(!i(t))return Nn(t,null,arguments,e,"v-on handler");for(var r=t.slice(),o=0;o0&&(r=ze(r,"".concat(e||"","_").concat(n)),Ge(r[0])&&Ge(l)&&(f[u]=_t(l.text+r[0].text),r.shift()),f.push.apply(f,r)):c(r)?Ge(l)?f[u]=_t(l.text+r):""!==r&&f.push(_t(r)):Ge(r)&&Ge(l)?f[u]=_t(l.text+r.text):(s(t._isVList)&&a(r.tag)&&o(r.key)&&a(e)&&(r.key="__vlist".concat(e,"_").concat(n,"__")),f.push(r)));return f}function Ve(t,e){var n,r,o,s,u=null;if(i(t)||"string"===typeof t)for(u=new Array(t.length),n=0,r=t.length;n0,s=e?!!e.$stable:!a,u=e&&e.$key;if(e){if(e._normalized)return e._normalized;if(s&&i&&i!==r&&u===i.$key&&!a&&!i.$hasNormal)return i;for(var c in o={},e)e[c]&&"$"!==c[0]&&(o[c]=ln(t,n,c,e[c]))}else o={};for(var l in n)l in o||(o[l]=fn(n,l));return e&&Object.isExtensible(e)&&(e._normalized=o),K(o,"$stable",s),K(o,"$key",u),K(o,"$hasNormal",a),o}function ln(t,e,n,r){var o=function(){var e=vt;mt(t);var n=arguments.length?r.apply(null,arguments):r({});n=n&&"object"===typeof n&&!i(n)?[n]:Be(n);var o=n&&n[0];return mt(e),n&&(!o||1===n.length&&o.isComment&&!un(o))?void 0:n};return r.proxy&&Object.defineProperty(e,n,{get:o,enumerable:!0,configurable:!0}),o}function fn(t,e){return function(){return t[e]}}function hn(t){var e=t.$options,n=e.setup;if(n){var r=t._setupContext=dn(t);mt(t),Ct();var i=Nn(n,null,[t._props||Gt({}),r],t,"setup");if(Ot(),mt(),l(i))e.render=i;else if(f(i))if(t._setupState=i,i.__sfc){var o=t._setupProxy={};for(var a in i)"__sfc"!==a&&ie(o,i,a)}else for(var a in i)Y(a)||ie(t,i,a);else 0}}function dn(t){return{get attrs(){if(!t._attrsProxy){var e=t._attrsProxy={};K(e,"_v_attr_proxy",!0),pn(e,t.$attrs,r,t,"$attrs")}return t._attrsProxy},get listeners(){if(!t._listenersProxy){var e=t._listenersProxy={};pn(e,t.$listeners,r,t,"$listeners")}return t._listenersProxy},get slots(){return gn(t)},emit:M(t.$emit,t),expose:function(e){e&&Object.keys(e).forEach((function(n){return ie(t,e,n)}))}}}function pn(t,e,n,r,i){var o=!1;for(var a in e)a in t?e[a]!==n[a]&&(o=!0):(o=!0,vn(t,a,r,i));for(var a in t)a in e||(o=!0,delete t[a]);return o}function vn(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get:function(){return n[r][e]}})}function gn(t){return t._slotsProxy||mn(t._slotsProxy={},t.$scopedSlots),t._slotsProxy}function mn(t,e){for(var n in e)t[n]=e[n];for(var n in t)n in e||delete t[n]}function yn(){return wn().slots}function bn(){return wn().attrs}function _n(){return wn().listeners}function wn(){var t=vt;return t._setupContext||(t._setupContext=dn(t))}function xn(t,e){var n=i(t)?t.reduce((function(t,e){return t[e]={},t}),{}):t;for(var r in e){var o=n[r];o?i(o)||l(o)?n[r]={type:o,default:e[r]}:o.default=e[r]:null===o&&(n[r]={default:e[r]})}return n}function Sn(t){t._vnode=null,t._staticTrees=null;var e=t.$options,n=t.$vnode=e._parentVnode,i=n&&n.context;t.$slots=an(e._renderChildren,i),t.$scopedSlots=n?cn(t.$parent,n.data.scopedSlots,t.$slots):r,t._c=function(e,n,r,i){return Mn(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Mn(t,e,n,r,i,!0)};var o=n&&n.data;$t(t,"$attrs",o&&o.attrs||r,null,!0),$t(t,"$listeners",e._parentListeners||r,null,!0)}var kn=null;function Cn(t){on(t.prototype),t.prototype.$nextTick=function(t){return Xn(t,this)},t.prototype._render=function(){var t,e=this,n=e.$options,r=n.render,o=n._parentVnode;o&&e._isMounted&&(e.$scopedSlots=cn(e.$parent,o.data.scopedSlots,e.$slots,e.$scopedSlots),e._slotsProxy&&mn(e._slotsProxy,e.$scopedSlots)),e.$vnode=o;try{mt(e),kn=e,t=r.call(e._renderProxy,e.$createElement)}catch(eu){$n(eu,e,"render"),t=e._vnode}finally{kn=null,mt()}return i(t)&&1===t.length&&(t=t[0]),t instanceof yt||(t=bt()),t.parent=o,t}}function On(t,e){return(t.__esModule||pt&&"Module"===t[Symbol.toStringTag])&&(t=t.default),f(t)?e.extend(t):t}function Pn(t,e,n,r,i){var o=bt();return o.asyncFactory=t,o.asyncMeta={data:e,context:n,children:r,tag:i},o}function Tn(t,e){if(s(t.error)&&a(t.errorComp))return t.errorComp;if(a(t.resolved))return t.resolved;var n=kn;if(n&&a(t.owners)&&-1===t.owners.indexOf(n)&&t.owners.push(n),s(t.loading)&&a(t.loadingComp))return t.loadingComp;if(n&&!a(t.owners)){var r=t.owners=[n],i=!0,u=null,c=null;n.$on("hook:destroyed",(function(){return w(r,n)}));var l=function(t){for(var e=0,n=r.length;e1?R(n):n;for(var r=R(arguments,1),i='event handler for "'.concat(t,'"'),o=0,a=n.length;odocument.createEvent("Event").timeStamp&&(qr=function(){return Hr.now()})}var Yr=function(t,e){if(t.post){if(!e.post)return 1}else if(e.post)return-1;return t.id-e.id};function Kr(){var t,e;for(Wr=qr(),Gr=!0,Nr.sort(Yr),zr=0;zrzr&&Nr[n].id>t.id)n--;Nr.splice(n+1,0,t)}else Nr.push(t);Br||(Br=!0,Xn(Kr))}}function ti(t){var e=t.$options.provide;if(e){var n=l(e)?e.call(t):e;if(!f(n))return;for(var r=Me(t),i=pt?Reflect.ownKeys(n):Object.keys(n),o=0;o-1)if(o&&!S(i,"default"))a=!1;else if(""===a||a===A(t)){var u=Ri(String,i.type);(u<0||s-1)return this;var n=R(arguments,1);return n.unshift(this),l(t.install)?t.install.apply(t,n):l(t)&&t.apply(null,n),e.push(t),this}}function no(t){t.mixin=function(t){return this.options=Oi(this.options,t),this}}function ro(t){t.cid=0;var e=1;t.extend=function(t){t=t||{};var n=this,r=n.cid,i=t._Ctor||(t._Ctor={});if(i[r])return i[r];var o=si(t)||si(n.options);var a=function(t){this._init(t)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=e++,a.options=Oi(n.options,t),a["super"]=n,a.options.props&&io(a),a.options.computed&&oo(a),a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,V.forEach((function(t){a[t]=n[t]})),o&&(a.options.components[o]=a),a.superOptions=n.options,a.extendOptions=t,a.sealedOptions=D({},a.options),i[r]=a,a}}function io(t){var e=t.options.props;for(var n in e)Ii(t.prototype,"_props",n)}function oo(t){var e=t.options.computed;for(var n in e)Gi(t.prototype,n,e[n])}function ao(t){V.forEach((function(e){t[e]=function(t,n){return n?("component"===e&&d(n)&&(n.name=n.name||t,n=this.options._base.extend(n)),"directive"===e&&l(n)&&(n={bind:n,update:n}),this.options[e+"s"][t]=n,n):this.options[e+"s"][t]}}))}function so(t){return t&&(si(t.Ctor.options)||t.tag)}function uo(t,e){return i(t)?t.indexOf(e)>-1:"string"===typeof t?t.split(",").indexOf(e)>-1:!!p(t)&&t.test(e)}function co(t,e){var n=t.cache,r=t.keys,i=t._vnode;for(var o in n){var a=n[o];if(a){var s=a.name;s&&!e(s)&&lo(n,o,r,i)}}}function lo(t,e,n,r){var i=t[e];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),t[e]=null,w(n,e)}Xi(to),Yi(to),Pr(to),jr(to),Cn(to);var fo=[String,RegExp,Array],ho={name:"keep-alive",abstract:!0,props:{include:fo,exclude:fo,max:[String,Number]},methods:{cacheVNode:function(){var t=this,e=t.cache,n=t.keys,r=t.vnodeToCache,i=t.keyToCache;if(r){var o=r.tag,a=r.componentInstance,s=r.componentOptions;e[i]={name:so(s),tag:o,componentInstance:a},n.push(i),this.max&&n.length>parseInt(this.max)&&lo(e,n[0],n,this._vnode),this.vnodeToCache=null}}},created:function(){this.cache=Object.create(null),this.keys=[]},destroyed:function(){for(var t in this.cache)lo(this.cache,t,this.keys)},mounted:function(){var t=this;this.cacheVNode(),this.$watch("include",(function(e){co(t,(function(t){return uo(e,t)}))})),this.$watch("exclude",(function(e){co(t,(function(t){return!uo(e,t)}))}))},updated:function(){this.cacheVNode()},render:function(){var t=this.$slots.default,e=An(t),n=e&&e.componentOptions;if(n){var r=so(n),i=this,o=i.include,a=i.exclude;if(o&&(!r||!uo(o,r))||a&&r&&uo(a,r))return e;var s=this,u=s.cache,c=s.keys,l=null==e.key?n.Ctor.cid+(n.tag?"::".concat(n.tag):""):e.key;u[l]?(e.componentInstance=u[l].componentInstance,w(c,l),c.push(l)):(this.vnodeToCache=e,this.keyToCache=l),e.data.keepAlive=!0}return e||t&&t[0]}},po={KeepAlive:ho};function vo(t){var e={get:function(){return q}};Object.defineProperty(t,"config",e),t.util={warn:vi,extend:D,mergeOptions:Oi,defineReactive:$t},t.set=Nt,t.delete=Ft,t.nextTick=Xn,t.observable=function(t){return Lt(t),t},t.options=Object.create(null),V.forEach((function(e){t.options[e+"s"]=Object.create(null)})),t.options._base=t,D(t.options.components,po),eo(t),no(t),ro(t),ao(t)}vo(to),Object.defineProperty(to.prototype,"$isServer",{get:lt}),Object.defineProperty(to.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(to,"FunctionalRenderContext",{value:ri}),to.version=pr;var go=b("style,class"),mo=b("input,textarea,option,select,progress"),yo=function(t,e,n){return"value"===n&&mo(t)&&"button"!==e||"selected"===n&&"option"===t||"checked"===n&&"input"===t||"muted"===n&&"video"===t},bo=b("contenteditable,draggable,spellcheck"),_o=b("events,caret,typing,plaintext-only"),wo=function(t,e){return Oo(e)||"false"===e?"false":"contenteditable"===t&&_o(e)?e:"true"},xo=b("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible"),So="http://www.w3.org/1999/xlink",ko=function(t){return":"===t.charAt(5)&&"xlink"===t.slice(0,5)},Co=function(t){return ko(t)?t.slice(6,t.length):""},Oo=function(t){return null==t||!1===t};function Po(t){var e=t.data,n=t,r=t;while(a(r.componentInstance))r=r.componentInstance._vnode,r&&r.data&&(e=To(r.data,e));while(a(n=n.parent))n&&n.data&&(e=To(e,n.data));return Ao(e.staticClass,e.class)}function To(t,e){return{staticClass:Eo(t.staticClass,e.staticClass),class:a(t.class)?[t.class,e.class]:e.class}}function Ao(t,e){return a(t)||a(e)?Eo(t,jo(e)):""}function Eo(t,e){return t?e?t+" "+e:t:e||""}function jo(t){return Array.isArray(t)?Mo(t):f(t)?Ro(t):"string"===typeof t?t:""}function Mo(t){for(var e,n="",r=0,i=t.length;r-1?Fo[t]=e.constructor===window.HTMLUnknownElement||e.constructor===window.HTMLElement:Fo[t]=/HTMLUnknownElement/.test(e.toString())}var Bo=b("text,number,password,search,email,tel,url");function Go(t){if("string"===typeof t){var e=document.querySelector(t);return e||document.createElement("div")}return t}function zo(t,e){var n=document.createElement(t);return"select"!==t||e.data&&e.data.attrs&&void 0!==e.data.attrs.multiple&&n.setAttribute("multiple","multiple"),n}function Vo(t,e){return document.createElementNS(Do[t],e)}function Wo(t){return document.createTextNode(t)}function qo(t){return document.createComment(t)}function Ho(t,e,n){t.insertBefore(e,n)}function Yo(t,e){t.removeChild(e)}function Ko(t,e){t.appendChild(e)}function Xo(t){return t.parentNode}function Jo(t){return t.nextSibling}function Zo(t){return t.tagName}function Qo(t,e){t.textContent=e}function ta(t,e){t.setAttribute(e,"")}var ea=Object.freeze({__proto__:null,createElement:zo,createElementNS:Vo,createTextNode:Wo,createComment:qo,insertBefore:Ho,removeChild:Yo,appendChild:Ko,parentNode:Xo,nextSibling:Jo,tagName:Zo,setTextContent:Qo,setStyleScope:ta}),na={create:function(t,e){ra(e)},update:function(t,e){t.data.ref!==e.data.ref&&(ra(t,!0),ra(e))},destroy:function(t){ra(t,!0)}};function ra(t,e){var n=t.data.ref;if(a(n)){var r=t.context,o=t.componentInstance||t.elm,s=e?null:o,u=e?void 0:o;if(l(n))Nn(n,r,[s],r,"template ref function");else{var c=t.data.refInFor,f="string"===typeof n||"number"===typeof n,h=Jt(n),d=r.$refs;if(f||h)if(c){var p=f?d[n]:n.value;e?i(p)&&w(p,o):i(p)?p.includes(o)||p.push(o):f?(d[n]=[o],ia(r,n,d[n])):n.value=[o]}else if(f){if(e&&d[n]!==o)return;d[n]=u,ia(r,n,s)}else if(h){if(e&&n.value!==o)return;n.value=s}else 0}}}function ia(t,e,n){var r=t._setupState;r&&S(r,e)&&(Jt(r[e])?r[e].value=n:r[e]=n)}var oa=new yt("",{},[]),aa=["create","activate","update","remove","destroy"];function sa(t,e){return t.key===e.key&&t.asyncFactory===e.asyncFactory&&(t.tag===e.tag&&t.isComment===e.isComment&&a(t.data)===a(e.data)&&ua(t,e)||s(t.isAsyncPlaceholder)&&o(e.asyncFactory.error))}function ua(t,e){if("input"!==t.tag)return!0;var n,r=a(n=t.data)&&a(n=n.attrs)&&n.type,i=a(n=e.data)&&a(n=n.attrs)&&n.type;return r===i||Bo(r)&&Bo(i)}function ca(t,e,n){var r,i,o={};for(r=e;r<=n;++r)i=t[r].key,a(i)&&(o[i]=r);return o}function la(t){var e,n,r={},u=t.modules,l=t.nodeOps;for(e=0;ev?(f=o(n[y+1])?null:n[y+1].elm,k(t,f,n,d,y,r)):d>y&&O(e,h,v)}function A(t,e,n,r){for(var i=n;i-1?wa(t,e,n):xo(e)?Oo(n)?t.removeAttribute(e):(n="allowfullscreen"===e&&"EMBED"===t.tagName?"true":e,t.setAttribute(e,n)):bo(e)?t.setAttribute(e,wo(e,n)):ko(e)?Oo(n)?t.removeAttributeNS(So,Co(e)):t.setAttributeNS(So,e,n):wa(t,e,n)}function wa(t,e,n){if(Oo(n))t.removeAttribute(e);else{if(et&&!nt&&"TEXTAREA"===t.tagName&&"placeholder"===e&&""!==n&&!t.__ieph){var r=function(e){e.stopImmediatePropagation(),t.removeEventListener("input",r)};t.addEventListener("input",r),t.__ieph=!0}t.setAttribute(e,n)}}var xa={create:ba,update:ba};function Sa(t,e){var n=e.elm,r=e.data,i=t.data;if(!(o(r.staticClass)&&o(r.class)&&(o(i)||o(i.staticClass)&&o(i.class)))){var s=Po(e),u=n._transitionClasses;a(u)&&(s=Eo(s,jo(u))),s!==n._prevClass&&(n.setAttribute("class",s),n._prevClass=s)}}var ka,Ca={create:Sa,update:Sa},Oa="__r",Pa="__c";function Ta(t){if(a(t[Oa])){var e=et?"change":"input";t[e]=[].concat(t[Oa],t[e]||[]),delete t[Oa]}a(t[Pa])&&(t.change=[].concat(t[Pa],t.change||[]),delete t[Pa])}function Aa(t,e,n){var r=ka;return function i(){var o=e.apply(null,arguments);null!==o&&Ma(t,i,n,r)}}var Ea=Gn&&!(at&&Number(at[1])<=53);function ja(t,e,n,r){if(Ea){var i=Wr,o=e;e=o._wrapper=function(t){if(t.target===t.currentTarget||t.timeStamp>=i||t.timeStamp<=0||t.target.ownerDocument!==document)return o.apply(this,arguments)}}ka.addEventListener(t,e,ut?{capture:n,passive:r}:n)}function Ma(t,e,n,r){(r||ka).removeEventListener(t,e._wrapper||e,n)}function Ra(t,e){if(!o(t.data.on)||!o(e.data.on)){var n=e.data.on||{},r=t.data.on||{};ka=e.elm||t.elm,Ta(n),Le(n,r,ja,Ma,Aa,e.context),ka=void 0}}var Da,Ia={create:Ra,update:Ra,destroy:function(t){return Ra(t,oa)}};function La(t,e){if(!o(t.data.domProps)||!o(e.data.domProps)){var n,r,i=e.elm,u=t.data.domProps||{},c=e.data.domProps||{};for(n in(a(c.__ob__)||s(c._v_attr_proxy))&&(c=e.data.domProps=D({},c)),u)n in c||(i[n]="");for(n in c){if(r=c[n],"textContent"===n||"innerHTML"===n){if(e.children&&(e.children.length=0),r===u[n])continue;1===i.childNodes.length&&i.removeChild(i.childNodes[0])}if("value"===n&&"PROGRESS"!==i.tagName){i._value=r;var l=o(r)?"":String(r);$a(i,l)&&(i.value=l)}else if("innerHTML"===n&&Lo(i.tagName)&&o(i.innerHTML)){Da=Da||document.createElement("div"),Da.innerHTML="".concat(r,"");var f=Da.firstChild;while(i.firstChild)i.removeChild(i.firstChild);while(f.firstChild)i.appendChild(f.firstChild)}else if(r!==u[n])try{i[n]=r}catch(eu){}}}}function $a(t,e){return!t.composing&&("OPTION"===t.tagName||Na(t,e)||Fa(t,e))}function Na(t,e){var n=!0;try{n=document.activeElement!==t}catch(eu){}return n&&t.value!==e}function Fa(t,e){var n=t.value,r=t._vModifiers;if(a(r)){if(r.number)return y(n)!==y(e);if(r.trim)return n.trim()!==e.trim()}return n!==e}var Ua={create:La,update:La},Ba=k((function(t){var e={},n=/;(?![^(]*\))/g,r=/:(.+)/;return t.split(n).forEach((function(t){if(t){var n=t.split(r);n.length>1&&(e[n[0].trim()]=n[1].trim())}})),e}));function Ga(t){var e=za(t.style);return t.staticStyle?D(t.staticStyle,e):e}function za(t){return Array.isArray(t)?I(t):"string"===typeof t?Ba(t):t}function Va(t,e){var n,r={};if(e){var i=t;while(i.componentInstance)i=i.componentInstance._vnode,i&&i.data&&(n=Ga(i.data))&&D(r,n)}(n=Ga(t.data))&&D(r,n);var o=t;while(o=o.parent)o.data&&(n=Ga(o.data))&&D(r,n);return r}var Wa,qa=/^--/,Ha=/\s*!important$/,Ya=function(t,e,n){if(qa.test(e))t.style.setProperty(e,n);else if(Ha.test(n))t.style.setProperty(A(e),n.replace(Ha,""),"important");else{var r=Xa(e);if(Array.isArray(n))for(var i=0,o=n.length;i-1?e.split(Qa).forEach((function(e){return t.classList.add(e)})):t.classList.add(e);else{var n=" ".concat(t.getAttribute("class")||""," ");n.indexOf(" "+e+" ")<0&&t.setAttribute("class",(n+e).trim())}}function es(t,e){if(e&&(e=e.trim()))if(t.classList)e.indexOf(" ")>-1?e.split(Qa).forEach((function(e){return t.classList.remove(e)})):t.classList.remove(e),t.classList.length||t.removeAttribute("class");else{var n=" ".concat(t.getAttribute("class")||""," "),r=" "+e+" ";while(n.indexOf(r)>=0)n=n.replace(r," ");n=n.trim(),n?t.setAttribute("class",n):t.removeAttribute("class")}}function ns(t){if(t){if("object"===typeof t){var e={};return!1!==t.css&&D(e,rs(t.name||"v")),D(e,t),e}return"string"===typeof t?rs(t):void 0}}var rs=k((function(t){return{enterClass:"".concat(t,"-enter"),enterToClass:"".concat(t,"-enter-to"),enterActiveClass:"".concat(t,"-enter-active"),leaveClass:"".concat(t,"-leave"),leaveToClass:"".concat(t,"-leave-to"),leaveActiveClass:"".concat(t,"-leave-active")}})),is=Q&&!nt,os="transition",as="animation",ss="transition",us="transitionend",cs="animation",ls="animationend";is&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(ss="WebkitTransition",us="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(cs="WebkitAnimation",ls="webkitAnimationEnd"));var fs=Q?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(t){return t()};function hs(t){fs((function(){fs(t)}))}function ds(t,e){var n=t._transitionClasses||(t._transitionClasses=[]);n.indexOf(e)<0&&(n.push(e),ts(t,e))}function ps(t,e){t._transitionClasses&&w(t._transitionClasses,e),es(t,e)}function vs(t,e,n){var r=ms(t,e),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===os?us:ls,u=0,c=function(){t.removeEventListener(s,l),n()},l=function(e){e.target===t&&++u>=a&&c()};setTimeout((function(){u0&&(n=os,l=a,f=o.length):e===as?c>0&&(n=as,l=c,f=u.length):(l=Math.max(a,c),n=l>0?a>c?os:as:null,f=n?n===os?o.length:u.length:0);var h=n===os&&gs.test(r[ss+"Property"]);return{type:n,timeout:l,propCount:f,hasTransform:h}}function ys(t,e){while(t.length1}function ks(t,e){!0!==e.data.show&&_s(e)}var Cs=Q?{create:ks,activate:ks,remove:function(t,e){!0!==t.data.show?ws(t,e):e()}}:{},Os=[xa,Ca,Ia,Ua,Za,Cs],Ps=Os.concat(ya),Ts=la({nodeOps:ea,modules:Ps});nt&&document.addEventListener("selectionchange",(function(){var t=document.activeElement;t&&t.vmodel&&Ls(t,"input")}));var As={inserted:function(t,e,n,r){"select"===n.tag?(r.elm&&!r.elm._vOptions?$e(n,"postpatch",(function(){As.componentUpdated(t,e,n)})):Es(t,e,n.context),t._vOptions=[].map.call(t.options,Rs)):("textarea"===n.tag||Bo(t.type))&&(t._vModifiers=e.modifiers,e.modifiers.lazy||(t.addEventListener("compositionstart",Ds),t.addEventListener("compositionend",Is),t.addEventListener("change",Is),nt&&(t.vmodel=!0)))},componentUpdated:function(t,e,n){if("select"===n.tag){Es(t,e,n.context);var r=t._vOptions,i=t._vOptions=[].map.call(t.options,Rs);if(i.some((function(t,e){return!F(t,r[e])}))){var o=t.multiple?e.value.some((function(t){return Ms(t,i)})):e.value!==e.oldValue&&Ms(e.value,i);o&&Ls(t,"change")}}}};function Es(t,e,n){js(t,e,n),(et||rt)&&setTimeout((function(){js(t,e,n)}),0)}function js(t,e,n){var r=e.value,i=t.multiple;if(!i||Array.isArray(r)){for(var o,a,s=0,u=t.options.length;s-1,a.selected!==o&&(a.selected=o);else if(F(Rs(a),r))return void(t.selectedIndex!==s&&(t.selectedIndex=s));i||(t.selectedIndex=-1)}}function Ms(t,e){return e.every((function(e){return!F(e,t)}))}function Rs(t){return"_value"in t?t._value:t.value}function Ds(t){t.target.composing=!0}function Is(t){t.target.composing&&(t.target.composing=!1,Ls(t.target,"input"))}function Ls(t,e){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0),t.dispatchEvent(n)}function $s(t){return!t.componentInstance||t.data&&t.data.transition?t:$s(t.componentInstance._vnode)}var Ns={bind:function(t,e,n){var r=e.value;n=$s(n);var i=n.data&&n.data.transition,o=t.__vOriginalDisplay="none"===t.style.display?"":t.style.display;r&&i?(n.data.show=!0,_s(n,(function(){t.style.display=o}))):t.style.display=r?o:"none"},update:function(t,e,n){var r=e.value,i=e.oldValue;if(!r!==!i){n=$s(n);var o=n.data&&n.data.transition;o?(n.data.show=!0,r?_s(n,(function(){t.style.display=t.__vOriginalDisplay})):ws(n,(function(){t.style.display="none"}))):t.style.display=r?t.__vOriginalDisplay:"none"}},unbind:function(t,e,n,r,i){i||(t.style.display=t.__vOriginalDisplay)}},Fs={model:As,show:Ns},Us={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function Bs(t){var e=t&&t.componentOptions;return e&&e.Ctor.options.abstract?Bs(An(e.children)):t}function Gs(t){var e={},n=t.$options;for(var r in n.propsData)e[r]=t[r];var i=n._parentListeners;for(var r in i)e[O(r)]=i[r];return e}function zs(t,e){if(/\d-keep-alive$/.test(e.tag))return t("keep-alive",{props:e.componentOptions.propsData})}function Vs(t){while(t=t.parent)if(t.data.transition)return!0}function Ws(t,e){return e.key===t.key&&e.tag===t.tag}var qs=function(t){return t.tag||un(t)},Hs=function(t){return"show"===t.name},Ys={name:"transition",props:Us,abstract:!0,render:function(t){var e=this,n=this.$slots.default;if(n&&(n=n.filter(qs),n.length)){0;var r=this.mode;0;var i=n[0];if(Vs(this.$vnode))return i;var o=Bs(i);if(!o)return i;if(this._leaving)return zs(t,i);var a="__transition-".concat(this._uid,"-");o.key=null==o.key?o.isComment?a+"comment":a+o.tag:c(o.key)?0===String(o.key).indexOf(a)?o.key:a+o.key:o.key;var s=(o.data||(o.data={})).transition=Gs(this),u=this._vnode,l=Bs(u);if(o.data.directives&&o.data.directives.some(Hs)&&(o.data.show=!0),l&&l.data&&!Ws(o,l)&&!un(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=D({},s);if("out-in"===r)return this._leaving=!0,$e(f,"afterLeave",(function(){e._leaving=!1,e.$forceUpdate()})),zs(t,i);if("in-out"===r){if(un(o))return u;var h,d=function(){h()};$e(s,"afterEnter",d),$e(s,"enterCancelled",d),$e(f,"delayLeave",(function(t){h=t}))}}return i}}},Ks=D({tag:String,moveClass:String},Us);delete Ks.mode;var Xs={props:Ks,beforeMount:function(){var t=this,e=this._update;this._update=function(n,r){var i=Ar(t);t.__patch__(t._vnode,t.kept,!1,!0),t._vnode=t.kept,i(),e.call(t,n,r)}},render:function(t){for(var e=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=Gs(this),s=0;s=c&&(h=u,d=!1,e=new r(e));t:while(++f1?n[o-1]:void 0,s=o>2?n[2]:void 0;a=t.length>3&&"function"==typeof a?(o--,a):void 0,s&&i(n[0],n[1],s)&&(a=o<3?void 0:a,o=1),e=Object(e);while(++r + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */(function(){var o,a="4.17.21",s=200,u="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",c="Expected a function",l="Invalid `variable` option passed into `_.template`",f="__lodash_hash_undefined__",h=500,d="__lodash_placeholder__",p=1,v=2,g=4,m=1,y=2,b=1,_=2,w=4,x=8,S=16,k=32,C=64,O=128,P=256,T=512,A=30,E="...",j=800,M=16,R=1,D=2,I=3,L=1/0,$=9007199254740991,N=17976931348623157e292,F=NaN,U=4294967295,B=U-1,G=U>>>1,z=[["ary",O],["bind",b],["bindKey",_],["curry",x],["curryRight",S],["flip",T],["partial",k],["partialRight",C],["rearg",P]],V="[object Arguments]",W="[object Array]",q="[object AsyncFunction]",H="[object Boolean]",Y="[object Date]",K="[object DOMException]",X="[object Error]",J="[object Function]",Z="[object GeneratorFunction]",Q="[object Map]",tt="[object Number]",et="[object Null]",nt="[object Object]",rt="[object Promise]",it="[object Proxy]",ot="[object RegExp]",at="[object Set]",st="[object String]",ut="[object Symbol]",ct="[object Undefined]",lt="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",dt="[object DataView]",pt="[object Float32Array]",vt="[object Float64Array]",gt="[object Int8Array]",mt="[object Int16Array]",yt="[object Int32Array]",bt="[object Uint8Array]",_t="[object Uint8ClampedArray]",wt="[object Uint16Array]",xt="[object Uint32Array]",St=/\b__p \+= '';/g,kt=/\b(__p \+=) '' \+/g,Ct=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Ot=/&(?:amp|lt|gt|quot|#39);/g,Pt=/[&<>"']/g,Tt=RegExp(Ot.source),At=RegExp(Pt.source),Et=/<%-([\s\S]+?)%>/g,jt=/<%([\s\S]+?)%>/g,Mt=/<%=([\s\S]+?)%>/g,Rt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Dt=/^\w*$/,It=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Lt=/[\\^$.*+?()[\]{}|]/g,$t=RegExp(Lt.source),Nt=/^\s+/,Ft=/\s/,Ut=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Bt=/\{\n\/\* \[wrapped with (.+)\] \*/,Gt=/,? & /,zt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Vt=/[()=,{}\[\]\/\s]/,Wt=/\\(\\)?/g,qt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ht=/\w*$/,Yt=/^[-+]0x[0-9a-f]+$/i,Kt=/^0b[01]+$/i,Xt=/^\[object .+?Constructor\]$/,Jt=/^0o[0-7]+$/i,Zt=/^(?:0|[1-9]\d*)$/,Qt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,te=/($^)/,ee=/['\n\r\u2028\u2029\\]/g,ne="\\ud800-\\udfff",re="\\u0300-\\u036f",ie="\\ufe20-\\ufe2f",oe="\\u20d0-\\u20ff",ae=re+ie+oe,se="\\u2700-\\u27bf",ue="a-z\\xdf-\\xf6\\xf8-\\xff",ce="\\xac\\xb1\\xd7\\xf7",le="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",fe="\\u2000-\\u206f",he=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",de="A-Z\\xc0-\\xd6\\xd8-\\xde",pe="\\ufe0e\\ufe0f",ve=ce+le+fe+he,ge="['’]",me="["+ne+"]",ye="["+ve+"]",be="["+ae+"]",_e="\\d+",we="["+se+"]",xe="["+ue+"]",Se="[^"+ne+ve+_e+se+ue+de+"]",ke="\\ud83c[\\udffb-\\udfff]",Ce="(?:"+be+"|"+ke+")",Oe="[^"+ne+"]",Pe="(?:\\ud83c[\\udde6-\\uddff]){2}",Te="[\\ud800-\\udbff][\\udc00-\\udfff]",Ae="["+de+"]",Ee="\\u200d",je="(?:"+xe+"|"+Se+")",Me="(?:"+Ae+"|"+Se+")",Re="(?:"+ge+"(?:d|ll|m|re|s|t|ve))?",De="(?:"+ge+"(?:D|LL|M|RE|S|T|VE))?",Ie=Ce+"?",Le="["+pe+"]?",$e="(?:"+Ee+"(?:"+[Oe,Pe,Te].join("|")+")"+Le+Ie+")*",Ne="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Fe="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ue=Le+Ie+$e,Be="(?:"+[we,Pe,Te].join("|")+")"+Ue,Ge="(?:"+[Oe+be+"?",be,Pe,Te,me].join("|")+")",ze=RegExp(ge,"g"),Ve=RegExp(be,"g"),We=RegExp(ke+"(?="+ke+")|"+Ge+Ue,"g"),qe=RegExp([Ae+"?"+xe+"+"+Re+"(?="+[ye,Ae,"$"].join("|")+")",Me+"+"+De+"(?="+[ye,Ae+je,"$"].join("|")+")",Ae+"?"+je+"+"+Re,Ae+"+"+De,Fe,Ne,_e,Be].join("|"),"g"),He=RegExp("["+Ee+ne+ae+pe+"]"),Ye=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ke=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Xe=-1,Je={};Je[pt]=Je[vt]=Je[gt]=Je[mt]=Je[yt]=Je[bt]=Je[_t]=Je[wt]=Je[xt]=!0,Je[V]=Je[W]=Je[ht]=Je[H]=Je[dt]=Je[Y]=Je[X]=Je[J]=Je[Q]=Je[tt]=Je[nt]=Je[ot]=Je[at]=Je[st]=Je[lt]=!1;var Ze={};Ze[V]=Ze[W]=Ze[ht]=Ze[dt]=Ze[H]=Ze[Y]=Ze[pt]=Ze[vt]=Ze[gt]=Ze[mt]=Ze[yt]=Ze[Q]=Ze[tt]=Ze[nt]=Ze[ot]=Ze[at]=Ze[st]=Ze[ut]=Ze[bt]=Ze[_t]=Ze[wt]=Ze[xt]=!0,Ze[X]=Ze[J]=Ze[lt]=!1;var Qe={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},tn={"&":"&","<":"<",">":">",'"':""","'":"'"},en={"&":"&","<":"<",">":">",""":'"',"'":"'"},nn={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},rn=parseFloat,on=parseInt,an="object"==typeof t&&t&&t.Object===Object&&t,sn="object"==typeof self&&self&&self.Object===Object&&self,un=an||sn||Function("return this")(),cn=e&&!e.nodeType&&e,ln=cn&&"object"==typeof r&&r&&!r.nodeType&&r,fn=ln&&ln.exports===cn,hn=fn&&an.process,dn=function(){try{var t=ln&&ln.require&&ln.require("util").types;return t||hn&&hn.binding&&hn.binding("util")}catch(e){}}(),pn=dn&&dn.isArrayBuffer,vn=dn&&dn.isDate,gn=dn&&dn.isMap,mn=dn&&dn.isRegExp,yn=dn&&dn.isSet,bn=dn&&dn.isTypedArray;function _n(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function wn(t,e,n,r){var i=-1,o=null==t?0:t.length;while(++i-1}function Pn(t,e,n){var r=-1,i=null==t?0:t.length;while(++r-1);return n}function tr(t,e){var n=t.length;while(n--&&Nn(e,t[n],0)>-1);return n}function er(t,e){var n=t.length,r=0;while(n--)t[n]===e&&++r;return r}var nr=zn(Qe),rr=zn(tn);function ir(t){return"\\"+nn[t]}function or(t,e){return null==t?o:t[e]}function ar(t){return He.test(t)}function sr(t){return Ye.test(t)}function ur(t){var e,n=[];while(!(e=t.next()).done)n.push(e.value);return n}function cr(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}function lr(t,e){return function(n){return t(e(n))}}function fr(t,e){var n=-1,r=t.length,i=0,o=[];while(++n-1}function Gr(t,e){var n=this.__data__,r=li(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function zr(t){var e=-1,n=null==t?0:t.length;this.clear();while(++e=e?t:e)),t}function mi(t,e,n,r,i,a){var s,u=e&p,c=e&v,l=e&g;if(n&&(s=i?n(t,r,i,a):n(t)),s!==o)return s;if(!kl(t))return t;var f=ul(t);if(f){if(s=es(t),!u)return ia(t,s)}else{var h=Ja(t),d=h==J||h==Z;if(dl(t))return Yo(t,u);if(h==nt||h==V||d&&!i){if(s=c||d?{}:ns(t),!u)return c?sa(t,di(s,t)):aa(t,hi(s,t))}else{if(!Ze[h])return i?t:{};s=rs(t,h,u)}}a||(a=new Zr);var m=a.get(t);if(m)return m;a.set(t,s),$l(t)?t.forEach((function(r){s.add(mi(r,e,n,r,t,a))})):Ol(t)&&t.forEach((function(r,i){s.set(i,mi(r,e,n,i,t,a))}));var y=l?c?Ua:Fa:c?kf:Sf,b=f?o:y(t);return xn(b||t,(function(r,i){b&&(i=r,r=t[i]),ci(s,i,mi(r,e,n,i,t,a))})),s}function yi(t){var e=Sf(t);return function(n){return bi(n,t,e)}}function bi(t,e,n){var r=n.length;if(null==t)return!r;t=ne(t);while(r--){var i=n[r],a=e[i],s=t[i];if(s===o&&!(i in t)||!a(s))return!1}return!0}function _i(t,e,n){if("function"!=typeof t)throw new oe(c);return Cs((function(){t.apply(o,n)}),e)}function wi(t,e,n,r){var i=-1,o=On,a=!0,u=t.length,c=[],l=e.length;if(!u)return c;n&&(e=Tn(e,Xn(n))),r?(o=Pn,a=!1):e.length>=s&&(o=Zn,a=!1,e=new Kr(e));t:while(++ii?0:i+n),r=r===o||r>i?i:Yl(r),r<0&&(r+=i),r=n>r?0:Kl(r);while(n0&&n(s)?e>1?Ti(s,e-1,n,r,i):An(i,s):r||(i[i.length]=s)}return i}var Ai=fa(),Ei=fa(!0);function ji(t,e){return t&&Ai(t,e,Sf)}function Mi(t,e){return t&&Ei(t,e,Sf)}function Ri(t,e){return Cn(e,(function(e){return wl(t[e])}))}function Di(t,e){e=Vo(e,t);var n=0,r=e.length;while(null!=t&&ne}function Ni(t,e){return null!=t&&fe.call(t,e)}function Fi(t,e){return null!=t&&e in ne(t)}function Ui(t,e,n){return t>=Be(e,n)&&t=120&&h.length>=120)?new Kr(u&&h):o}h=t[0];var d=-1,p=c[0];t:while(++d-1)s!==t&&Ce.call(s,u,1),Ce.call(t,u,1)}return t}function mo(t,e){var n=t?e.length:0,r=n-1;while(n--){var i=e[n];if(n==r||i!==o){var o=i;as(i)?Ce.call(t,i,1):Lo(t,i)}}return t}function yo(t,e){return t+De(qe()*(e-t+1))}function bo(t,e,r,i){var o=-1,a=Ue(Re((e-t)/(r||1)),0),s=n(a);while(a--)s[i?a:++o]=t,t+=r;return s}function _o(t,e){var n="";if(!t||e<1||e>$)return n;do{e%2&&(n+=t),e=De(e/2),e&&(t+=t)}while(e);return n}function wo(t,e){return Os(_s(t,e,jh),t+"")}function xo(t){return oi(Gf(t))}function So(t,e){var n=Gf(t);return As(n,gi(e,0,n.length))}function ko(t,e,n,r){if(!kl(t))return t;e=Vo(e,t);var i=-1,a=e.length,s=a-1,u=t;while(null!=u&&++io?0:o+e),r=r>o?o:r,r<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;var a=n(o);while(++i>>1,a=t[o];null!==a&&!Fl(a)&&(n?a<=e:a=s){var l=e?null:Aa(t);if(l)return hr(l);a=!1,i=Zn,c=new Kr}else c=e?[]:u;t:while(++r=r?t:To(t,e,n)}var Ho=Ee||function(t){return un.clearTimeout(t)};function Yo(t,e){if(e)return t.slice();var n=t.length,r=we?we(n):new t.constructor(n);return t.copy(r),r}function Ko(t){var e=new t.constructor(t.byteLength);return new _e(e).set(new _e(t)),e}function Xo(t,e){var n=e?Ko(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}function Jo(t){var e=new t.constructor(t.source,Ht.exec(t));return e.lastIndex=t.lastIndex,e}function Zo(t){return pr?ne(pr.call(t)):{}}function Qo(t,e){var n=e?Ko(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function ta(t,e){if(t!==e){var n=t!==o,r=null===t,i=t===t,a=Fl(t),s=e!==o,u=null===e,c=e===e,l=Fl(e);if(!u&&!l&&!a&&t>e||a&&s&&c&&!u&&!l||r&&s&&c||!n&&c||!i)return 1;if(!r&&!a&&!l&&t=s)return u;var c=n[r];return u*("desc"==c?-1:1)}}return t.index-e.index}function na(t,e,r,i){var o=-1,a=t.length,s=r.length,u=-1,c=e.length,l=Ue(a-s,0),f=n(c+l),h=!i;while(++u1?n[i-1]:o,s=i>2?n[2]:o;a=t.length>3&&"function"==typeof a?(i--,a):o,s&&ss(n[0],n[1],s)&&(a=i<3?o:a,i=1),e=ne(e);while(++r-1?i[a?e[s]:s]:o}}function ya(t){return Na((function(e){var n=e.length,r=n,i=Or.prototype.thru;t&&e.reverse();while(r--){var a=e[r];if("function"!=typeof a)throw new oe(c);if(i&&!s&&"wrapper"==Ga(a))var s=new Or([],!0)}r=s?r:n;while(++r1&&b.reverse(),h&&lu))return!1;var l=a.get(t),f=a.get(e);if(l&&f)return l==e&&f==t;var h=-1,d=!0,p=n&y?new Kr:o;a.set(t,e),a.set(e,t);while(++h1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(Ut,"{\n/* [wrapped with "+e+"] */\n")}function os(t){return ul(t)||sl(t)||!!(Oe&&t&&t[Oe])}function as(t,e){var n=typeof t;return e=null==e?$:e,!!e&&("number"==n||"symbol"!=n&&Zt.test(t))&&t>-1&&t%1==0&&t0){if(++e>=j)return arguments[0]}else e=0;return t.apply(o,arguments)}}function As(t,e){var n=-1,r=t.length,i=r-1;e=e===o?r:e;while(++n1?t[e-1]:o;return n="function"==typeof n?(t.pop(),n):o,Lu(t,n)}));function Wu(t){var e=wr(t);return e.__chain__=!0,e}function qu(t,e){return e(t),t}function Hu(t,e){return e(t)}var Yu=Na((function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,i=function(e){return vi(e,t)};return!(e>1||this.__actions__.length)&&r instanceof Pr&&as(n)?(r=r.slice(n,+n+(e?1:0)),r.__actions__.push({func:Hu,args:[i],thisArg:o}),new Or(r,this.__chain__).thru((function(t){return e&&!t.length&&t.push(o),t}))):this.thru(i)}));function Ku(){return Wu(this)}function Xu(){return new Or(this.value(),this.__chain__)}function Ju(){this.__values__===o&&(this.__values__=ql(this.value()));var t=this.__index__>=this.__values__.length,e=t?o:this.__values__[this.__index__++];return{done:t,value:e}}function Zu(){return this}function Qu(t){var e,n=this;while(n instanceof Cr){var r=Ds(n);r.__index__=0,r.__values__=o,e?i.__wrapped__=r:e=r;var i=r;n=n.__wrapped__}return i.__wrapped__=t,e}function tc(){var t=this.__wrapped__;if(t instanceof Pr){var e=t;return this.__actions__.length&&(e=new Pr(this)),e=e.reverse(),e.__actions__.push({func:Hu,args:[pu],thisArg:o}),new Or(e,this.__chain__)}return this.thru(pu)}function ec(){return Fo(this.__wrapped__,this.__actions__)}var nc=ua((function(t,e,n){fe.call(t,n)?++t[n]:pi(t,n,1)}));function rc(t,e,n){var r=ul(t)?kn:ki;return n&&ss(t,e,n)&&(e=o),r(t,Va(e,3))}function ic(t,e){var n=ul(t)?Cn:Pi;return n(t,Va(e,3))}var oc=ma(qs),ac=ma(Hs);function sc(t,e){return Ti(gc(t,e),1)}function uc(t,e){return Ti(gc(t,e),L)}function cc(t,e,n){return n=n===o?1:Yl(n),Ti(gc(t,e),n)}function lc(t,e){var n=ul(t)?xn:xi;return n(t,Va(e,3))}function fc(t,e){var n=ul(t)?Sn:Si;return n(t,Va(e,3))}var hc=ua((function(t,e,n){fe.call(t,n)?t[n].push(e):pi(t,n,[e])}));function dc(t,e,n,r){t=ll(t)?t:Gf(t),n=n&&!r?Yl(n):0;var i=t.length;return n<0&&(n=Ue(i+n,0)),Nl(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&Nn(t,e,n)>-1}var pc=wo((function(t,e,r){var i=-1,o="function"==typeof e,a=ll(t)?n(t.length):[];return xi(t,(function(t){a[++i]=o?_n(e,t,r):zi(t,e,r)})),a})),vc=ua((function(t,e,n){pi(t,n,e)}));function gc(t,e){var n=ul(t)?Tn:oo;return n(t,Va(e,3))}function mc(t,e,n,r){return null==t?[]:(ul(e)||(e=null==e?[]:[e]),n=r?o:n,ul(n)||(n=null==n?[]:[n]),fo(t,e,n))}var yc=ua((function(t,e,n){t[n?0:1].push(e)}),(function(){return[[],[]]}));function bc(t,e,n){var r=ul(t)?En:Vn,i=arguments.length<3;return r(t,Va(e,4),n,i,xi)}function _c(t,e,n){var r=ul(t)?jn:Vn,i=arguments.length<3;return r(t,Va(e,4),n,i,Si)}function wc(t,e){var n=ul(t)?Cn:Pi;return n(t,Bc(Va(e,3)))}function xc(t){var e=ul(t)?oi:xo;return e(t)}function Sc(t,e,n){e=(n?ss(t,e,n):e===o)?1:Yl(e);var r=ul(t)?ai:So;return r(t,e)}function kc(t){var e=ul(t)?si:Po;return e(t)}function Cc(t){if(null==t)return 0;if(ll(t))return Nl(t)?gr(t):t.length;var e=Ja(t);return e==Q||e==at?t.size:no(t).length}function Oc(t,e,n){var r=ul(t)?Mn:Ao;return n&&ss(t,e,n)&&(e=o),r(t,Va(e,3))}var Pc=wo((function(t,e){if(null==t)return[];var n=e.length;return n>1&&ss(t,e[0],e[1])?e=[]:n>2&&ss(e[0],e[1],e[2])&&(e=[e[0]]),fo(t,Ti(e,1),[])})),Tc=je||function(){return un.Date.now()};function Ac(t,e){if("function"!=typeof e)throw new oe(c);return t=Yl(t),function(){if(--t<1)return e.apply(this,arguments)}}function Ec(t,e,n){return e=n?o:e,e=t&&null==e?t.length:e,ja(t,O,o,o,o,o,e)}function jc(t,e){var n;if("function"!=typeof e)throw new oe(c);return t=Yl(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=o),n}}var Mc=wo((function(t,e,n){var r=b;if(n.length){var i=fr(n,za(Mc));r|=k}return ja(t,r,e,n,i)})),Rc=wo((function(t,e,n){var r=b|_;if(n.length){var i=fr(n,za(Rc));r|=k}return ja(e,r,t,n,i)}));function Dc(t,e,n){e=n?o:e;var r=ja(t,x,o,o,o,o,o,e);return r.placeholder=Dc.placeholder,r}function Ic(t,e,n){e=n?o:e;var r=ja(t,S,o,o,o,o,o,e);return r.placeholder=Ic.placeholder,r}function Lc(t,e,n){var r,i,a,s,u,l,f=0,h=!1,d=!1,p=!0;if("function"!=typeof t)throw new oe(c);function v(e){var n=r,a=i;return r=i=o,f=e,s=t.apply(a,n),s}function g(t){return f=t,u=Cs(b,e),h?v(t):s}function m(t){var n=t-l,r=t-f,i=e-n;return d?Be(i,a-r):i}function y(t){var n=t-l,r=t-f;return l===o||n>=e||n<0||d&&r>=a}function b(){var t=Tc();if(y(t))return _(t);u=Cs(b,m(t))}function _(t){return u=o,p&&r?v(t):(r=i=o,s)}function w(){u!==o&&Ho(u),f=0,r=l=i=u=o}function x(){return u===o?s:_(Tc())}function S(){var t=Tc(),n=y(t);if(r=arguments,i=this,l=t,n){if(u===o)return g(l);if(d)return Ho(u),u=Cs(b,e),v(l)}return u===o&&(u=Cs(b,e)),s}return e=Xl(e)||0,kl(n)&&(h=!!n.leading,d="maxWait"in n,a=d?Ue(Xl(n.maxWait)||0,e):a,p="trailing"in n?!!n.trailing:p),S.cancel=w,S.flush=x,S}var $c=wo((function(t,e){return _i(t,1,e)})),Nc=wo((function(t,e,n){return _i(t,Xl(e)||0,n)}));function Fc(t){return ja(t,T)}function Uc(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new oe(c);var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=t.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(Uc.Cache||zr),n}function Bc(t){if("function"!=typeof t)throw new oe(c);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}function Gc(t){return jc(2,t)}Uc.Cache=zr;var zc=Wo((function(t,e){e=1==e.length&&ul(e[0])?Tn(e[0],Xn(Va())):Tn(Ti(e,1),Xn(Va()));var n=e.length;return wo((function(r){var i=-1,o=Be(r.length,n);while(++i=e})),sl=Vi(function(){return arguments}())?Vi:function(t){return Cl(t)&&fe.call(t,"callee")&&!ke.call(t,"callee")},ul=n.isArray,cl=pn?Xn(pn):Wi;function ll(t){return null!=t&&Sl(t.length)&&!wl(t)}function fl(t){return Cl(t)&&ll(t)}function hl(t){return!0===t||!1===t||Cl(t)&&Li(t)==H}var dl=Le||Kh,pl=vn?Xn(vn):qi;function vl(t){return Cl(t)&&1===t.nodeType&&!Dl(t)}function gl(t){if(null==t)return!0;if(ll(t)&&(ul(t)||"string"==typeof t||"function"==typeof t.splice||dl(t)||Ul(t)||sl(t)))return!t.length;var e=Ja(t);if(e==Q||e==at)return!t.size;if(ds(t))return!no(t).length;for(var n in t)if(fe.call(t,n))return!1;return!0}function ml(t,e){return Hi(t,e)}function yl(t,e,n){n="function"==typeof n?n:o;var r=n?n(t,e):o;return r===o?Hi(t,e,o,n):!!r}function bl(t){if(!Cl(t))return!1;var e=Li(t);return e==X||e==K||"string"==typeof t.message&&"string"==typeof t.name&&!Dl(t)}function _l(t){return"number"==typeof t&&$e(t)}function wl(t){if(!kl(t))return!1;var e=Li(t);return e==J||e==Z||e==q||e==it}function xl(t){return"number"==typeof t&&t==Yl(t)}function Sl(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=$}function kl(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Cl(t){return null!=t&&"object"==typeof t}var Ol=gn?Xn(gn):Ki;function Pl(t,e){return t===e||Xi(t,e,qa(e))}function Tl(t,e,n){return n="function"==typeof n?n:o,Xi(t,e,qa(e),n)}function Al(t){return Rl(t)&&t!=+t}function El(t){if(hs(t))throw new i(u);return Ji(t)}function jl(t){return null===t}function Ml(t){return null==t}function Rl(t){return"number"==typeof t||Cl(t)&&Li(t)==tt}function Dl(t){if(!Cl(t)||Li(t)!=nt)return!1;var e=xe(t);if(null===e)return!0;var n=fe.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&le.call(n)==ve}var Il=mn?Xn(mn):Zi;function Ll(t){return xl(t)&&t>=-$&&t<=$}var $l=yn?Xn(yn):Qi;function Nl(t){return"string"==typeof t||!ul(t)&&Cl(t)&&Li(t)==st}function Fl(t){return"symbol"==typeof t||Cl(t)&&Li(t)==ut}var Ul=bn?Xn(bn):to;function Bl(t){return t===o}function Gl(t){return Cl(t)&&Ja(t)==lt}function zl(t){return Cl(t)&&Li(t)==ft}var Vl=Oa(io),Wl=Oa((function(t,e){return t<=e}));function ql(t){if(!t)return[];if(ll(t))return Nl(t)?mr(t):ia(t);if(Pe&&t[Pe])return ur(t[Pe]());var e=Ja(t),n=e==Q?cr:e==at?hr:Gf;return n(t)}function Hl(t){if(!t)return 0===t?t:0;if(t=Xl(t),t===L||t===-L){var e=t<0?-1:1;return e*N}return t===t?t:0}function Yl(t){var e=Hl(t),n=e%1;return e===e?n?e-n:e:0}function Kl(t){return t?gi(Yl(t),0,U):0}function Xl(t){if("number"==typeof t)return t;if(Fl(t))return F;if(kl(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=kl(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=Kn(t);var n=Kt.test(t);return n||Jt.test(t)?on(t.slice(2),n?2:8):Yt.test(t)?F:+t}function Jl(t){return oa(t,kf(t))}function Zl(t){return t?gi(Yl(t),-$,$):0===t?t:0}function Ql(t){return null==t?"":Do(t)}var tf=ca((function(t,e){if(ds(e)||ll(e))oa(e,Sf(e),t);else for(var n in e)fe.call(e,n)&&ci(t,n,e[n])})),ef=ca((function(t,e){oa(e,kf(e),t)})),nf=ca((function(t,e,n,r){oa(e,kf(e),t,r)})),rf=ca((function(t,e,n,r){oa(e,Sf(e),t,r)})),of=Na(vi);function af(t,e){var n=Sr(t);return null==e?n:hi(n,e)}var sf=wo((function(t,e){t=ne(t);var n=-1,r=e.length,i=r>2?e[2]:o;i&&ss(e[0],e[1],i)&&(r=1);while(++n1),e})),oa(t,Ua(t),n),r&&(n=mi(n,p|v|g,Da));var i=e.length;while(i--)Lo(n,e[i]);return n}));function Ef(t,e){return Mf(t,Bc(Va(e)))}var jf=Na((function(t,e){return null==t?{}:ho(t,e)}));function Mf(t,e){if(null==t)return{};var n=Tn(Ua(t),(function(t){return[t]}));return e=Va(e),po(t,n,(function(t,n){return e(t,n[0])}))}function Rf(t,e,n){e=Vo(e,t);var r=-1,i=e.length;i||(i=1,t=o);while(++re){var r=t;t=e,e=r}if(n||t%1||e%1){var i=qe();return Be(t+i*(e-t+rn("1e-"+((i+"").length-1))),e)}return yo(t,e)}var Hf=pa((function(t,e,n){return e=e.toLowerCase(),t+(n?Yf(e):e)}));function Yf(t){return wh(Ql(t).toLowerCase())}function Kf(t){return t=Ql(t),t&&t.replace(Qt,nr).replace(Ve,"")}function Xf(t,e,n){t=Ql(t),e=Do(e);var r=t.length;n=n===o?r:gi(Yl(n),0,r);var i=n;return n-=e.length,n>=0&&t.slice(n,i)==e}function Jf(t){return t=Ql(t),t&&At.test(t)?t.replace(Pt,rr):t}function Zf(t){return t=Ql(t),t&&$t.test(t)?t.replace(Lt,"\\$&"):t}var Qf=pa((function(t,e,n){return t+(n?"-":"")+e.toLowerCase()})),th=pa((function(t,e,n){return t+(n?" ":"")+e.toLowerCase()})),eh=da("toLowerCase");function nh(t,e,n){t=Ql(t),e=Yl(e);var r=e?gr(t):0;if(!e||r>=e)return t;var i=(e-r)/2;return Sa(De(i),n)+t+Sa(Re(i),n)}function rh(t,e,n){t=Ql(t),e=Yl(e);var r=e?gr(t):0;return e&&r>>0,n?(t=Ql(t),t&&("string"==typeof e||null!=e&&!Il(e))&&(e=Do(e),!e&&ar(t))?qo(mr(t),0,n):t.split(e,n)):[]}var lh=pa((function(t,e,n){return t+(n?" ":"")+wh(e)}));function fh(t,e,n){return t=Ql(t),n=null==n?0:gi(Yl(n),0,t.length),e=Do(e),t.slice(n,n+e.length)==e}function hh(t,e,n){var r=wr.templateSettings;n&&ss(t,e,n)&&(e=o),t=Ql(t),e=nf({},e,r,Ma);var a,s,u=nf({},e.imports,r.imports,Ma),c=Sf(u),f=Jn(u,c),h=0,d=e.interpolate||te,p="__p += '",v=re((e.escape||te).source+"|"+d.source+"|"+(d===Mt?qt:te).source+"|"+(e.evaluate||te).source+"|$","g"),g="//# sourceURL="+(fe.call(e,"sourceURL")?(e.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Xe+"]")+"\n";t.replace(v,(function(e,n,r,i,o,u){return r||(r=i),p+=t.slice(h,u).replace(ee,ir),n&&(a=!0,p+="' +\n__e("+n+") +\n'"),o&&(s=!0,p+="';\n"+o+";\n__p += '"),r&&(p+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),h=u+e.length,e})),p+="';\n";var m=fe.call(e,"variable")&&e.variable;if(m){if(Vt.test(m))throw new i(l)}else p="with (obj) {\n"+p+"\n}\n";p=(s?p.replace(St,""):p).replace(kt,"$1").replace(Ct,"$1;"),p="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(a?", __e = _.escape":"")+(s?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var y=Sh((function(){return Ft(c,g+"return "+p).apply(o,f)}));if(y.source=p,bl(y))throw y;return y}function dh(t){return Ql(t).toLowerCase()}function ph(t){return Ql(t).toUpperCase()}function vh(t,e,n){if(t=Ql(t),t&&(n||e===o))return Kn(t);if(!t||!(e=Do(e)))return t;var r=mr(t),i=mr(e),a=Qn(r,i),s=tr(r,i)+1;return qo(r,a,s).join("")}function gh(t,e,n){if(t=Ql(t),t&&(n||e===o))return t.slice(0,yr(t)+1);if(!t||!(e=Do(e)))return t;var r=mr(t),i=tr(r,mr(e))+1;return qo(r,0,i).join("")}function mh(t,e,n){if(t=Ql(t),t&&(n||e===o))return t.replace(Nt,"");if(!t||!(e=Do(e)))return t;var r=mr(t),i=Qn(r,mr(e));return qo(r,i).join("")}function yh(t,e){var n=A,r=E;if(kl(e)){var i="separator"in e?e.separator:i;n="length"in e?Yl(e.length):n,r="omission"in e?Do(e.omission):r}t=Ql(t);var a=t.length;if(ar(t)){var s=mr(t);a=s.length}if(n>=a)return t;var u=n-gr(r);if(u<1)return r;var c=s?qo(s,0,u).join(""):t.slice(0,u);if(i===o)return c+r;if(s&&(u+=c.length-u),Il(i)){if(t.slice(u).search(i)){var l,f=c;i.global||(i=re(i.source,Ql(Ht.exec(i))+"g")),i.lastIndex=0;while(l=i.exec(f))var h=l.index;c=c.slice(0,h===o?u:h)}}else if(t.indexOf(Do(i),u)!=u){var d=c.lastIndexOf(i);d>-1&&(c=c.slice(0,d))}return c+r}function bh(t){return t=Ql(t),t&&Tt.test(t)?t.replace(Ot,br):t}var _h=pa((function(t,e,n){return t+(n?" ":"")+e.toUpperCase()})),wh=da("toUpperCase");function xh(t,e,n){return t=Ql(t),e=n?o:e,e===o?sr(t)?xr(t):In(t):t.match(e)||[]}var Sh=wo((function(t,e){try{return _n(t,o,e)}catch(n){return bl(n)?n:new i(n)}})),kh=Na((function(t,e){return xn(e,(function(e){e=js(e),pi(t,e,Mc(t[e],t))})),t}));function Ch(t){var e=null==t?0:t.length,n=Va();return t=e?Tn(t,(function(t){if("function"!=typeof t[1])throw new oe(c);return[n(t[0]),t[1]]})):[],wo((function(n){var r=-1;while(++r$)return[];var n=U,r=Be(t,U);e=Va(e),t-=U;var i=Hn(r,e);while(++n0||e<0)?new Pr(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==o&&(e=Yl(e),n=e<0?n.dropRight(-e):n.take(e-t)),n)},Pr.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Pr.prototype.toArray=function(){return this.take(U)},ji(Pr.prototype,(function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),i=wr[r?"take"+("last"==e?"Right":""):e],a=r||/^find/.test(e);i&&(wr.prototype[e]=function(){var e=this.__wrapped__,s=r?[1]:arguments,u=e instanceof Pr,c=s[0],l=u||ul(e),f=function(t){var e=i.apply(wr,An([t],s));return r&&h?e[0]:e};l&&n&&"function"==typeof c&&1!=c.length&&(u=l=!1);var h=this.__chain__,d=!!this.__actions__.length,p=a&&!h,v=u&&!d;if(!a&&l){e=v?e:new Pr(this);var g=t.apply(e,s);return g.__actions__.push({func:Hu,args:[f],thisArg:o}),new Or(g,h)}return p&&v?t.apply(this,s):(g=this.thru(f),p?r?g.value()[0]:g.value():g)})})),xn(["pop","push","shift","sort","splice","unshift"],(function(t){var e=ae[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);wr.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var i=this.value();return e.apply(ul(i)?i:[],t)}return this[n]((function(n){return e.apply(ul(n)?n:[],t)}))}})),ji(Pr.prototype,(function(t,e){var n=wr[e];if(n){var r=n.name+"";fe.call(cn,r)||(cn[r]=[]),cn[r].push({name:e,func:n})}})),cn[ba(o,_).name]=[{name:"wrapper",func:o}],Pr.prototype.clone=Tr,Pr.prototype.reverse=Ar,Pr.prototype.value=Er,wr.prototype.at=Yu,wr.prototype.chain=Ku,wr.prototype.commit=Xu,wr.prototype.next=Ju,wr.prototype.plant=Qu,wr.prototype.reverse=tc,wr.prototype.toJSON=wr.prototype.valueOf=wr.prototype.value=ec,wr.prototype.first=wr.prototype.head,Pe&&(wr.prototype[Pe]=Zu),wr},kr=Sr();un._=kr,i=function(){return kr}.call(e,n,e,r),i===o||(r.exports=i)}).call(this)}).call(this,n("c8ba"),n("62e4")(t))},"2fb2":function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0}),e.FastLayer=void 0;var i=n("9cb8"),o=n("0ff5"),a=n("d777"),s=function(t){function e(e){var n=t.call(this,e)||this;return n.listening(!1),i.Util.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.'),n}return r(e,t),e}(o.Layer);e.FastLayer=s,s.prototype.nodeType="FastLayer",a._registerNode(s),i.Collection.mapMethods(s)},"2fcc":function(t,e){function n(t){var e=this.__data__,n=e["delete"](t);return this.size=e.size,n}t.exports=n},"2fd7":function(t,e,n){},"30c9":function(t,e,n){var r=n("9520"),i=n("b218");function o(t){return null!=t&&i(t.length)&&!r(t)}t.exports=o},"32b3":function(t,e,n){var r=n("872a"),i=n("9638"),o=Object.prototype,a=o.hasOwnProperty;function s(t,e,n){var o=t[e];a.call(t,e)&&i(o,n)&&(void 0!==n||e in t)||r(t,e,n)}t.exports=s},"32f4":function(t,e,n){var r=n("2d7c"),i=n("d327"),o=Object.prototype,a=o.propertyIsEnumerable,s=Object.getOwnPropertySymbols,u=s?function(t){return null==t?[]:(t=Object(t),r(s(t),(function(e){return a.call(t,e)})))}:i;t.exports=u},3360:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n("78ef"),i=function(){for(var t=arguments.length,e=new Array(t),n=0;n0&&e.reduce((function(e,n){return e&&n.apply(t,r)}),!0)}))};e.default=i},"34ac":function(t,e,n){var r=n("9520"),i=n("1368"),o=n("1a8c"),a=n("dc57"),s=/[\\^$.*+?()[\]{}|]/g,u=/^\[object .+?Constructor\]$/,c=Function.prototype,l=Object.prototype,f=c.toString,h=l.hasOwnProperty,d=RegExp("^"+f.call(h).replace(s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function p(t){if(!o(t)||i(t))return!1;var e=r(t)?d:u;return e.test(a(t))}t.exports=p},"362d":function(t,e,n){var r=n("fd15").Konva;r._injectGlobal(r),e["default"]=r,t.exports=e["default"]},3665:function(t,e,n){"use strict";n.d(e,"a",(function(){return tl}));var r={};n.r(r),n.d(r,"Experiment",(function(){return lt})),n.d(r,"Screen",(function(){return St})),n.d(r,"Slide",(function(){return At})),n.d(r,"CompletionInput",(function(){return $t})),n.d(r,"DropdownInput",(function(){return Wt})),n.d(r,"ForcedChoiceInput",(function(){return Qt})),n.d(r,"ImageSelectionInput",(function(){return se})),n.d(r,"KeypressInput",(function(){return ve})),n.d(r,"RatingInput",(function(){return Se})),n.d(r,"SliderInput",(function(){return Re})),n.d(r,"TextareaInput",(function(){return Be})),n.d(r,"MultipleChoiceInput",(function(){return Je})),n.d(r,"MultipleChoiceMatrixInput",(function(){return an})),n.d(r,"SliderRangesInput",(function(){return mn})),n.d(r,"RankOrderInput",(function(){return Pn})),n.d(r,"MazeInput",(function(){return vr})),n.d(r,"SerialInput",(function(){return $n})),n.d(r,"SelfPacedReadingInput",(function(){return Sr})),n.d(r,"Rsvp",(function(){return jr})),n.d(r,"FixationCross",(function(){return Fr})),n.d(r,"Synth",(function(){return Ou})),n.d(r,"Chat",(function(){return Xr})),n.d(r,"WaitForParticipants",(function(){return ii})),n.d(r,"LifecycleScreen",(function(){return Ti})),n.d(r,"ConnectInteractiveScreen",(function(){return Li})),n.d(r,"AwaitIteratedResultScreen",(function(){return Vi})),n.d(r,"DebugResultsScreen",(function(){return to})),n.d(r,"SubmitResultsScreen",(function(){return uo})),n.d(r,"PostTestScreen",(function(){return mo})),n.d(r,"InstructionScreen",(function(){return Co})),n.d(r,"EyetrackingCalibrationScreen",(function(){return Io})),n.d(r,"EyetrackingValidationScreen",(function(){return Jo})),n.d(r,"ForcedChoiceScreen",(function(){return oa})),n.d(r,"ImageSelectionScreen",(function(){return da})),n.d(r,"TextareaScreen",(function(){return wa})),n.d(r,"SliderScreen",(function(){return Aa})),n.d(r,"SliderRangesScreen",(function(){return $a})),n.d(r,"RatingScreen",(function(){return Wa})),n.d(r,"CompletionScreen",(function(){return Qa})),n.d(r,"KeypressScreen",(function(){return ss})),n.d(r,"ForcedChoiceMousetrackingScreen",(function(){return vs})),n.d(r,"MultipleChoiceScreen",(function(){return Ss})),n.d(r,"MultipleChoiceMatrixScreen",(function(){return js})),n.d(r,"MazeScreen",(function(){return Fs})),n.d(r,"SelfPacedReadingScreen",(function(){return Hs})),n.d(r,"Wait",(function(){return cr})),n.d(r,"TimerStop",(function(){return Wn})),n.d(r,"TimerStart",(function(){return Qn})),n.d(r,"Record",(function(){return xi})),n.d(r,"ResponseTimeStart",(function(){return pi})),n.d(r,"MousetrackingStart",(function(){return eu})),n.d(r,"EyetrackingStart",(function(){return Wo})),n.d(r,"FullscreenStart",(function(){return cu})),n.d(r,"HideCursor",(function(){return mu})),n.d(r,"PreventCopyPaste",(function(){return Cu}));var i={};n.r(i),n.d(i,"en",(function(){return Zc})),n.d(i,"de",(function(){return Qc}));var o=n("faa1"),a=n.n(o),s=n("2b0e"),u=t=>{if("function"===typeof t)return t;{let e=function(){return t};return e}},c="undefined"!==typeof self?self:null,l="undefined"!==typeof window?window:null,f=c||l||f,h="2.0.0",d={connecting:0,open:1,closing:2,closed:3},p=1e4,v=1e3,g={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},m={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},y={longpoll:"longpoll",websocket:"websocket"},b={complete:4},_=class{constructor(t,e,n,r){this.channel=t,this.event=e,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:t,response:e,_ref:n}){this.recHooks.filter(e=>e.status===t).forEach(t=>t.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},w=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},x=class{constructor(t,e,n){this.state=g.closed,this.topic=t,this.params=u(e||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new _(this,m.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new w(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=g.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(t=>t.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=g.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=g.closed,this.socket.remove(this)}),this.onError(t=>{this.socket.hasLogger()&&this.socket.log("channel","error "+this.topic,t),this.isJoining()&&this.joinPush.reset(),this.state=g.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout);let t=new _(this,m.leave,u({}),this.timeout);t.send(),this.state=g.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(m.reply,(t,e)=>{this.trigger(this.replyEventName(e),t)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(t){this.on(m.close,t)}onError(t){return this.on(m.error,e=>t(e))}on(t,e){let n=this.bindingRef++;return this.bindings.push({event:t,ref:n,callback:e}),n}off(t,e){this.bindings=this.bindings.filter(n=>!(n.event===t&&("undefined"===typeof e||e===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,n=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new _(this,t,(function(){return e}),n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=g.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel","leave "+this.topic),this.trigger(m.close,"leave")},n=new _(this,m.leave,u({}),t);return n.receive("ok",()=>e()).receive("timeout",()=>e()),n.send(),this.canPush()||n.trigger("ok",{}),n}onMessage(t,e,n){return e}isMember(t,e,n,r){return this.topic===t&&(!r||r===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:n,joinRef:r}),!1))}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=g.joining,this.joinPush.resend(t))}trigger(t,e,n,r){let i=this.onMessage(t,e,n,r);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let o=this.bindings.filter(e=>e.event===t);for(let a=0;a{let e=this.parseJSON(t.responseText);a&&a(e)},o&&(t.ontimeout=o),t.onprogress=()=>{},t.send(r),t}static xhrRequest(t,e,n,r,i,o,a,s){return t.open(e,n,!0),t.timeout=o,t.setRequestHeader("Content-Type",r),t.onerror=()=>s&&s(null),t.onreadystatechange=()=>{if(t.readyState===b.complete&&s){let e=this.parseJSON(t.responseText);s(e)}},a&&(t.ontimeout=a),t.send(i),t}static parseJSON(t){if(!t||""===t)return null;try{return JSON.parse(t)}catch(e){return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let n=[];for(var r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let i=e?`${e}[${r}]`:r,o=t[r];"object"===typeof o?n.push(this.serialize(o,i)):n.push(encodeURIComponent(i)+"="+encodeURIComponent(o))}return n.join("&")}static appendParams(t,e){if(0===Object.keys(e).length)return t;let n=t.match(/\?/)?"&":"?";return`${t}${n}${this.serialize(e)}`}},k=class{constructor(t){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=d.connecting,this.poll()}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+y.websocket),"$1/"+y.longpoll)}endpointURL(){return S.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,n){this.close(t,e,n),this.readyState=d.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===d.open||this.readyState===d.connecting}poll(){this.ajax("GET",null,()=>this.ontimeout(),t=>{if(t){var{status:e,token:n,messages:r}=t;this.token=n}else e=0;switch(e){case 200:r.forEach(t=>{setTimeout(()=>this.onmessage({data:t}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=d.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error("unhandled poll status "+e)}})}send(t){this.ajax("POST",t,()=>this.onerror("timeout"),t=>{t&&200===t.status||(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1))})}close(t,e,n){for(let i of this.reqs)i.abort();this.readyState=d.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:n});"undefined"!==typeof CloseEvent?this.onclose(new CloseEvent("close",r)):this.onclose(r)}ajax(t,e,n,r){let i,o=()=>{this.reqs.delete(i),n()};i=S.request(t,this.endpointURL(),"application/json",e,this.timeout,o,t=>{this.reqs.delete(i),this.isActive()&&r(t)}),this.reqs.add(i)}},C={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let n=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(n))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[n,r,i,o,a]=JSON.parse(t);return e({join_ref:n,ref:r,topic:i,event:o,payload:a})}},binaryEncode(t){let{join_ref:e,ref:n,event:r,topic:i,payload:o}=t,a=this.META_LENGTH+e.length+n.length+i.length+r.length,s=new ArrayBuffer(this.HEADER_LENGTH+a),u=new DataView(s),c=0;u.setUint8(c++,this.KINDS.push),u.setUint8(c++,e.length),u.setUint8(c++,n.length),u.setUint8(c++,i.length),u.setUint8(c++,r.length),Array.from(e,t=>u.setUint8(c++,t.charCodeAt(0))),Array.from(n,t=>u.setUint8(c++,t.charCodeAt(0))),Array.from(i,t=>u.setUint8(c++,t.charCodeAt(0))),Array.from(r,t=>u.setUint8(c++,t.charCodeAt(0)));var l=new Uint8Array(s.byteLength+o.byteLength);return l.set(new Uint8Array(s),0),l.set(new Uint8Array(o),s.byteLength),l.buffer},binaryDecode(t){let e=new DataView(t),n=e.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(t,e,r);case this.KINDS.reply:return this.decodeReply(t,e,r);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,r)}},decodePush(t,e,n){let r=e.getUint8(1),i=e.getUint8(2),o=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,s=n.decode(t.slice(a,a+r));a+=r;let u=n.decode(t.slice(a,a+i));a+=i;let c=n.decode(t.slice(a,a+o));a+=o;let l=t.slice(a,t.byteLength);return{join_ref:s,ref:null,topic:u,event:c,payload:l}},decodeReply(t,e,n){let r=e.getUint8(1),i=e.getUint8(2),o=e.getUint8(3),a=e.getUint8(4),s=this.HEADER_LENGTH+this.META_LENGTH,u=n.decode(t.slice(s,s+r));s+=r;let c=n.decode(t.slice(s,s+i));s+=i;let l=n.decode(t.slice(s,s+o));s+=o;let f=n.decode(t.slice(s,s+a));s+=a;let h=t.slice(s,t.byteLength),d={status:f,response:h};return{join_ref:u,ref:c,topic:l,event:m.reply,payload:d}},decodeBroadcast(t,e,n){let r=e.getUint8(1),i=e.getUint8(2),o=this.HEADER_LENGTH+2,a=n.decode(t.slice(o,o+r));o+=r;let s=n.decode(t.slice(o,o+i));o+=i;let u=t.slice(o,t.byteLength);return{join_ref:null,ref:null,topic:a,event:s,payload:u}}},O=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||p,this.transport=e.transport||f.WebSocket||k,this.establishedConnections=0,this.defaultEncoder=C.encode.bind(C),this.defaultDecoder=C.decode.bind(C),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==k?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;l&&l.addEventListener&&(l.addEventListener("pagehide",t=>{this.conn&&(this.disconnect(),n=this.connectClock)}),l.addEventListener("pageshow",t=>{n===this.connectClock&&(n=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=t=>e.rejoinAfterMs?e.rejoinAfterMs(t):[1e3,2e3,5e3][t-1]||1e4,this.reconnectAfterMs=t=>e.reconnectAfterMs?e.reconnectAfterMs(t):[10,50,100,150,200,250,500,1e3,2e3][t-1]||5e3,this.logger=e.logger||null,this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=u(e.params||{}),this.endPoint=`${t}/${y.websocket}`,this.vsn=e.vsn||h,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new w(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return k}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.sendBuffer=[],this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=S.appendParams(S.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==t.charAt(0)?t:"/"===t.charAt(1)?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,n){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(t,e,n)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=u(t)),this.conn||(this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t))}log(t,e,n){this.logger(t,e,n)}hasLogger(){return null!==this.logger}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),n=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let r=this.onMessage(i=>{i.ref===e&&(this.off([r]),t(Date.now()-n))});return!0}onConnOpen(){this.hasLogger()&&this.log("transport","connected to "+this.endPointURL()),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,t])=>t())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.abnormalClose("heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,clearTimeout(this.heartbeatTimer),setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,n){if(!this.conn)return t&&t();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,n||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e=1){5!==e&&this.conn&&this.conn.bufferedAmount?setTimeout(()=>{this.waitForBufferDone(t,e+1)},150*e):t()}waitForSocketClosed(t,e=1){5!==e&&this.conn&&this.conn.readyState!==d.closed?setTimeout(()=>{this.waitForSocketClosed(t,e+1)},150*e):t()}onConnClose(t){let e=t&&t.code;this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),clearTimeout(this.heartbeatTimer),this.closeWasClean||1e3===e||this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,e])=>e(t))}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,n=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,r])=>{r(t,e,n)}),(e===this.transport||n>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(m.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case d.connecting:return"connecting";case d.open:return"open";case d.closing:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e.joinRef()!==t.joinRef())}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([e])=>-1===t.indexOf(e))}channel(t,e={}){let n=new x(t,e,this);return this.channels.push(n),n}push(t){if(this.hasLogger()){let{topic:e,event:n,payload:r,ref:i,join_ref:o}=t;this.log("push",`${e} ${n} (${o}, ${i})`,r)}this.isConnected()?this.encode(t,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(t,t=>this.conn.send(t)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}abnormalClose(t){this.closeWasClean=!1,this.isConnected()&&this.conn.close(v,t)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,t=>{let{topic:e,event:n,payload:r,ref:i,join_ref:o}=t;i&&i===this.pendingHeartbeatRef&&(clearTimeout(this.heartbeatTimer),this.pendingHeartbeatRef=null,setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${r.status||""} ${e} ${n} ${i&&"("+i+")"||""}`,r);for(let a=0;ae.topic===t&&(e.isJoined()||e.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}},P=n("8bc1");const T=3e3,A=1e4,E="screen_presence",j={CONNECTING:"CONNECTING",CONNECTED:"CONNECTED",WAITING:"WAITING",READY:"READY",ERROR:"ERROR"};class M extends a.a{constructor(t,e,n){super(),this.socketURL=e,this.errorHandler=t=>{this.state=j.ERROR,n(t)},this.participantId=R(40),this.experimentId=t,this.state=j.CONNECTING,this.iteratedState=j.WAITING,this.participants=[],this.active=[],this.variant=null,this.chain=null,this.generation=null,this.player=null,this.groupLabel=null,this.lastIterationResults=null,s["default"].observable(this),this.currentScreen=null,this.participantsPerScreen={},this.timeoutsPerParticipant={}}getParticipantName(t){return I(t,P)}getParticipantColor(t){return I(t,L)}initialize(){null===this.variant&&(this.phoenix=new O(this.socketURL,{params:{participant_id:this.participantId,experiment_id:this.experimentId}}),this.phoenix.onError(this.errorHandler),this.phoenix.connect(),this.participantChannel=this.phoenix.channel("participant:"+this.participantId,{}),this.participantChannel.on("experiment_available",t=>{this.variant=t.variant,this.chain=t.chain,this.generation=t.generation,this.player=t.player,this.groupLabel=t.group_label,this.state=j.CONNECTED,this.join()}),this.participantChannel.join().receive("ok",()=>{}).receive("error",this.errorHandler).receive("timeout",this.errorHandler),setInterval(()=>{this.participantChannel.push("report_heartbeat")},3e4))}join(){this.chain&&this.generation&&(this.roomChannel=this.phoenix.channel(`interactive_room:${this.experimentId}:${this.chain}:${this.variant}:${this.generation}`,{participant_id:this.participantId}),this.roomChannel.join().receive("ok",()=>{this.state=j.WAITING}).receive("error",this.errorHandler).receive("timeout",this.errorHandler),this.roomChannel.on("start_game",({group_label:t})=>{this.groupLabel=t,this.state=j.READY}),this.roomChannel.on("new_msg",t=>{this.emit(t.event,t.payload)}),this.roomChannel.on("presence_diff",t=>{Object.keys(t.joins).forEach(t=>this.participants.push(t)),Object.keys(t.leaves).forEach(t=>{this.participants.splice(this.participants.indexOf(t),1),this.leaveHandler&&this.leaveHandler()})}),setInterval(()=>{this.broadcast(E,{[this.participantId]:this.currentScreen})},T),this.on(E,t=>{Object.assign(this.participantsPerScreen,t),this.updateActiveParticipants();const e=Object.keys(t)[0];e&&(clearTimeout(this.timeoutsPerParticipant[e]),this.timeoutsPerParticipant[e]=setTimeout(()=>{delete this.participantsPerScreen[e],this.updateActiveParticipants()},A))}),1===this.generation?this.iteratedState=j.READY:(this.lobbyChannel=this.phoenix.channel(`iterated_lobby:${this.experimentId}:${this.chain}:${this.variant}:${this.generation-1}:${this.player}`,{participant_id:this.participantId}),this.lobbyChannel.on("finished",t=>{this.lastIterationResults=t.results,this.lobbyChannel.leave(),this.iteratedState=j.READY}),this.lobbyChannel.join().receive("error",this.errorHandler).receive("timeout",this.errorHandler)))}setCurrentScreen(t){this.currentScreen=t,this.updateActiveParticipants()}updateActiveParticipants(){this.active=Object.entries({...this.participantsPerScreen,[this.participantId]:this.currentScreen}).filter(([,t])=>t===this.currentScreen).map(([t])=>t)}setUpSubscriptions(t,e){for(const n of Object.keys(t))t[n].listener=r=>t[n].call(e,r),this.on(n,t[n].listener)}tearDownSubscriptions(t){for(const e of Object.keys(t))this.off(e,t[e].listener)}broadcast(t,e){this.roomChannel.push("new_msg",{event:t,payload:e})}}function R(t){const e=function(t){return("0"+t.toString(16)).substr(-2)};let n=new Uint8Array((t||40)/2);return window.crypto.getRandomValues(n),Array.from(n,e).join("")}function D(t){var e,n,r=0;if(0===t.length)return r;for(e=0;et){const r=(this.time[n+1]-this.time[n])/t-1,i=(this.x[n+1]-this.x[n])/(r+1),o=(this.y[n+1]-this.y[n])/(r+1),a=e.mt_time.length-1;for(let n=0;nt&&this.onGaze(t)),q.begin()}onGaze(t){this.deaf||(this.time.push(Date.now()-this.startTime),this.x.push(t.x-this.originX),this.y.push(t.y-this.originY))}start(t,e){t&&e&&(this.originX=t,this.originY=e),this.time=[],this.x=[],this.y=[],this.startTime=Date.now(),this.resume()}pause(){q&&q.pause()}resume(){if(!q)throw new Error("Could not find webgazer");q.resume()}setDebug(t){q.showVideoPreview(t),q.showPredictionPoints(t)}setDeaf(t){this.deaf=t}getEyeTrack(t=15){const e={et_time:[],et_x:[],et_y:[],et_start_time:this.startTime};for(let n=0;nt){const r=(this.time[n+1]-this.time[n])/t-1,i=(this.x[n+1]-this.x[n])/(r+1),o=(this.y[n+1]-this.y[n])/(r+1),a=e.et_time.length-1;for(let n=0;n{const e=new Proxy(()=>e,{get:(n,r)=>(t&&t(),"valueOf"===r||"toString"===r||r===Symbol.toPrimitive?()=>"":e)});return e};class K extends a.a{get validators(){return $}get v(){return $}constructor(t){super(),this.experiment={},this.id=t.experimentId,this.serverUrl=t.serverUrl,this.submissionUrl=this.serverUrl+("/"===this.serverUrl[this.serverUrl.length-1]?"":"/")+"api/submit_experiment/"+this.id,this.validateSubmission=t=>!0,this.completionUrl=t.completionUrl,this.contactEmail=t.contactEmail,this.mode=t.mode,this.debug="debug"===t.mode,this.socketUrl=t.socketUrl,this.socket=t.socketUrl?new M(t.experimentId,t.socketUrl,this.onSocketError):Y(()=>this.warning="You are making use of Socket functionality, but no socket URL is set in magpie.config.js"),this.trialData=window.magpie_trial_data={},this.expData=window.magpie_exp_data={},this.progress=-1,this.mousetracking=new V,this.eyetracking=new H,this.currentScreenIndex=0,this.currentSlideIndex=0,this.responseTimeStart=Date.now(),this.measurements={},this.validateMeasurements={},this.timers={},this.warning=null,console.log("magpie "+W.version),console.log("Experiment id: "+this.id),console.log("Server: "+this.serverUrl),console.log("Submission URL: "+this.submissionUrl),console.log("Mode: "+this.mode),console.log("Completion URL: "+this.completionUrl),console.log("magpie_trial_data = ",this.trialData),console.log("magpie_exp_data = ",this.expData),s["default"].observable(this),"prolific"===this.mode&&this.extractProlificData(),this.addExpData({experiment_start_time:Date.now()}),"debug"===this.mode&&(window.onunhandledrejection=t=>{this.warning=t.reason},window.onerror=function(t){this.warning=t})}nextSlide(t){"number"!==typeof t?this.currentSlideIndex++:this.currentSlideIndex=t}nextScreen(t){if("number"===typeof t)this.currentScreenIndex=t;else if("string"===typeof t){const e=this.experiment.$slots.default,n=e.filter(t=>!!t.componentOptions).findIndex(e=>e.componentOptions.propsData.label===t);if(-1===n)throw new Error('Could not find screen with label "'+t+'"');this.currentScreenIndex=n}else this.currentScreenIndex+=1;this.currentSlideIndex=0,this.measurements={},this.currentVarsData={},this.socket.state!==j.CONNECTED&&this.socket.state!==j.READY||this.socket.setCurrentScreen(this.currentScreenIndex),this.responseTimeStart=Date.now(),this.experiment.scrollToTop(),this.mousetracking.start(),this.eyetracking.pause()}saveAndNextScreen(t){this.saveMeasurements(),this.nextScreen(t)}addTrialData(t){this.trialData[this.currentScreenIndex]||(this.trialData[this.currentScreenIndex]=[]),this.trialData[this.currentScreenIndex].push({responseTime:Date.now()-this.responseTimeStart,...t})}addExpData(t){Object.assign(this.expData,t)}saveMeasurements(){this.addTrialData({responseTime:Date.now()-this.responseTimeStart,...this.measurements})}onSocketError(t){console.error(t)}getAllData(){return J({...this.expData,experiment_end_time:Date.now(),experiment_duration:Date.now()-this.expData.experiment_start_time,...(this.socket.state===j.CONNECTED||this.socket.state===j.READY)&&{participantId:this.socket.participantId},...(this.socket.state===j.CONNECTED||this.socket.state===j.READY)&&{groupLabel:this.socket.groupLabel},trials:X(z()(Object.values(this.trialData)).map(t=>Object.assign({},Object.fromEntries(Object.entries(t).filter(([,t])=>"function"!==typeof t)))))})}submit(){if(!this.submissionUrl)throw new Error("No submission URL set");const t=this.getAllData();if(!this.validateSubmission(t))throw new Error("Submission failed validation");return this.submitResults(this.submissionUrl,t)}submitIntermediateResults(){if(!this.submissionUrl)throw new Error("No submission URL set");return this.submitResults(this.submissionUrl,this.getAllData(),!0)}async submitResults(t,e,n){if(this.socket.state===j.CONNECTED||this.socket.state===j.READY)try{const t=n?"save_intermediate_results":"submit_results";return await new Promise((n,r)=>this.socket.participantChannel.push(t,{results:e}).receive("ok",n).receive("error",r))}catch(el){if(n)throw el;console.log("Submission via magpie socket failed, trying HTTP")}const r=await fetch(t,{method:"POST",mode:"cors",headers:{"Content-type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error("The server says: "+await r.text())}setProgress(t){this.progress=t}extractProlificData(){const t=new URL(window.location);this.addExpData({prolific_pid:t.searchParams.get("PROLIFIC_PID"),prolific_study_id:t.searchParams.get("STUDY_ID"),prolific_session_id:t.searchParams.get("SESSION_ID")})}}const X=function(t){for(var e=[],n=0;n({})},imageAssets:{type:Array,default(){return[]}},audioAssets:{type:Array,default(){return[]}},videoAssets:{type:Array,default(){return[]}},validateSubmission:{type:Function,default(){return()=>!0}}},data(){return{currentScreenComponent:{}}},created(){if(this.$parent.magpie=new K(this.$options.magpie),this.$magpie.experiment=this,window.$magpie=this.$magpie,this.$magpie.socketUrl){let t=0;this.$watch("$magpie.socket.participants",e=>{const n=this.$slots.default.filter(t=>!!t.componentOptions);e.length-t<0&&n.length-1!==this.$magpie.currentScreenIndex&&(window.alert(this.$t("interactive.general.aborted")),this.$magpie.nextScreen(n.length-1)),t=e.length})}this.title&&(document.title=this.title),this.imageAssets.forEach(t=>{const e=document.createElement("link");e.href=t,e.rel="preload",e.as="image",document.head.appendChild(e)}),this.audioAssets.forEach(t=>{const e=document.createElement("link");e.href=t,e.rel="preload",e.as="audio",document.head.appendChild(e)}),this.videoAssets.forEach(t=>{const e=document.createElement("link");e.href=t,e.rel="preload",e.as="video",document.head.appendChild(e)}),this.$magpie.validateSubmission=this.validateSubmission,this.$magpie.addExpData(this.recordData),window.addEventListener("beforeunload",t=>{t.preventDefault()})},mounted(){this.$el.addEventListener("mousemove",t=>this.$magpie.mousetracking.onMouseMove(t))},methods:{scrollToTop(){const t=this.$el.getBoundingClientRect();window.scrollTo(0,window.scrollY+t.top)}},render(t){const e=this.$slots.default,n=e?e.filter(t=>!!t.componentOptions)[this.$magpie.currentScreenIndex]:null;return n.key=this.$magpie.currentScreenIndex,t("div",{class:"experiment"+(this.wide?" wide":"")},[t("div",{class:"header"},[t("div",{class:"col title"},this.$slots.title),t("div",{class:"col status"},[-1!==this.$magpie.progress?t(et.a,{props:{percent:100*this.$magpie.progress,showText:!1,lineHeight:10},style:{width:"150px"}}):null])]),n])}},rt=nt,it=(n("2e66"),n("2877")),ot=n("28a2"),at=n.n(ot),st=Object(it["a"])(rt,Z,Q,!1,null,null,null);"function"===typeof at.a&&at()(st);var ut,ct,lt=st.exports,ft=n("1dce"),ht=function(){var t=this,e=t._self._c;return e("div",{staticClass:"debug-statement"},[e("h2",[t._v("magpie "+t._s(t.type))]),t._v(" "+t._s(t.text)+" ")])},dt=[],pt={name:"DebugStatement",props:{text:{type:String,required:!0},type:{type:String,default:"info"}}},vt=pt,gt=(n("4904"),Object(it["a"])(vt,ht,dt,!1,null,"5a63c536",null)),mt=gt.exports,yt={name:"Screen",mixins:[ft["validationMixin"]],props:{title:{type:String,required:!1,default:""},progress:{type:Number,default:-1},label:{type:String,default:""},validations:{type:Object,default(){return{}}}},data(){return{measurements:{}}},watch:{"$magpie.measurements":{handler(){this.measurements=this.$magpie.measurements,this.$v.measurements.$touch()},deep:!0}},beforeMount(){this.$magpie.setProgress(this.progress)},mounted(){this.$magpie.validateMeasurements=this.$v.measurements,this.$magpie.mousetracking.start()},validations(){return{measurements:this.validations}},render(t){const e=this.$slots.default;if(!e)return t("div",{class:"screen"},[this.title?t("h2",this.title):null]);let n;const r=e.filter(t=>!!t.componentOptions);return r.length&&r.every(t=>"Slide"===t.componentOptions.tag)?n=r[this.$magpie.currentSlideIndex]:(n=this.$slots.default,r.some(t=>"Slide"===t.componentOptions.tag)&&(this.$magpie.warning="This screen received mixed contents. Either provide only elements inside your or provide the contents of the first and only slide directly.")),n.key=this.$magpie.currentSlideIndex,t("div",{class:"screen"},[this.title?t("h2",this.title):null,n,this.$magpie.warning?t(mt,{props:{text:this.$magpie.warning,type:"warning"}}):null])}},bt=yt,_t=(n("50f7"),n("3d7b")),wt=n.n(_t),xt=Object(it["a"])(bt,ut,ct,!1,null,"2db71145",null);"function"===typeof wt.a&&wt()(xt);var St=xt.exports,kt=function(){var t=this,e=t._self._c;return e("div",[t._t("default")],2)},Ct=[],Ot={name:"Slide"},Pt=Ot,Tt=Object(it["a"])(Pt,kt,Ct,!1,null,null,null),At=Tt.exports,Et=function(){var t=this,e=t._self._c;return e("div",{staticClass:"completion"},[e("div",{staticClass:"question"},t._l(t.slices,(function(n,r){return e("span",{key:r},[t._v(t._s(n)+" "),r!==t.slices.length-1?e("select",{directives:[{name:"model",rawName:"v-model",value:t.answers[r],expression:"answers[i]"}],on:{change:[function(e){var n=Array.prototype.filter.call(e.target.options,(function(t){return t.selected})).map((function(t){var e="_value"in t?t._value:t.value;return e}));t.$set(t.answers,r,e.target.multiple?n:n[0])},function(e){t.$emit("update:response",t.fullAnswer),t.$emit("update:responses",t.answers)}]}},t._l(t.options[r],(function(n){return e("option",{key:n,domProps:{textContent:t._s(n)}})})),0):t._e()])})),0)])},jt=[],Mt={name:"CompletionInput",props:{text:{type:String,required:!0},options:{type:Array,required:!0}},data(){return{answers:[]}},computed:{slices(){return this.text.split("%s")},fullAnswer(){const t=this.answers.slice();return this.text.split("%s").map(e=>e+(t.shift()||"")).join("")}}},Rt=Mt,Dt=(n("d8c8"),n("c0e4")),It=n.n(Dt),Lt=Object(it["a"])(Rt,Et,jt,!1,null,"20ec9a19",null);"function"===typeof It.a&&It()(Lt);var $t=Lt.exports,Nt=function(){var t=this,e=t._self._c;return e("div",{staticClass:"dropdown-input"},[e("select",{ref:"input",on:{change:function(e){return t.$emit("update:response",t.$refs.input.value)}}},t._l(t.options,(function(n){return e("option",{key:n,domProps:{value:n,textContent:t._s(n)}})})),0)])},Ft=[],Ut={name:"DropdownInput",props:{options:{type:Array,required:!0}}},Bt=Ut,Gt=n("6b80"),zt=n.n(Gt),Vt=Object(it["a"])(Bt,Nt,Ft,!1,null,"6fb3df0e",null);"function"===typeof zt.a&&zt()(Vt);var Wt=Vt.exports,qt=function(){var t=this,e=t._self._c;return e("div",{staticClass:"forced_choice"},[e("div",{staticClass:"options"},t._l(t.options,(function(n){return e("div",{key:n,staticClass:"option",on:{click:function(e){return t.onOptionClick(n)}}},[t._v(" "+t._s(n)+" ")])})),0)])},Ht=[],Yt={name:"ForcedChoiceInput",props:{options:{type:Array,required:!0}},methods:{onOptionClick(t){this.$emit("update:response",t)}}},Kt=Yt,Xt=(n("9cdf"),n("8284")),Jt=n.n(Xt),Zt=Object(it["a"])(Kt,qt,Ht,!1,null,"0428af94",null);"function"===typeof Jt.a&&Jt()(Zt);var Qt=Zt.exports,te=function(){var t=this,e=t._self._c;return e("div",{staticClass:"image_selection"},[e("div",{staticClass:"options"},t._l(t.options,(function(n){return e("div",{key:n.label,staticClass:"option",on:{click:function(e){return t.onOptionClick(n.label)}}},[e("img",{attrs:{src:n.src,alt:n.label},on:{click:function(e){return t.onOptionClick(n.label)}}})])})),0)])},ee=[],ne={name:"ImageSelectionInput",props:{options:{type:Array,required:!0}},methods:{onOptionClick(t){this.$emit("update:response",t)}}},re=ne,ie=(n("f2e3"),n("23dc")),oe=n.n(ie),ae=Object(it["a"])(re,te,ee,!1,null,"36baf217",null);"function"===typeof oe.a&&oe()(ae);var se=ae.exports,ue=function(){var t=this,e=t._self._c;return e("div",{staticClass:"keypress"},[t.showOptions?e("div",{staticClass:"options"},t._l(t.keys,(function(n,r){return e("span",{key:r},[e("strong",{domProps:{textContent:t._s(r)}}),t._v(" = "+t._s(n)+" ")])})),0):t._e()])},ce=[],le={name:"KeypressInput",props:{keys:{type:Object,required:!0},showOptions:{type:Boolean,default:!0}},mounted(){window.document.addEventListener("keydown",this.onKeyDown)},destroyed(){window.document.removeEventListener("keydown",this.onKeyDown)},methods:{onKeyDown(t){"undefined"!==typeof this.keys[t.key]&&(t.preventDefault(),this.$emit("update:response",this.keys[t.key]))}}},fe=le,he=n("66f3"),de=n.n(he),pe=Object(it["a"])(fe,ue,ce,!1,null,"6de4318b",null);"function"===typeof de.a&&de()(pe);var ve=pe.exports,ge=function(){var t=this,e=t._self._c;return e("div",{staticClass:"rating"},[e("form",[e("div",{staticClass:"options"},[e("div",{staticClass:"left"},[t._v(t._s(t.left))]),t._l(t.count,(function(n){return e("label",{key:n},[e("input",{directives:[{name:"model",rawName:"v-model",value:t.answers[n],expression:"answers[i]"}],attrs:{type:"radio",name:"rating"},domProps:{checked:t._q(t.answers[n],null)},on:{input:function(e){return t.$emit("update:response",n)},change:function(e){return t.$set(t.answers,n,null)}}}),t._v(" "+t._s(n))])})),e("div",{staticClass:"right"},[t._v(t._s(t.right))])],2)])])},me=[],ye={name:"RatingInput",props:{count:{type:Number,default:7},left:{type:String,optional:!0,default:""},right:{type:String,optional:!0,default:""}},data(){const t={};for(let e=1;e[]},orientation:{type:String,default:"vertical"},labels:{type:Boolean,default:!0},randomize:{type:Boolean,default:!1}},data(){let t=Object.keys(this.options);return this.randomize&&(t=We()(t)),{order:t}},methods:{onOptionClick(t){this.$emit("update:response",t)}}},He=qe,Ye=(n("2bef"),n("676b")),Ke=n.n(Ye),Xe=Object(it["a"])(He,Ge,ze,!1,null,"f03be8e0",null);"function"===typeof Ke.a&&Ke()(Xe);var Je=Xe.exports,Ze=function(){var t=this,e=t._self._c;return e("div",{staticClass:"matrix-choice"},[e("div",{staticClass:"row header"},[e("p"),e("div",t._l(t.options,(function(n){return e("label",{key:n,domProps:{textContent:t._s(n)}})})),0)]),t.randomize?[t._l(t.randomizedQuestions,(function([n,r]){return[e("div",{key:r,staticClass:"row"},[e("p",[t._v(t._s(n))]),e("MultipleChoiceInput",{attrs:{labels:!1,options:t.options,orientation:"horizontal"},on:{"update:response":function(e){return t.onOptionClick(r,e)}}})],1)]}))]:[t._l(t.questions,(function(n,r){return[e("div",{key:r,staticClass:"row"},[e("p",[t._v(t._s(n))]),e("MultipleChoiceInput",{attrs:{labels:!1,options:t.options,orientation:"horizontal"},on:{"update:response":function(e){return t.onOptionClick(r,e)}}})],1)]}))],e("div",{staticClass:"row header"},[e("p"),e("div",t._l(t.options,(function(n){return e("label",{key:n,domProps:{textContent:t._s(n)}})})),0)])],2)},Qe=[],tn={name:"MultipleChoiceMatrixInput",components:{MultipleChoiceInput:Je},props:{questions:{type:Array,required:!0},options:{type:Array,required:!0},randomize:{type:Boolean,default:!1}},data(){return{responses:[],randomizedQuestions:We()(this.questions.map((t,e)=>[t,e]))}},methods:{onOptionClick(t,e){s["default"].set(this.responses,t,e),this.$emit("update:responses",this.responses)}}},en=tn,nn=(n("8ae6"),n("cfe5")),rn=n.n(nn),on=Object(it["a"])(en,Ze,Qe,!1,null,null,null);"function"===typeof rn.a&&rn()(on);var an=on.exports,sn=function(){var t=this,e=t._self._c;return e("div",{staticClass:"slider"},[e("div",{staticClass:"slider-element"},[e("div",{staticClass:"left"},[t._v(t._s(t.left))]),e("Slider",{staticClass:"slider",attrs:{tooltip:t.tooltip?"always":"none",min:t.min,max:t.max,interval:t.interval,"enable-cross":!1,process:t.process},model:{value:t.value,callback:function(e){t.value=e},expression:"value"}}),e("div",{staticClass:"right"},[t._v(t._s(t.right))])],1)])},un=[],cn={name:"SliderRangesInput",components:{Slider:Pe.a},props:{left:{type:String,optional:!0,default:""},right:{type:String,optional:!0,default:""},initial:{type:Number,optional:!0,default:0},min:{type:Number,optional:!0,default:0},max:{type:Number,optional:!0,default:100},interval:{type:Number,optional:!0,default:1},tooltip:{type:Boolean,optional:!0,default:!1},ranges:{type:Array,required:!0}},data(){return{value:this.ranges.slice(1).map((t,e)=>Math.round((e+1)*(this.max/this.ranges.length))),process:t=>[[this.min,t[0],this.ranges[0]]].concat(t.map((e,n)=>[e,t[n+1]||this.max,this.ranges[n+1]])).map(([t,e,n])=>[t,e,{background:fn(n,hn)}])}},computed:{rangeValues(){return this.value.map((t,e)=>t-(this.value[e-1]||this.min)).concat([this.max-this.value[this.value.length-1]])},responses(){return[this.min].concat(this.value).concat[this.max]}},watch:{value(){this.$emit("update:responses",this.responses),this.$emit("update:rangeValues",this.rangeValues)}},mounted(){this.$emit("update:responses",this.responses),this.$emit("update:rangeValues",this.rangeValues)}};function ln(t){var e,n,r=0;if(0===t.length)return r;for(e=0;e0?e("TimerStop",{attrs:{id:"responseTime"},on:{"update:time":function(e){t.responseTimes.push(e),n===t.targets.length&&r()}}}):t._e(),e("TimerStart",{attrs:{id:"responseTime"}}),-1!==t.responseTimeLimit?e("Wait",{attrs:{time:t.responseTimeLimit},on:{done:function(e){t.timeout=!0}}}):t._e(),e("KeypressInput",{attrs:{keys:{[t.leftKey]:"left",[t.rightKey]:"right"},"show-options":t.showKeypressOptions},on:{"update:response":function(e){t.correct=t.targets[n]===t.getOption(e,n),t.responses.push(t.getOption(e,n)),r()}}}),e("div",{staticClass:"options"},[e("div",{staticClass:"option"},[t._v(" "+t._s(t.getLeftOption(n))+" ")]),e("div",{staticClass:"option"},[t._v(" "+t._s(t.getRightOption(n))+" ")])])]:[e("TimerStop",{attrs:{id:"responseTime"},on:{"update:time":function(e){return t.responseTimes.push(e)}}}),e("Wait",{attrs:{time:0},on:{done:t.end}})]]}}])})],1)},An=[],En=function(){var t=this,e=t._self._c;return e("div",{staticClass:"serial_input"},[e("div",{key:t.i,staticClass:"slice"},[t._t("default",(function(){return[t._v(" No template defined. ")]}),{i:t.i,iterations:t.iterations,record:(e,n)=>t.$magpie.measurements[e]&&t.$magpie.measurements[e].length?t.$magpie.measurements[e].push(n):t.$magpie.measurements[e]=[n],next:()=>t.i++})],2)])},jn=[],Mn={name:"SerialInput",props:{iterations:{type:Number,required:!0}},data(){return{i:0}},watch:{i(){this.i>=this.iterations&&this.$emit("end")}}},Rn=Mn,Dn=n("9315"),In=n.n(Dn),Ln=Object(it["a"])(Rn,En,jn,!1,null,null,null);"function"===typeof In.a&&In()(Ln);var $n=Ln.exports,Nn=function(){var t=this,e=t._self._c;return e("span")},Fn=[],Un={name:"TimerStop",props:{id:{type:String,required:!0}},mounted(){this.$emit("update:time",Date.now()-this.$magpie.timers[this.id])}},Bn=Un,Gn=n("04d3"),zn=n.n(Gn),Vn=Object(it["a"])(Bn,Nn,Fn,!1,null,"51fb0e4e",null);"function"===typeof zn.a&&zn()(Vn);var Wn=Vn.exports,qn=function(){var t=this,e=t._self._c;return e("span")},Hn=[],Yn={name:"TimerStart",props:{id:{type:String,required:!0}},mounted(){this.$magpie.timers[this.id]=Date.now()}},Kn=Yn,Xn=n("bc0d"),Jn=n.n(Xn),Zn=Object(it["a"])(Kn,qn,Hn,!1,null,"87863ff4",null);"function"===typeof Jn.a&&Jn()(Zn);var Qn=Zn.exports,tr=n("2ef0"),er=n.n(tr),nr=function(){var t=this,e=t._self._c;return e("span")},rr=[],ir={name:"Wait",props:{time:{required:!0,type:Number}},data(){return{timeout:null}},watch:{time(){this.$el&&this.set()}},mounted(){this.set()},updated(){this.set()},activated(){this.set()},deactivated(){this.timeout&&clearTimeout(this.timeout)},beforeDestroy(){this.timeout&&clearTimeout(this.timeout)},methods:{set(){this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.$emit("done"),this.time)}}},or=ir,ar=n("5c5c"),sr=n.n(ar),ur=Object(it["a"])(or,nr,rr,!1,null,"16ed3190",null);"function"===typeof sr.a&&sr()(ur);var cr=ur.exports,lr={name:"MazeInput",components:{Wait:cr,TimerStart:Qn,TimerStop:Wn,SerialInput:$n,KeypressInput:ve},props:{targets:{type:Array,required:!0},competitors:{type:Array,required:!0},leftKey:{type:String,default:"f"},rightKey:{type:String,default:"j"},showKeypressOptions:{type:Boolean,default:!0},responseTimeLimit:{type:Number,default:-1}},data(){const t=this.targets.length,e=er.a.map(er.a.range(t),()=>er.a.random());return{responseTimes:[],responses:[],targetOnLeft:e,targetPositions:e.map(t=>t?"left":"right"),timeout:!1,correct:!0}},methods:{getLeftOption(t){return 1===this.targetOnLeft[t]?this.targets[t]:this.competitors[t]},getRightOption(t){return 0===this.targetOnLeft[t]?this.targets[t]:this.competitors[t]},getOption(t,e){return"left"===t?this.getLeftOption(e):this.getRightOption(e)},end(){this.$emit("update:response-times",this.responseTimes),this.$emit("update:responses",this.responses),this.$emit("update:target-positions",this.targetPositions),this.$emit("update:correct",this.correct),this.$emit("update:timeout",this.timeout),this.$emit("end")}}},fr=lr,hr=(n("46c5"),n("9cff")),dr=n.n(hr),pr=Object(it["a"])(fr,Tn,An,!1,null,"e124492a",null);"function"===typeof dr.a&&dr()(pr);var vr=pr.exports,gr=function(){var t=this,e=t._self._c;return e("div",[e("SerialInput",{attrs:{iterations:t.chunks.length+2},on:{end:t.end},scopedSlots:t._u([{key:"default",fn:function({i:n,next:r}){return[t.timeout?[e("TimerStop",{attrs:{id:"responseTime"},on:{"update:time":function(e){return t.responseTimes.push(e)}}}),e("Wait",{attrs:{time:0},on:{done:t.end}})]:[n>1?e("TimerStop",{attrs:{id:"responseTime"},on:{"update:time":function(e){t.responseTimes.push(e),n>t.chunks.length&&r()}}}):t._e(),n>0?e("TimerStart",{attrs:{id:"responseTime"}}):t._e(),e("KeypressInput",{attrs:{keys:{[t.trigger]:t.instructions},"show-options":t.showKeypressOptions},on:{"update:response":r}}),-1!==t.responseTimeLimit&&n>1?e("Wait",{attrs:{time:t.responseTimeLimit},on:{done:function(e){t.timeout=!0}}}):t._e(),e("div",{class:{text:!0,"underline-words":"words"===t.underline,"underline-sentence":"sentence"===t.underline,"show-all":"next"===t.wordPos}},t._l(t.chunks,(function(r,i){return e("span",{key:i,class:{current:n-1===i},domProps:{textContent:t._s(r)}})})),0)]]}}])})],1)},mr=[],yr={name:"SelfPacedReadingInput",components:{Wait:cr,TimerStart:Qn,TimerStop:Wn,SerialInput:$n,KeypressInput:ve},props:{chunks:{type:Array,required:!0},instructions:{type:String,default:"Press SPACE to reveal the words."},trigger:{type:String,default:" "},underline:{type:String,default:"none"},wordPos:{type:String,default:"same"},showKeypressOptions:{type:Boolean,default:!0},responseTimeLimit:{type:Number,default:-1}},data(){return{responseTimes:[],timeout:!1}},methods:{end(){this.$emit("update:response-times",this.responseTimes),this.$emit("update:timeout",this.timeout),this.$emit("end")}}},br=yr,_r=(n("6041"),n("0155")),wr=n.n(_r),xr=Object(it["a"])(br,gr,mr,!1,null,"752e72bd",null);"function"===typeof wr.a&&wr()(xr);var Sr=xr.exports,kr=function(){var t=this,e=t._self._c;return e("div",[t._t("presentation",(function(){return[e("p",[t._v(t._s(t.chunks[t.position]))])]}),{chunk:t.chunks[t.position]}),t.position=this.chunks.length&&this.$emit("end")}}},Pr=Or,Tr=n("c0f2"),Ar=n.n(Tr),Er=Object(it["a"])(Pr,kr,Cr,!1,null,null,null);"function"===typeof Ar.a&&Ar()(Er);var jr=Er.exports,Mr=function(){var t=this,e=t._self._c;return e("CanvasStage",{attrs:{config:{width:800,height:400}}},[e("CanvasLayer",[e("CanvasShape",{attrs:{config:{sceneFunc:function(e,n){e.beginPath(),e.moveTo(t.x-25,t.y-25),e.lineTo(t.x+25,t.y+25),e.moveTo(t.x+25,t.y-25),e.lineTo(t.x-25,t.y+25),e.closePath(),e.strokeShape(n)},strokeWidth:1,stroke:"black"}}})],1)],1)},Rr=[],Dr={name:"FixationCross",props:{x:{type:Number,default:425},y:{type:Number,default:200}}},Ir=Dr,Lr=n("0435"),$r=n.n(Lr),Nr=Object(it["a"])(Ir,Mr,Rr,!1,null,null,null);"function"===typeof $r.a&&$r()(Nr);var Fr=Nr.exports,Ur=function(){var t=this,e=t._self._c;return e("div",{staticClass:"chat"},[e("div",{ref:"box",staticClass:"chat-box"},t._l(t.messages,(function(n,r){return e("p",{key:r,class:{message:"message"===n.event,userEvent:"join"===n.event||"leave"===n.event,me:n.participantId===t.$magpie.socket.participantId},style:{...n.message&&{background:t.$magpie.socket.getParticipantColor(n.participantId)},...!n.message&&{color:t.$magpie.socket.getParticipantColor(n.participantId)}},domProps:{textContent:t._s(n.message||(n.participantId===t.$magpie.socket.participantId?"join"===n.event?t.$t("interactive.Chat.statusYouJoined"):"leave"===n.event?t.$t("interactive.Chat.statusYouLeft"):"":"join"===n.event?t.$t("interactive.Chat.statusParticipantJoined",{user:t.$magpie.socket.getParticipantName(n.participantId)}):"leave"===n.event?t.$t("interactive.Chat.statusParticipantLeft",{user:t.$magpie.socket.getParticipantName(n.participantId)}):""))}})})),0),e("div",{staticClass:"chat-input"},[e("textarea",{ref:"text",attrs:{cols:"50",placeholder:t.$t("interactive.Chat.messageLabel")},on:{keydown:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"enter",13,e.key,"Enter")?null:(e.preventDefault(),t.send.apply(null,arguments))}}}),e("button",{on:{click:function(e){return e.stopPropagation(),t.send()}}},[t._v(t._s(t.$t("general.send")))])])])},Br=[],Gr=n("ceac"),zr=n.n(Gr);const Vr="$magpie.chat_message";var Wr={name:"Chat",props:{participantLabel:{type:String,default:null}},data(){return{messages:[],interval:null}},socket:{[Vr](t){this.messages.push(t),s["default"].nextTick(()=>{this.$refs.box.scrollTop=this.$refs.box.scrollHeight}),this.$emit("update:messages",this.messages.filter(t=>"message"===t.event)),this.$emit("update:data",this.flattenData(this.messages.filter(t=>"message"===t.event)))}},watch:{["$magpie.socket.active"](t,e){const n=zr()(t,e),r=zr()(e,t);r.forEach(t=>{this.messages.push({time:Date.now(),participantId:t,event:"leave",message:""})}),n.forEach(t=>{this.messages.push({time:Date.now(),participantId:t,event:"join",message:""})})}},mounted(){this.$magpie.socket.active.forEach(t=>{this.messages.push({time:Date.now(),participantId:t,event:"join",message:""})})},EVENT_CHAT_MESSAGE:Vr,methods:{send(){const t=this.$refs.text.value;t&&(this.$magpie.socket.broadcast(Vr,{event:"message",message:t,participantId:this.$magpie.socket.participantId,participantLabel:this.participantLabel,time:Date.now()}),this.$refs.text.value="",this.$refs.text.focus())},flattenData(t){return{chatMessage:t.map(t=>t.message),chatParticipantId:t.map(t=>t.participantId),chatParticipantLabel:t.map(t=>t.participantId),chatTime:t.map(t=>t.time)}}}},qr=Wr,Hr=(n("be87"),n("fb49")),Yr=n.n(Hr),Kr=Object(it["a"])(qr,Ur,Br,!1,null,null,null);"function"===typeof Yr.a&&Yr()(Kr);var Xr=Kr.exports,Jr=function(){var t=this,e=t._self._c;return e("span")},Zr=[],Qr={name:"WaitForParticipants",props:{number:{type:Number,required:!0}},watch:{["$magpie.socket.active"](){this.$magpie.socket.active.length===this.number&&this.$emit("done")}},mounted(){this.$magpie.socket.active.length===this.number&&this.$emit("done")}},ti=Qr,ei=n("969e"),ni=n.n(ei),ri=Object(it["a"])(ti,Jr,Zr,!1,null,null,null);"function"===typeof ni.a&&ni()(ri);var ii=ri.exports,oi=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[t.pauseTime?e("Slide",[t.qud?e("p",{domProps:{textContent:t._s(t.qud)}}):t._e(),e("Wait",{key:"pause-timer",attrs:{time:t.pauseTime},on:{done:function(e){return t.$magpie.nextSlide()}}})],1):t._e(),t.fixationTime?e("Slide",[t.qud?e("p",{domProps:{textContent:t._s(t.qud)}}):t._e(),t._t("fixation",(function(){return[e("FixationCross")]})),-1!==t.fixationTime?e("Wait",{key:"fixation-timer",attrs:{time:t.fixationTime},on:{done:function(e){return t.$magpie.nextSlide()}}}):t._e()],2):t._e(),t.stimulusTime?e("Slide",[t.qud?e("p",{domProps:{textContent:t._s(t.qud)}}):t._e(),t._t("stimulus"),-1!==t.stimulusTime?e("Wait",{key:"stimulus-timer",attrs:{time:t.stimulusTime},on:{done:function(e){return t.$magpie.nextSlide()}}}):t._e()],2):t._e(),e("Slide",[t.qud?e("p",{domProps:{textContent:t._s(t.qud)}}):t._e(),t.stimulusTime?t._e():t._t("stimulus"),t._t("task"),t.responseTimeLimit?e("Wait",{attrs:{time:t.responseTimeLimit},on:{done:t.nextAfterTimeout}}):t._e(),e("Record",{attrs:{data:{...t.qud&&{qud:t.qud},...t.responseTimeLimit&&{responseTimeout:!1},...t.pauseTime&&{pauseTime:t.pauseTime},...t.fixationTime&&{fixationTime:t.fixationTime},...t.stimulusTime&&{stimulusTime:t.stimulusTime},...t.responseTimeLimit&&{responseTimeLimit:t.responseTimeLimit},...t.feedbackTime&&{feedbackTime:t.feedbackTime}}}}),e("ResponseTimeStart")],2),t.feedbackTime?e("Slide",[t.qud?e("p",{domProps:{textContent:t._s(t.qud)}}):t._e(),t._t("feedback"),t.feedbackTime>0?e("Wait",{attrs:{time:t.feedbackTime},on:{done:function(e){return t.$magpie.nextScreen()}}}):t._e()],2):t._e()],1)},ai=[],si=function(){var t=this,e=t._self._c;return e("span")},ui=[],ci={name:"ResponseTimeStart",mounted(){this.$magpie.responseTimeStart=Date.now()}},li=ci,fi=n("f88f"),hi=n.n(fi),di=Object(it["a"])(li,si,ui,!1,null,"18fe891b",null);"function"===typeof hi.a&&hi()(di);var pi=di.exports,vi=function(){var t=this,e=t._self._c;return e("span")},gi=[],mi={name:"Record",props:{data:{type:Object,required:!0},global:{type:Boolean,default:!1}},mounted(){this.global?this.$magpie.addExpData(this.data):Object.keys(this.data).forEach(t=>{"undefined"!==typeof this.data[t]&&s["default"].set(this.$magpie.measurements,t,this.data[t])})}},yi=mi,bi=n("ae6f"),_i=n.n(bi),wi=Object(it["a"])(yi,vi,gi,!1,null,"36ef7edc",null);"function"===typeof _i.a&&_i()(wi);var xi=wi.exports,Si={name:"LifecycleScreen",components:{Record:xi,ResponseTimeStart:pi,Wait:cr,FixationCross:Fr,Slide:At,Screen:St},props:{qud:{type:String,default:""},pauseTime:{type:Number,default:0},fixationTime:{type:Number,default:0},stimulusTime:{type:Number,default:0},responseTimeLimit:{type:Number,default:0},feedbackTime:{type:Number,default:0}},methods:{nextAfterResponse(){this.$props.feedbackTime?(this.$magpie.saveMeasurements(),this.$magpie.nextSlide()):this.$magpie.saveAndNextScreen()},nextAfterTimeout(){this.$props.responseTimeLimit&&(this.$magpie.measurements.responseTimeout=!0),this.nextAfterResponse()}}},ki=Si,Ci=n("b8cd"),Oi=n.n(Ci),Pi=Object(it["a"])(ki,oi,ai,!1,null,"d32534da",null);"function"===typeof Oi.a&&Oi()(Pi);var Ti=Pi.exports,Ai=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[t._t("default",(function(){return[t._v(" "+t._s(t.$t("screens.ConnectInteractiveScreen.description"))+" ")]}))],2)},Ei=[],ji={name:"ConnectInteractiveScreen",components:{Screen:St},props:{},watch:{"$magpie.socket.state":function(t){t===j.READY&&this.$magpie.nextScreen()}},mounted(){this.$magpie.socket.initialize(),this.$magpie.socket.state===j.READY&&this.$magpie.nextScreen()}},Mi=ji,Ri=n("43c6"),Di=n.n(Ri),Ii=Object(it["a"])(Mi,Ai,Ei,!1,null,null,null);"function"===typeof Di.a&&Di()(Ii);var Li=Ii.exports,$i=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[t._t("default",(function(){return[t._v(" "+t._s(t.$t("screens.AwaitIteratedResultScreen.description"))+" ")]}))],2)},Ni=[],Fi={name:"AwaitIteratedResultScreen",components:{Screen:St},props:{},watch:{"$magpie.socket.iteratedState":function(){this.$magpie.socket.iteratedState===j.READY&&this.$magpie.nextScreen()}},mounted(){this.$magpie.socket.initialize(),this.$magpie.socket.iteratedState===j.READY&&this.$magpie.nextScreen()}},Ui=Fi,Bi=n("5f89"),Gi=n.n(Bi),zi=Object(it["a"])(Ui,$i,Ni,!1,null,null,null);"function"===typeof Gi.a&&Gi()(zi);var Vi=zi.exports,Wi=function(){var t=this,e=t._self._c;return e("Screen",{staticClass:"debugResults",attrs:{title:"Results"}},[e("Slide",[e("button",{on:{click:t.downloadCsv}},[t._v("Download all data as csv")]),t.results.length?e("table",[e("thead",[e("tr",t._l(Object.keys(t.results[0]),(function(n){return e("th",{key:n},[t._v(t._s(n))])})),0)]),e("tbody",t._l(t.results,(function(n,r){return e("tr",{key:r},t._l(Object.keys(t.results[0]),(function(r,i){return e("td",{key:i},[t._v(" "+t._s(String(n[r]))+" ")])})),0)})),0)]):t._e()])],1)},qi=[],Hi=n("ee10"),Yi=n.n(Hi),Ki={name:"DebugResultsScreen",components:{Slide:At,Screen:St},props:{},data(){return{results:[],csv:""}},mounted(){this.results=this.$magpie.getAllData(),this.csv=Yi()(this.results,{columns:Object.keys(this.results[0]),header:!0})},methods:{downloadCsv(){let t=new Blob([this.csv],{type:"text/plain",endings:"native"});this.download("magpie-"+this.$magpie.id+"-"+(new Date).toISOString().slice(0,10)+".csv",t)},download(t,e){const n=document.createElement("a");let r=URL.createObjectURL(e);n.setAttribute("href",r),n.setAttribute("download",t),n.style.display="none",document.body.appendChild(n),n.click(),URL.revokeObjectURL(r),document.body.removeChild(n)}}},Xi=Ki,Ji=(n("de44"),n("775d")),Zi=n.n(Ji),Qi=Object(it["a"])(Xi,Wi,qi,!1,null,"681a623c",null);"function"===typeof Zi.a&&Zi()(Qi);var to=Qi.exports,eo=function(){var t=this,e=t._self._c;return t.$magpie.debug?e("DebugResultsScreen"):e("Screen",{attrs:{title:"Submitting"}},[e("Slide",[e("p",[t._v(t._s(t.$t("screens.SubmitResultsScreen.waiting")))]),e("Wait",{attrs:{time:0},on:{done:function(e){t.submit(()=>t.$magpie.nextSlide())}}})],1),e("Slide",[t.error?e("div",[e("p",[t._v(t._s(t.$t("screens.SubmitResultsScreen.error")))]),e("p",[t._v(" "+t._s(t.$t("screens.SubmitResultsScreen.contact"))+" "),e("a",{attrs:{href:"mailto:"+t.$magpie.contactEmail}},[t._v(t._s(t.$magpie.contactEmail))]),t._v(". ")]),e("p",{domProps:{textContent:t._s(t.error)}})]):e("p",[t._v(" "+t._s(t.$t("screens.SubmitResultsScreen.done"))+" "),e("Wait",{attrs:{time:3e3},on:{done:t.redirectToCompletionUrl}})],1)])],1)},no=[],ro={name:"SubmitResultsScreen",components:{Slide:At,DebugResultsScreen:to,Wait:cr,Screen:St},props:{},data(){return{error:null}},methods:{async submit(t){try{await this.$magpie.submit(),t()}catch(e){this.error=e.message,t()}},redirectToCompletionUrl(){this.$magpie.completionUrl&&"prolific"===this.$magpie.mode&&(window.location=this.$magpie.completionUrl)}}},io=ro,oo=n("656e"),ao=n.n(oo),so=Object(it["a"])(io,eo,no,!1,null,null,null);"function"===typeof ao.a&&ao()(so);var uo=so.exports,co=function(){var t=this,e=t._self._c;return e("Screen",t._b({attrs:{title:"Additional information"}},"Screen",{...t.$attrs,...t.$props},!1),[e("Slide",[e("p",[t._v(" "+t._s(t.$t("screens.PostTestScreen.instruction"))+" ")]),e("div",{staticStyle:{"text-align":"left",width:"200px",margin:"0 auto"}},[t.age?e("p",[e("label",[t._v(t._s(t.$t("screens.PostTestScreen.age"))+" "),e("input",{directives:[{name:"model",rawName:"v-model",value:t.$magpie.measurements.age,expression:"$magpie.measurements.age"}],attrs:{type:"number",max:"110",min:"18"},domProps:{value:t.$magpie.measurements.age},on:{input:function(e){e.target.composing||t.$set(t.$magpie.measurements,"age",e.target.value)}}})])]):t._e(),t.gender?e("p",[e("label",[t._v(t._s(t.$t("screens.PostTestScreen.gender"))+" "),e("DropdownInput",{attrs:{options:["",t.$t("screens.PostTestScreen.male"),t.$t("screens.PostTestScreen.female"),t.$t("screens.PostTestScreen.otherGender")],response:t.$magpie.measurements.gender},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"gender",e)}}})],1)]):t._e(),t.education?e("p",[e("label",[t._v(t._s(t.$t("screens.PostTestScreen.education"))+" "),e("DropdownInput",{attrs:{options:["",t.$t("screens.PostTestScreen.educationBelowHighschool"),t.$t("screens.PostTestScreen.educationHighschool"),t.$t("screens.PostTestScreen.educationCollege"),t.$t("screens.PostTestScreen.educationHigher")],response:t.$magpie.measurements.education},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"education",e)}}})],1)]):t._e(),t.languages?e("p",[e("label",[t._v(t._s(t.$t("screens.PostTestScreen.nativeLanguages"))+" "),e("input",{directives:[{name:"model",rawName:"v-model",value:t.$magpie.measurements.languages,expression:"$magpie.measurements.languages"}],attrs:{type:"text",placeholder:t.$t("screens.PostTestScreen.nativeLanguagesExplanation"),title:t.$t("screens.PostTestScreen.nativeLanguagesExplanation")},domProps:{value:t.$magpie.measurements.languages},on:{input:function(e){e.target.composing||t.$set(t.$magpie.measurements,"languages",e.target.value)}}})])]):t._e(),t._t("default",null,{measurements:t.$magpie.measurements}),t._v(" "+t._s(t.$t("screens.PostTestScreen.comments"))+" "),e("TextareaInput",{attrs:{response:t.$magpie.measurements.comments},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"comments",e)}}})],2),e("button",{on:{click:function(e){t.$magpie.addExpData(t.$magpie.measurements),t.$magpie.nextScreen()}}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")])])],1)},lo=[],fo={name:"PostTestScreen",components:{Slide:At,DropdownInput:Wt,TextareaInput:Be,Screen:St},props:{age:{type:Boolean,default:!0},gender:{type:Boolean,default:!0},education:{type:Boolean,default:!0},languages:{type:Boolean,default:!0},comments:{type:Boolean,default:!0}}},ho=fo,po=n("eb48"),vo=n.n(po),go=Object(it["a"])(ho,co,lo,!1,null,"1cb95052",null);"function"===typeof vo.a&&vo()(go);var mo=go.exports,yo=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[e("Slide",[e("div",{staticClass:"instructions"},[t._t("default")],2),e("button",{on:{click:function(e){return t.$magpie.nextScreen()}}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")])])],1)},bo=[],_o={name:"InstructionScreen",components:{Slide:At,Screen:St},props:{}},wo=_o,xo=(n("fd96"),n("e09c")),So=n.n(xo),ko=Object(it["a"])(wo,yo,bo,!1,null,"286444fe",null);"function"===typeof So.a&&So()(ko);var Co=ko.exports,Oo=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[e("Slide",[e("Wait",{key:"start",attrs:{time:0},on:{done:t.onStart}}),e("p",[t._v(t._s(t.$t("screens.EyetrackingCalibrationScreen.start")))])],1),e("Slide",[e("Wait",{key:"calibration",attrs:{time:0},on:{done:t.runCalibration}}),e("p",[t._v(t._s(t.$t("screens.EyetrackingCalibrationScreen.instruction")))]),e("CanvasStage",{staticClass:"point",style:{left:t.x+"px",top:t.y+"px"},attrs:{config:{width:26,height:26}},on:{click:t.nextPoint}},[e("CanvasLayer",[e("CanvasCircle",{attrs:{config:{x:13,y:13,fill:"red",radius:12,stroke:"black",strokeWidth:1}}})],1)],1)],1),e("Slide",[e("p",[t._v(t._s(t.$t("screens.EyetrackingCalibrationScreen.error")))])])],1)},Po=[],To=n("db1a"),Ao=n.n(To),Eo={name:"EyetrackingCalibrationScreen",components:{Slide:At,Screen:St},props:{debug:{type:Boolean,default:!1}},data(){return{x:0,y:0,calibrationSequence:[]}},methods:{nextPoint(){const t=this.calibrationSequence.pop();t?Object.assign(this,t):(this.$magpie.eyetracking.setDeaf(!1),this.$magpie.nextScreen())},async onStart(){this.$magpie.eyetracking.setDeaf(!0);try{await this.$magpie.eyetracking.initialize(),this.$magpie.eyetracking.setDebug(this.debug),this.$magpie.nextSlide()}catch(el){console.error(el),this.$magpie.nextSlide(2)}},runCalibration(){const t=this.$magpie.experiment.$el.getBoundingClientRect();[0,.25*t.height,t.height/2,.75*t.height].forEach(e=>{[0,.25*t.width,t.width/2,.75*t.width,t.width].forEach(t=>{this.calibrationSequence.push({x:t,y:e})})}),this.calibrationSequence=z()(Ao()(2,()=>We()(this.calibrationSequence))),this.nextPoint()}}},jo=Eo,Mo=(n("9bb1"),n("39a4")),Ro=n.n(Mo),Do=Object(it["a"])(jo,Oo,Po,!1,null,"8ef3bc36",null);"function"===typeof Ro.a&&Ro()(Do);var Io=Do.exports,Lo=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[e("Slide",[e("p",[t._v(t._s(t.$t("screens.EyetrackingValidationScreen.instruction")))]),e("Wait",{attrs:{time:5e3},on:{done:t.measureAccuracy}}),e("EyetrackingStart"),e("CanvasStage",{ref:"checkpoint",staticClass:"point check",style:{top:t.windowHeight/2+"px",left:t.windowWidth/2+"px"},attrs:{config:{width:26,height:26}}},[e("CanvasLayer",[e("CanvasCircle",{attrs:{config:{x:13,y:13,fill:"lightblue",radius:12,stroke:"black",strokeWidth:1}}})],1)],1)],1),e("Slide",[e("p",[t._v(t._s(t.$t("screens.EyetrackingValidationScreen.error")))])])],1)},$o=[],No=function(){var t=this,e=t._self._c;return e("span")},Fo=[],Uo={name:"EyetrackingStart",mounted(){this.$magpie.eyetracking.start()}},Bo=Uo,Go=n("cc16"),zo=n.n(Go),Vo=Object(it["a"])(Bo,No,Fo,!1,null,"cea287d6",null);"function"===typeof zo.a&&zo()(Vo);var Wo=Vo.exports,qo={name:"EyetrackingValidationScreen",components:{Wait:cr,EyetrackingStart:Wo,Slide:At,Screen:St},props:{precision:{type:Number,default:100}},data(){return{x:0,y:0,calibrationSequence:[]}},computed:{windowHeight(){return window.innerHeight},windowWidth(){return window.innerWidth}},methods:{measureAccuracy(){const t=this.$magpie.eyetracking.getEyeTrack(),e={x:window.innerWidth/2,y:window.innerHeight/2};let n,r,i,o=0;for(let s=0;st.label)}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("ImageSelectionInput",{attrs:{options:t.options,response:t.$magpie.measurements.response},on:{"update:response":[function(e){return t.$set(t.$magpie.measurements,"response",e)},t.nextAfterResponse]}})]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},sa=[],ua={name:"ImageSelectionScreen",components:{LifecycleScreen:Ti,ImageSelectionInput:se,Record:xi},extends:Ti,props:{question:{type:String,default:void 0},options:{type:Array,required:!0}},methods:{next(){this.$attrs.feedbackTime?(this.$magpie.save(),this.$magpie.nextSlide()):this.$magpie.saveAndNextScreen()}}},ca=ua,la=n("bb2d"),fa=n.n(la),ha=Object(it["a"])(ca,aa,sa,!1,null,"2f4f474a",null);"function"===typeof fa.a&&fa()(ha);var da=ha.exports,pa=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("TextareaInput",{attrs:{response:t.$magpie.measurements.response},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"response",e)}}}),!t.$magpie.measurements.response||t.$magpie.validateMeasurements.response&&t.$magpie.validateMeasurements.response.$invalid?t._e():e("button",{on:{click:t.nextAfterResponse}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")])]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},va=[],ga={name:"TextareaScreen",components:{LifecycleScreen:Ti,TextareaInput:Be,Record:xi},extends:Ti,props:{question:{type:String,required:!0}}},ma=ga,ya=n("7991"),ba=n.n(ya),_a=Object(it["a"])(ma,pa,va,!1,null,"0d144568",null);"function"===typeof ba.a&&ba()(_a);var wa=_a.exports,xa=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question,...t.optionLeft&&{optionLeft:t.optionLeft},...t.optionRight&&{optionRight:t.optionRight},interval:t.interval,max:t.max,min:t.min,initial:t.initial}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("SliderInput",{attrs:{left:t.optionLeft,right:t.optionRight,min:t.min,max:t.max,interval:t.interval,initial:t.initial,disabled:t.disabled,response:t.$magpie.measurements.response},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"response",e)}}}),t.$magpie.measurements.response&&!t.$magpie.validateMeasurements.$invalid?e("button",{on:{click:t.nextAfterResponse}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")]):t._e()]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},Sa=[],ka={name:"SliderScreen",components:{LifecycleScreen:Ti,SliderInput:Re,Record:xi},extends:Ti,props:{question:{type:String,required:!0},optionLeft:{type:String,default:""},optionRight:{type:String,default:""},initial:{type:Number,optional:!0,default:0},min:{type:Number,optional:!0,default:0},max:{type:Number,optional:!0,default:100},interval:{type:Number,optional:!0,default:1},disabled:{type:Boolean,optional:!0,default:!1}}},Ca=ka,Oa=n("5517"),Pa=n.n(Oa),Ta=Object(it["a"])(Ca,xa,Sa,!1,null,"6468ed0d",null);"function"===typeof Pa.a&&Pa()(Ta);var Aa=Ta.exports,Ea=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question,...t.optionLeft&&{optionLeft:t.optionLeft},...t.optionRight&&{optionRight:t.optionRight},interval:t.interval,ranges:t.ranges,min:t.min,max:t.max}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("SliderRangesInput",{attrs:{left:t.optionLeft,right:t.optionRight,min:t.min,max:t.max,interval:t.interval,ranges:t.ranges,responses:t.$magpie.measurements.response,"range-values":t.$magpie.measurements.range_values},on:{"update:responses":function(e){return t.$set(t.$magpie.measurements,"response",e)},"update:rangeValues":function(e){return t.$set(t.$magpie.measurements,"range_values",e)},"update:range-values":function(e){return t.$set(t.$magpie.measurements,"range_values",e)}}}),t.$magpie.measurements.range_values?e("ul",t._l(t.$magpie.measurements.range_values,(function(n,r){return e("li",{key:r},[t._v(" "+t._s(n)+" "+t._s(t.ranges[r])+" ")])})),0):t._e(),!t.$magpie.measurements.response||t.$magpie.validateMeasurements.response&&t.$magpie.validateMeasurements.response.$invalid?t._e():e("button",{on:{click:t.nextAfterResponse}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")])]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},ja=[],Ma={name:"SliderRangesScreen",components:{LifecycleScreen:Ti,SliderRangesInput:mn,Record:xi},extends:Ti,props:{question:{type:String,required:!0},ranges:{type:Array,required:!0},optionLeft:{type:String,default:""},optionRight:{type:String,default:""},min:{type:Number,optional:!0,default:0},max:{type:Number,optional:!0,default:100},interval:{type:Number,optional:!0,default:1}}},Ra=Ma,Da=n("5046"),Ia=n.n(Da),La=Object(it["a"])(Ra,Ea,ja,!1,null,"674745fd",null);"function"===typeof Ia.a&&Ia()(La);var $a=La.exports,Na=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question,...t.optionLeft&&{optionLeft:t.optionLeft},...t.optionRight&&{optionRight:t.optionRight},count:t.count}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("RatingInput",{attrs:{left:t.optionLeft,right:t.optionRight,count:t.count,response:t.$magpie.measurements.response},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"response",e)}}}),!t.$magpie.measurements.response||t.$magpie.validateMeasurements.response&&t.$magpie.validateMeasurements.response.$invalid?t._e():e("button",{on:{click:function(e){return t.$magpie.saveAndNextScreen()}}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")])]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},Fa=[],Ua={name:"RatingScreen",components:{LifecycleScreen:Ti,RatingInput:Se,Record:xi},extends:Ti,props:{question:{type:String,required:!0},optionLeft:{type:String,default:""},optionRight:{type:String,default:""},count:{type:Number,default:7}}},Ba=Ua,Ga=n("686b"),za=n.n(Ga),Va=Object(it["a"])(Ba,Na,Fa,!1,null,"1d16eb65",null);"function"===typeof za.a&&za()(Va);var Wa=Va.exports,qa=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question,options:t.options,text:t.text}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("CompletionInput",{attrs:{text:t.text,options:t.options,response:t.$magpie.measurements.response,responses:t.$magpie.measurements.responses},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"response",e)},"update:responses":function(e){return t.$set(t.$magpie.measurements,"responses",e)}}}),t.$magpie.measurements.responses&&t.$magpie.measurements.responses.filter(Boolean).length===t.options.length?e("button",{on:{click:t.nextAfterResponse}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")]):t._e()]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},Ha=[],Ya={name:"CompletionScreen",components:{LifecycleScreen:Ti,CompletionInput:$t,Record:xi},extends:Ti,props:{question:{type:String,default:void 0},text:{type:String,required:!0},options:{type:Array,required:!0}}},Ka=Ya,Xa=n("748d"),Ja=n.n(Xa),Za=Object(it["a"])(Ka,qa,Ha,!1,null,"0526d666",null);"function"===typeof Ja.a&&Ja()(Za);var Qa=Za.exports,ts=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("KeypressInput",{attrs:{keys:t.keys,"show-options":t.showOptions,response:t.$magpie.measurements.response},on:{"update:response":[function(e){return t.$set(t.$magpie.measurements,"response",e)},t.nextAfterResponse]}})]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation",(function(){return[e("FixationCross")]})),e("KeypressInput",{attrs:{keys:t.keys,"show-options":t.showOptions}})],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},es=[],ns={name:"KeypressScreen",components:{FixationCross:Fr,LifecycleScreen:Ti,KeypressInput:ve,Record:xi},extends:Ti,props:{question:{type:String,default:void 0},keys:{type:Object,required:!0},showOptions:{type:Boolean,default:!0}}},rs=ns,is=n("8b74"),os=n.n(is),as=Object(it["a"])(rs,ts,es,!1,null,"08791dd8",null);"function"===typeof os.a&&os()(as);var ss=as.exports,us=function(){var t=this,e=t._self._c;return e("Screen",t._b({},"Screen",{...t.$attrs,...t.$props},!1),[e("Slide",[t.qud?e("p",{staticClass:"qud",domProps:{textContent:t._s(t.qud)}}):t._e(),t._t("preparation",(function(){return[e("Wait",{attrs:{time:1},on:{done:function(e){return t.$magpie.nextSlide()}}})]}))],2),e("Slide",[t.qud?e("p",{staticClass:"qud",domProps:{textContent:t._s(t.qud)}}):t._e(),e("Wait",{key:"pause",attrs:{time:t.pauseTime},on:{done:function(e){return t.$magpie.nextSlide()}}})],1),e("Slide",[t.qud?e("p",{staticClass:"qud",domProps:{textContent:t._s(t.qud)}}):t._e(),e("Wait",{key:"wait a bit",attrs:{time:500},on:{done:function(e){return t.$magpie.nextSlide()}}}),e("div",{staticClass:"options"},[e("div",{staticClass:"option1"},[t._t("option1")],2),e("div",{staticClass:"space"}),e("div",{staticClass:"option2"},[t._t("option2")],2)])],1),e("Slide",[e("div",{staticClass:"options"},[t.$magpie.measurements.response?t._e():e("div",{staticClass:"option1",on:t._d({},[t.selectEvent,function(e){return t.submit("option1")}])},[t._t("option1")],2),e("div",{staticClass:"space"}),t.$magpie.measurements.response?t._e():e("div",{staticClass:"option2",on:t._d({},[t.selectEvent,function(e){return t.submit("option2")}])},[t._t("option2")],2)]),t.qud?e("p",{staticClass:"qud",domProps:{textContent:t._s(t.qud)}}):t._e(),e("div",{staticClass:"stimulus"},[t.playing?t._t("stimulus",null,{coordinates:t.buttonCoordinates}):t._e(),t.$magpie.measurements.response?t._t("feedback"):t._e()],2),t.playing?t._e():e("button",{ref:"button",on:{click:t.onPressPlay}},[t._v(" "+t._s(t.$t("general.go"))+" ")]),t.playing&&t.responseTimeLimit?e("Wait",{attrs:{time:t.responseTimeLimit},on:{done:function(e){return t.$magpie.nextSlide()}}}):t._e(),t.playing?e("TimerStart",{attrs:{id:"fcmt-response-time"}}):t._e(),t.$magpie.measurements.response?e("TimerStop",{attrs:{id:"fcmt-response-time",time:t.$magpie.measurements.responseTime},on:{"update:time":function(e){return t.$set(t.$magpie.measurements,"responseTime",e)}}}):t._e()],1)],1)},cs=[],ls={name:"ForcedChoiceMousetrackingScreen",components:{TimerStart:Qn,TimerStop:Wn,Slide:At,Screen:St,Wait:cr},props:{option1:{type:String,default:"option1"},option2:{type:String,default:"option2"},selectEvent:{type:String,default:"mouseover"},qud:{type:String,default:void 0},pauseTime:{type:Number,default:0},responseTimeLimit:{type:Number,default:0}},data(){return{playing:!1}},computed:{buttonCoordinates(){return{x:this.$refs.button.getBoundingClientRect().x,y:this.$refs.button.getBoundingClientRect().y}}},methods:{onPressPlay(){this.playing=!0,this.$magpie.mousetracking.start(this.buttonCoordinates.x,this.buttonCoordinates.y)},submit(t){if(!this.playing)return;this.$magpie.measurements.response=this[t];const e=this.$magpie.mousetracking.getMouseTrack();for(const n in e)s["default"].set(this.$magpie.measurements,n,JSON.parse(JSON.stringify(e[n])))}}},fs=ls,hs=(n("c3bc"),n("7518")),ds=n.n(hs),ps=Object(it["a"])(fs,us,cs,!1,null,"22cf83e4",null);"function"===typeof ds.a&&ds()(ps);var vs=ps.exports,gs=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question,options:t.options,orientation:t.orientation,randomize:t.randomize,...t.optionsHtml.length&&{optionsHtml:t.optionsHtml}}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("MultipleChoiceInput",{attrs:{options:t.options,"options-html":t.optionsHtml,orientation:t.orientation,randomize:t.randomize,response:t.$magpie.measurements.response},on:{"update:response":function(e){return t.$set(t.$magpie.measurements,"response",e)}}}),!t.$magpie.measurements.response||t.$magpie.validateMeasurements.response&&t.$magpie.validateMeasurements.response.$invalid?t._e():e("button",{on:{click:function(e){return t.$magpie.saveAndNextScreen()}}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")])]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},ms=[],ys={name:"MultipleChoiceScreen",components:{LifecycleScreen:Ti,MultipleChoiceInput:Je,Record:xi},extends:Ti,props:{question:{type:String,required:!0},options:{type:Array,required:!0},optionsHtml:{type:Array,default:()=>[]},orientation:{type:String,default:"vertical"},randomize:{type:Boolean,default:!1}}},bs=ys,_s=n("4f8b"),ws=n.n(_s),xs=Object(it["a"])(bs,gs,ms,!1,null,"ccf8f3fe",null);"function"===typeof ws.a&&ws()(xs);var Ss=xs.exports,ks=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"task",fn:function(){return[e("Record",{attrs:{data:{questions:t.questions,options:t.options,...t.randomize&&{randomize:t.randomize}}}}),e("MultipleChoiceMatrixInput",{attrs:{options:t.options,questions:t.questions,randomize:t.randomize,responses:t.$magpie.measurements.responses},on:{"update:responses":function(e){return t.$set(t.$magpie.measurements,"responses",e)}}}),t.$magpie.measurements.responses&&!t.$magpie.validateMeasurements.$invalid?e("button",{on:{click:t.nextAfterResponse}},[t._v(" "+t._s(t.$t("general.nextButton"))+" ")]):t._e()]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1),[e("template",{slot:"fixation"},[t._t("fixation")],2),e("template",{slot:"stimulus"},[t._t("stimulus")],2)],2)},Cs=[],Os={name:"MultipleChoiceMatrixScreen",components:{LifecycleScreen:Ti,MultipleChoiceMatrixInput:an,Record:xi},extends:Ti,props:{questions:{type:Array,required:!0},options:{type:Array,required:!0},randomize:{type:Boolean,default:!1}}},Ps=Os,Ts=n("d3e0"),As=n.n(Ts),Es=Object(it["a"])(Ps,ks,Cs,!1,null,"489277d4",null);"function"===typeof As.a&&As()(Es);var js=Es.exports,Ms=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"fixation",fn:function(){return[t._t("fixation",(function(){return[e("FixationCross")]}))]},proxy:!0},{key:"stimulus",fn:function(){return[t._t("stimulus")]},proxy:!0},{key:"task",fn:function(){return[e("Record",{attrs:{data:{question:t.question,targets:t.targets,competitors:t.competitors,leftKey:t.leftKey,rightKey:t.rightKey,mazeTimeLimit:t.mazeTimeLimit}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),e("MazeInput",{attrs:{targets:t.targets,competitors:t.competitors,"response-time-limit":t.mazeTimeLimit,"response-times":t.$magpie.measurements.times,"target-positions":t.$magpie.measurements.target_positions,responses:t.$magpie.measurements.responses,timeout:t.$magpie.measurements.maze_timeout,correct:t.$magpie.measurements.correct},on:{"update:responseTimes":function(e){return t.$set(t.$magpie.measurements,"times",e)},"update:response-times":function(e){return t.$set(t.$magpie.measurements,"times",e)},"update:targetPositions":function(e){return t.$set(t.$magpie.measurements,"target_positions",e)},"update:target-positions":function(e){return t.$set(t.$magpie.measurements,"target_positions",e)},"update:responses":function(e){return t.$set(t.$magpie.measurements,"responses",e)},"update:timeout":function(e){return t.$set(t.$magpie.measurements,"maze_timeout",e)},"update:correct":function(e){return t.$set(t.$magpie.measurements,"correct",e)},end:t.nextAfterResponse}})]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1))},Rs=[],Ds={name:"MazeScreen",components:{LifecycleScreen:Ti,MazeInput:vr,Record:xi},extends:Ti,props:{question:{type:String,default:void 0},targets:{type:Array,required:!0},competitors:{type:Array,required:!0},mazeTimeLimit:{type:Number,default:-1},leftKey:{type:String,default:"f"},rightKey:{type:String,default:"j"},progress:{type:Number,default:void 0}}},Is=Ds,Ls=n("baba"),$s=n.n(Ls),Ns=Object(it["a"])(Is,Ms,Rs,!1,null,null,null);"function"===typeof $s.a&&$s()(Ns);var Fs=Ns.exports,Us=function(){var t=this,e=t._self._c;return e("LifecycleScreen",t._b({scopedSlots:t._u([{key:"fixation",fn:function(){return[t._t("fixation",(function(){return[e("FixationCross")]}))]},proxy:!0},{key:"stimulus",fn:function(){return[t._t("stimulus")]},proxy:!0},{key:"task",fn:function(){return[e("Record",{attrs:{data:{chunks:t.chunks,trigger:t.trigger,underline:t.underline,wordPos:t.wordPos,question:t.question}}}),t.question?e("p",{domProps:{textContent:t._s(t.question)}}):t._e(),t.instructions?e("p",{domProps:{textContent:t._s(t.instructions)}}):t._e(),e("SelfPacedReadingInput",{attrs:{chunks:t.chunks,"word-pos":t.wordPos,underline:t.underline,trigger:t.trigger,"response-times":t.$magpie.measurements.response_times,timeout:t.$magpie.measurements.spr_timeout,"show-keypress-options":!1},on:{"update:responseTimes":function(e){return t.$set(t.$magpie.measurements,"response_times",e)},"update:response-times":function(e){return t.$set(t.$magpie.measurements,"response_times",e)},"update:timeout":function(e){return t.$set(t.$magpie.measurements,"spr_timeout",e)},end:t.nextAfterResponse}})]},proxy:!0},{key:"feedback",fn:function(){return[t._t("feedback")]},proxy:!0}],null,!0)},"LifecycleScreen",{...t.$attrs,...t.$props},!1))},Bs=[],Gs={name:"SelfPacedReadingScreen",components:{LifecycleScreen:Ti,SelfPacedReadingInput:Sr},extends:Ti,props:{question:{type:String,default:void 0},chunks:{type:Array,required:!0},instructions:{type:String,default:"Press SPACE to reveal the words."},trigger:{type:String,default:" "},underline:{type:String,default:"none"},wordPos:{type:String,default:"same"},sprTimeLimit:{type:Number,default:-1}},data(){return{responseTimes:[],responseTimeout:!1}}},zs=Gs,Vs=(n("a4a0"),n("39cd")),Ws=n.n(Vs),qs=Object(it["a"])(zs,Us,Bs,!1,null,"18f4a5b4",null);"function"===typeof Ws.a&&Ws()(qs);var Hs=qs.exports,Ys=function(){var t=this,e=t._self._c;return e("span")},Ks=[],Xs={name:"MousetrackingStart",mounted(){this.$magpie.mousetracking.start()}},Js=Xs,Zs=n("acf4"),Qs=n.n(Zs),tu=Object(it["a"])(Js,Ys,Ks,!1,null,"39ed7d0a",null);"function"===typeof Qs.a&&Qs()(tu);var eu=tu.exports,nu=function(){var t=this,e=t._self._c;return e("span")},ru=[],iu={name:"FullscreenStart",mounted(){document.documentElement.requestFullscreen()}},ou=iu,au=n("38e4"),su=n.n(au),uu=Object(it["a"])(ou,nu,ru,!1,null,"292734e2",null);"function"===typeof su.a&&su()(uu);var cu=uu.exports,lu=function(){var t=this,e=t._self._c;return e("span")},fu=[],hu={name:"HideCursor",mounted(){document.onmousedown=()=>!1,document.onclick=()=>!1,document.body.classList.add("nocursor")},deactivated(){document.onmousedown=null,document.onclick=null,document.body.classList.remove("nocursor")},destroyed(){document.onmousedown=null,document.onclick=null,document.body.classList.remove("nocursor")}},du=hu,pu=(n("98b6"),n("5ec0")),vu=n.n(pu),gu=Object(it["a"])(du,lu,fu,!1,null,null,null);"function"===typeof vu.a&&vu()(gu);var mu=gu.exports,yu=function(){var t=this,e=t._self._c;return e("span")},bu=[],_u={name:"PreventCopyPaste",mounted(){document.onselectstart=()=>!1,document.oncontextmenu=()=>!1,document.body.classList.add("noselect")},deactivated(){document.onselectstart=null,document.oncontextmenu=null,document.body.classList.remove("noselect")},destroyed(){document.onselectstart=null,document.oncontextmenu=null,document.body.classList.remove("noselect")}},wu=_u,xu=(n("bd52"),n("627d")),Su=n.n(xu),ku=Object(it["a"])(wu,yu,bu,!1,null,null,null);"function"===typeof Su.a&&Su()(ku);var Cu=ku.exports;const Ou=()=>n.e("chunk-1335a3e6").then(n.bind(null,"39ca")); +/*! + * vue-i18n v8.27.2 + * (c) 2022 kazuya kawaguchi + * Released under the MIT License. + */var Pu=["compactDisplay","currency","currencyDisplay","currencySign","localeMatcher","notation","numberingSystem","signDisplay","style","unit","unitDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"];function Tu(t,e){"undefined"!==typeof console&&(console.warn("[vue-i18n] "+t),e&&console.warn(e.stack))}function Au(t,e){"undefined"!==typeof console&&(console.error("[vue-i18n] "+t),e&&console.error(e.stack))}var Eu=Array.isArray;function ju(t){return null!==t&&"object"===typeof t}function Mu(t){return"boolean"===typeof t}function Ru(t){return"string"===typeof t}var Du=Object.prototype.toString,Iu="[object Object]";function Lu(t){return Du.call(t)===Iu}function $u(t){return null===t||void 0===t}function Nu(t){return"function"===typeof t}function Fu(){var t=[],e=arguments.length;while(e--)t[e]=arguments[e];var n=null,r=null;return 1===t.length?ju(t[0])||Eu(t[0])?r=t[0]:"string"===typeof t[0]&&(n=t[0]):2===t.length&&("string"===typeof t[0]&&(n=t[0]),(ju(t[1])||Eu(t[1]))&&(r=t[1])),{locale:n,params:r}}function Uu(t){return JSON.parse(JSON.stringify(t))}function Bu(t,e){if(t.delete(e))return t}function Gu(t){var e=[];return t.forEach((function(t){return e.push(t)})),e}function zu(t,e){return!!~t.indexOf(e)}var Vu=Object.prototype.hasOwnProperty;function Wu(t,e){return Vu.call(t,e)}function qu(t){for(var e=arguments,n=Object(t),r=1;r/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ku(t){return null!=t&&Object.keys(t).forEach((function(e){"string"==typeof t[e]&&(t[e]=Yu(t[e]))})),t}function Xu(t){t.prototype.hasOwnProperty("$i18n")||Object.defineProperty(t.prototype,"$i18n",{get:function(){return this._i18n}}),t.prototype.$t=function(t){var e=[],n=arguments.length-1;while(n-- >0)e[n]=arguments[n+1];var r=this.$i18n;return r._t.apply(r,[t,r.locale,r._getMessages(),this].concat(e))},t.prototype.$tc=function(t,e){var n=[],r=arguments.length-2;while(r-- >0)n[r]=arguments[r+2];var i=this.$i18n;return i._tc.apply(i,[t,i.locale,i._getMessages(),this,e].concat(n))},t.prototype.$te=function(t,e){var n=this.$i18n;return n._te(t,n.locale,n._getMessages(),e)},t.prototype.$d=function(t){var e,n=[],r=arguments.length-1;while(r-- >0)n[r]=arguments[r+1];return(e=this.$i18n).d.apply(e,[t].concat(n))},t.prototype.$n=function(t){var e,n=[],r=arguments.length-1;while(r-- >0)n[r]=arguments[r+1];return(e=this.$i18n).n.apply(e,[t].concat(n))}}function Ju(t){function e(){this!==this.$root&&this.$options.__INTLIFY_META__&&this.$el&&this.$el.setAttribute("data-intlify",this.$options.__INTLIFY_META__)}return void 0===t&&(t=!1),t?{mounted:e}:{beforeCreate:function(){var t=this.$options;if(t.i18n=t.i18n||(t.__i18nBridge||t.__i18n?{}:null),t.i18n)if(t.i18n instanceof Kc){if(t.__i18nBridge||t.__i18n)try{var e=t.i18n&&t.i18n.messages?t.i18n.messages:{},n=t.__i18nBridge||t.__i18n;n.forEach((function(t){e=qu(e,JSON.parse(t))})),Object.keys(e).forEach((function(n){t.i18n.mergeLocaleMessage(n,e[n])}))}catch(el){0}this._i18n=t.i18n,this._i18nWatcher=this._i18n.watchI18nData()}else if(Lu(t.i18n)){var r=this.$root&&this.$root.$i18n&&this.$root.$i18n instanceof Kc?this.$root.$i18n:null;if(r&&(t.i18n.root=this.$root,t.i18n.formatter=r.formatter,t.i18n.fallbackLocale=r.fallbackLocale,t.i18n.formatFallbackMessages=r.formatFallbackMessages,t.i18n.silentTranslationWarn=r.silentTranslationWarn,t.i18n.silentFallbackWarn=r.silentFallbackWarn,t.i18n.pluralizationRules=r.pluralizationRules,t.i18n.preserveDirectiveContent=r.preserveDirectiveContent),t.__i18nBridge||t.__i18n)try{var i=t.i18n&&t.i18n.messages?t.i18n.messages:{},o=t.__i18nBridge||t.__i18n;o.forEach((function(t){i=qu(i,JSON.parse(t))})),t.i18n.messages=i}catch(el){0}var a=t.i18n,s=a.sharedMessages;s&&Lu(s)&&(t.i18n.messages=qu(t.i18n.messages,s)),this._i18n=new Kc(t.i18n),this._i18nWatcher=this._i18n.watchI18nData(),(void 0===t.i18n.sync||t.i18n.sync)&&(this._localeWatcher=this.$i18n.watchLocale()),r&&r.onComponentInstanceCreated(this._i18n)}else 0;else this.$root&&this.$root.$i18n&&this.$root.$i18n instanceof Kc?this._i18n=this.$root.$i18n:t.parent&&t.parent.$i18n&&t.parent.$i18n instanceof Kc&&(this._i18n=t.parent.$i18n)},beforeMount:function(){var t=this.$options;t.i18n=t.i18n||(t.__i18nBridge||t.__i18n?{}:null),t.i18n?(t.i18n instanceof Kc||Lu(t.i18n))&&(this._i18n.subscribeDataChanging(this),this._subscribing=!0):(this.$root&&this.$root.$i18n&&this.$root.$i18n instanceof Kc||t.parent&&t.parent.$i18n&&t.parent.$i18n instanceof Kc)&&(this._i18n.subscribeDataChanging(this),this._subscribing=!0)},mounted:e,beforeDestroy:function(){if(this._i18n){var t=this;this.$nextTick((function(){t._subscribing&&(t._i18n.unsubscribeDataChanging(t),delete t._subscribing),t._i18nWatcher&&(t._i18nWatcher(),t._i18n.destroyVM(),delete t._i18nWatcher),t._localeWatcher&&(t._localeWatcher(),delete t._localeWatcher)}))}}}}var Zu={name:"i18n",functional:!0,props:{tag:{type:[String,Boolean,Object],default:"span"},path:{type:String,required:!0},locale:{type:String},places:{type:[Array,Object]}},render:function(t,e){var n=e.data,r=e.parent,i=e.props,o=e.slots,a=r.$i18n;if(a){var s=i.path,u=i.locale,c=i.places,l=o(),f=a.i(s,u,Qu(l)||c?tc(l.default,c):l),h=i.tag&&!0!==i.tag||!1===i.tag?i.tag:"span";return h?t(h,n,f):f}}};function Qu(t){var e;for(e in t)if("default"!==e)return!1;return Boolean(e)}function tc(t,e){var n=e?ec(e):{};if(!t)return n;t=t.filter((function(t){return t.tag||""!==t.text.trim()}));var r=t.every(ic);return t.reduce(r?nc:rc,n)}function ec(t){return Array.isArray(t)?t.reduce(rc,{}):Object.assign({},t)}function nc(t,e){return e.data&&e.data.attrs&&e.data.attrs.place&&(t[e.data.attrs.place]=e),t}function rc(t,e,n){return t[n]=e,t}function ic(t){return Boolean(t.data&&t.data.attrs&&t.data.attrs.place)}var oc,ac={name:"i18n-n",functional:!0,props:{tag:{type:[String,Boolean,Object],default:"span"},value:{type:Number,required:!0},format:{type:[String,Object]},locale:{type:String}},render:function(t,e){var n=e.props,r=e.parent,i=e.data,o=r.$i18n;if(!o)return null;var a=null,s=null;Ru(n.format)?a=n.format:ju(n.format)&&(n.format.key&&(a=n.format.key),s=Object.keys(n.format).reduce((function(t,e){var r;return zu(Pu,e)?Object.assign({},t,(r={},r[e]=n.format[e],r)):t}),null));var u=n.locale||o.locale,c=o._ntp(n.value,u,a,s),l=c.map((function(t,e){var n,r=i.scopedSlots&&i.scopedSlots[t.type];return r?r((n={},n[t.type]=t.value,n.index=e,n.parts=c,n)):t.value})),f=n.tag&&!0!==n.tag||!1===n.tag?n.tag:"span";return f?t(f,{attrs:i.attrs,class:i["class"],staticClass:i.staticClass},l):l}};function sc(t,e,n){lc(t,n)&&hc(t,e,n)}function uc(t,e,n,r){if(lc(t,n)){var i=n.context.$i18n;fc(t,n)&&Hu(e.value,e.oldValue)&&Hu(t._localeMessage,i.getLocaleMessage(i.locale))||hc(t,e,n)}}function cc(t,e,n,r){var i=n.context;if(i){var o=n.context.$i18n||{};e.modifiers.preserve||o.preserveDirectiveContent||(t.textContent=""),t._vt=void 0,delete t["_vt"],t._locale=void 0,delete t["_locale"],t._localeMessage=void 0,delete t["_localeMessage"]}else Tu("Vue instance does not exists in VNode context")}function lc(t,e){var n=e.context;return n?!!n.$i18n||(Tu("VueI18n instance does not exists in Vue instance"),!1):(Tu("Vue instance does not exists in VNode context"),!1)}function fc(t,e){var n=e.context;return t._locale===n.$i18n.locale}function hc(t,e,n){var r,i,o=e.value,a=dc(o),s=a.path,u=a.locale,c=a.args,l=a.choice;if(s||u||c)if(s){var f=n.context;t._vt=t.textContent=null!=l?(r=f.$i18n).tc.apply(r,[s,l].concat(pc(u,c))):(i=f.$i18n).t.apply(i,[s].concat(pc(u,c))),t._locale=f.$i18n.locale,t._localeMessage=f.$i18n.getLocaleMessage(f.$i18n.locale)}else Tu("`path` is required in v-t directive");else Tu("value type not supported")}function dc(t){var e,n,r,i;return Ru(t)?e=t:Lu(t)&&(e=t.path,n=t.locale,r=t.args,i=t.choice),{path:e,locale:n,args:r,choice:i}}function pc(t,e){var n=[];return t&&n.push(t),e&&(Array.isArray(e)||Lu(e))&&n.push(e),n}function vc(t,e){void 0===e&&(e={bridge:!1}),vc.installed=!0,oc=t;oc.version&&Number(oc.version.split(".")[0]);Xu(oc),oc.mixin(Ju(e.bridge)),oc.directive("t",{bind:sc,update:uc,unbind:cc}),oc.component(Zu.name,Zu),oc.component(ac.name,ac);var n=oc.config.optionMergeStrategies;n.i18n=function(t,e){return void 0===e?t:e}}var gc=function(){this._caches=Object.create(null)};gc.prototype.interpolate=function(t,e){if(!e)return[t];var n=this._caches[t];return n||(n=bc(t),this._caches[t]=n),_c(n,e)};var mc=/^(?:\d)+/,yc=/^(?:\w)+/;function bc(t){var e=[],n=0,r="";while(n0)f--,l=Ac,h[wc]();else{if(f=0,void 0===n)return!1;if(n=Fc(n),!1===n)return!1;h[xc]()}};while(null!==l)if(c++,e=t[c],"\\"!==e||!d()){if(i=Nc(e),s=Dc[l],o=s[i]||s["else"]||Rc,o===Rc)return;if(l=o[0],a=h[o[1]],a&&(r=o[2],r=void 0===r?e:r,!1===a()))return;if(l===Mc)return u}}var Bc=function(){this._cache=Object.create(null)};Bc.prototype.parsePath=function(t){var e=this._cache[t];return e||(e=Uc(t),e&&(this._cache[t]=e)),e||[]},Bc.prototype.getPathValue=function(t,e){if(!ju(t))return null;var n=this.parsePath(e);if(0===n.length)return null;var r=n.length,i=t,o=0;while(o/,Vc=/(?:@(?:\.[a-zA-Z]+)?:(?:[\w\-_|./]+|\([\w\-_:|./]+\)))/g,Wc=/^@(?:\.([a-zA-Z]+))?:/,qc=/[()]/g,Hc={upper:function(t){return t.toLocaleUpperCase()},lower:function(t){return t.toLocaleLowerCase()},capitalize:function(t){return""+t.charAt(0).toLocaleUpperCase()+t.substr(1)}},Yc=new gc,Kc=function(t){var e=this;void 0===t&&(t={}),!oc&&"undefined"!==typeof window&&window.Vue&&vc(window.Vue);var n=t.locale||"en-US",r=!1!==t.fallbackLocale&&(t.fallbackLocale||"en-US"),i=t.messages||{},o=t.dateTimeFormats||t.datetimeFormats||{},a=t.numberFormats||{};this._vm=null,this._formatter=t.formatter||Yc,this._modifiers=t.modifiers||{},this._missing=t.missing||null,this._root=t.root||null,this._sync=void 0===t.sync||!!t.sync,this._fallbackRoot=void 0===t.fallbackRoot||!!t.fallbackRoot,this._fallbackRootWithEmptyString=void 0===t.fallbackRootWithEmptyString||!!t.fallbackRootWithEmptyString,this._formatFallbackMessages=void 0!==t.formatFallbackMessages&&!!t.formatFallbackMessages,this._silentTranslationWarn=void 0!==t.silentTranslationWarn&&t.silentTranslationWarn,this._silentFallbackWarn=void 0!==t.silentFallbackWarn&&!!t.silentFallbackWarn,this._dateTimeFormatters={},this._numberFormatters={},this._path=new Bc,this._dataListeners=new Set,this._componentInstanceCreatedListener=t.componentInstanceCreatedListener||null,this._preserveDirectiveContent=void 0!==t.preserveDirectiveContent&&!!t.preserveDirectiveContent,this.pluralizationRules=t.pluralizationRules||{},this._warnHtmlInMessage=t.warnHtmlInMessage||"off",this._postTranslation=t.postTranslation||null,this._escapeParameterHtml=t.escapeParameterHtml||!1,"__VUE_I18N_BRIDGE__"in t&&(this.__VUE_I18N_BRIDGE__=t.__VUE_I18N_BRIDGE__),this.getChoiceIndex=function(t,n){var r=Object.getPrototypeOf(e);if(r&&r.getChoiceIndex){var i=r.getChoiceIndex;return i.call(e,t,n)}var o=function(t,e){return t=Math.abs(t),2===e?t?t>1?1:0:1:t?Math.min(t,2):0};return e.locale in e.pluralizationRules?e.pluralizationRules[e.locale].apply(e,[t,n]):o(t,n)},this._exist=function(t,n){return!(!t||!n)&&(!$u(e._path.getPathValue(t,n))||!!t[n])},"warn"!==this._warnHtmlInMessage&&"error"!==this._warnHtmlInMessage||Object.keys(i).forEach((function(t){e._checkLocaleMessage(t,e._warnHtmlInMessage,i[t])})),this._initVM({locale:n,fallbackLocale:r,messages:i,dateTimeFormats:o,numberFormats:a})},Xc={vm:{configurable:!0},messages:{configurable:!0},dateTimeFormats:{configurable:!0},numberFormats:{configurable:!0},availableLocales:{configurable:!0},locale:{configurable:!0},fallbackLocale:{configurable:!0},formatFallbackMessages:{configurable:!0},missing:{configurable:!0},formatter:{configurable:!0},silentTranslationWarn:{configurable:!0},silentFallbackWarn:{configurable:!0},preserveDirectiveContent:{configurable:!0},warnHtmlInMessage:{configurable:!0},postTranslation:{configurable:!0},sync:{configurable:!0}};Kc.prototype._checkLocaleMessage=function(t,e,n){var r=[],i=function(t,e,n,r){if(Lu(n))Object.keys(n).forEach((function(o){var a=n[o];Lu(a)?(r.push(o),r.push("."),i(t,e,a,r),r.pop(),r.pop()):(r.push(o),i(t,e,a,r),r.pop())}));else if(Eu(n))n.forEach((function(n,o){Lu(n)?(r.push("["+o+"]"),r.push("."),i(t,e,n,r),r.pop(),r.pop()):(r.push("["+o+"]"),i(t,e,n,r),r.pop())}));else if(Ru(n)){var o=zc.test(n);if(o){var a="Detected HTML in message '"+n+"' of keypath '"+r.join("")+"' at '"+e+"'. Consider component interpolation with '' to avoid XSS. See https://bit.ly/2ZqJzkp";"warn"===t?Tu(a):"error"===t&&Au(a)}}};i(e,t,n,r)},Kc.prototype._initVM=function(t){var e=oc.config.silent;oc.config.silent=!0,this._vm=new oc({data:t,__VUE18N__INSTANCE__:!0}),oc.config.silent=e},Kc.prototype.destroyVM=function(){this._vm.$destroy()},Kc.prototype.subscribeDataChanging=function(t){this._dataListeners.add(t)},Kc.prototype.unsubscribeDataChanging=function(t){Bu(this._dataListeners,t)},Kc.prototype.watchI18nData=function(){var t=this;return this._vm.$watch("$data",(function(){var e=Gu(t._dataListeners),n=e.length;while(n--)oc.nextTick((function(){e[n]&&e[n].$forceUpdate()}))}),{deep:!0})},Kc.prototype.watchLocale=function(t){if(t){if(!this.__VUE_I18N_BRIDGE__)return null;var e=this,n=this._vm;return this.vm.$watch("locale",(function(r){n.$set(n,"locale",r),e.__VUE_I18N_BRIDGE__&&t&&(t.locale.value=r),n.$forceUpdate()}),{immediate:!0})}if(!this._sync||!this._root)return null;var r=this._vm;return this._root.$i18n.vm.$watch("locale",(function(t){r.$set(r,"locale",t),r.$forceUpdate()}),{immediate:!0})},Kc.prototype.onComponentInstanceCreated=function(t){this._componentInstanceCreatedListener&&this._componentInstanceCreatedListener(t,this)},Xc.vm.get=function(){return this._vm},Xc.messages.get=function(){return Uu(this._getMessages())},Xc.dateTimeFormats.get=function(){return Uu(this._getDateTimeFormats())},Xc.numberFormats.get=function(){return Uu(this._getNumberFormats())},Xc.availableLocales.get=function(){return Object.keys(this.messages).sort()},Xc.locale.get=function(){return this._vm.locale},Xc.locale.set=function(t){this._vm.$set(this._vm,"locale",t)},Xc.fallbackLocale.get=function(){return this._vm.fallbackLocale},Xc.fallbackLocale.set=function(t){this._localeChainCache={},this._vm.$set(this._vm,"fallbackLocale",t)},Xc.formatFallbackMessages.get=function(){return this._formatFallbackMessages},Xc.formatFallbackMessages.set=function(t){this._formatFallbackMessages=t},Xc.missing.get=function(){return this._missing},Xc.missing.set=function(t){this._missing=t},Xc.formatter.get=function(){return this._formatter},Xc.formatter.set=function(t){this._formatter=t},Xc.silentTranslationWarn.get=function(){return this._silentTranslationWarn},Xc.silentTranslationWarn.set=function(t){this._silentTranslationWarn=t},Xc.silentFallbackWarn.get=function(){return this._silentFallbackWarn},Xc.silentFallbackWarn.set=function(t){this._silentFallbackWarn=t},Xc.preserveDirectiveContent.get=function(){return this._preserveDirectiveContent},Xc.preserveDirectiveContent.set=function(t){this._preserveDirectiveContent=t},Xc.warnHtmlInMessage.get=function(){return this._warnHtmlInMessage},Xc.warnHtmlInMessage.set=function(t){var e=this,n=this._warnHtmlInMessage;if(this._warnHtmlInMessage=t,n!==t&&("warn"===t||"error"===t)){var r=this._getMessages();Object.keys(r).forEach((function(t){e._checkLocaleMessage(t,e._warnHtmlInMessage,r[t])}))}},Xc.postTranslation.get=function(){return this._postTranslation},Xc.postTranslation.set=function(t){this._postTranslation=t},Xc.sync.get=function(){return this._sync},Xc.sync.set=function(t){this._sync=t},Kc.prototype._getMessages=function(){return this._vm.messages},Kc.prototype._getDateTimeFormats=function(){return this._vm.dateTimeFormats},Kc.prototype._getNumberFormats=function(){return this._vm.numberFormats},Kc.prototype._warnDefault=function(t,e,n,r,i,o){if(!$u(n))return n;if(this._missing){var a=this._missing.apply(null,[t,e,r,i]);if(Ru(a))return a}else 0;if(this._formatFallbackMessages){var s=Fu.apply(void 0,i);return this._render(e,o,s.params,e)}return e},Kc.prototype._isFallbackRoot=function(t){return(this._fallbackRootWithEmptyString?!t:$u(t))&&!$u(this._root)&&this._fallbackRoot},Kc.prototype._isSilentFallbackWarn=function(t){return this._silentFallbackWarn instanceof RegExp?this._silentFallbackWarn.test(t):this._silentFallbackWarn},Kc.prototype._isSilentFallback=function(t,e){return this._isSilentFallbackWarn(e)&&(this._isFallbackRoot()||t!==this.fallbackLocale)},Kc.prototype._isSilentTranslationWarn=function(t){return this._silentTranslationWarn instanceof RegExp?this._silentTranslationWarn.test(t):this._silentTranslationWarn},Kc.prototype._interpolate=function(t,e,n,r,i,o,a){if(!e)return null;var s,u=this._path.getPathValue(e,n);if(Eu(u)||Lu(u))return u;if($u(u)){if(!Lu(e))return null;if(s=e[n],!Ru(s)&&!Nu(s))return null}else{if(!Ru(u)&&!Nu(u))return null;s=u}return Ru(s)&&(s.indexOf("@:")>=0||s.indexOf("@.")>=0)&&(s=this._link(t,e,s,r,"raw",o,a)),this._render(s,i,o,n)},Kc.prototype._link=function(t,e,n,r,i,o,a){var s=n,u=s.match(Vc);for(var c in u)if(u.hasOwnProperty(c)){var l=u[c],f=l.match(Wc),h=f[0],d=f[1],p=l.replace(h,"").replace(qc,"");if(zu(a,p))return s;a.push(p);var v=this._interpolate(t,e,p,r,"raw"===i?"string":i,"raw"===i?void 0:o,a);if(this._isFallbackRoot(v)){if(!this._root)throw Error("unexpected error");var g=this._root.$i18n;v=g._translate(g._getMessages(),g.locale,g.fallbackLocale,p,r,i,o)}v=this._warnDefault(t,p,v,r,Eu(o)?o:[o],i),this._modifiers.hasOwnProperty(d)?v=this._modifiers[d](v):Hc.hasOwnProperty(d)&&(v=Hc[d](v)),a.pop(),s=v?s.replace(l,v):s}return s},Kc.prototype._createMessageContext=function(t,e,n,r){var i=this,o=Eu(t)?t:[],a=ju(t)?t:{},s=function(t){return o[t]},u=function(t){return a[t]},c=this._getMessages(),l=this.locale;return{list:s,named:u,values:t,formatter:e,path:n,messages:c,locale:l,linked:function(t){return i._interpolate(l,c[l]||{},t,null,r,void 0,[t])}}},Kc.prototype._render=function(t,e,n,r){if(Nu(t))return t(this._createMessageContext(n,this._formatter||Yc,r,e));var i=this._formatter.interpolate(t,n,r);return i||(i=Yc.interpolate(t,n,r)),"string"!==e||Ru(i)?i:i.join("")},Kc.prototype._appendItemToChain=function(t,e,n){var r=!1;return zu(t,e)||(r=!0,e&&(r="!"!==e[e.length-1],e=e.replace(/!/g,""),t.push(e),n&&n[e]&&(r=n[e]))),r},Kc.prototype._appendLocaleToChain=function(t,e,n){var r,i=e.split("-");do{var o=i.join("-");r=this._appendItemToChain(t,o,n),i.splice(-1,1)}while(i.length&&!0===r);return r},Kc.prototype._appendBlockToChain=function(t,e,n){for(var r=!0,i=0;i0)o[a]=arguments[a+4];if(!t)return"";var s=Fu.apply(void 0,o);this._escapeParameterHtml&&(s.params=Ku(s.params));var u=s.locale||e,c=this._translate(n,u,this.fallbackLocale,t,r,"string",s.params);if(this._isFallbackRoot(c)){if(!this._root)throw Error("unexpected error");return(i=this._root).$t.apply(i,[t].concat(o))}return c=this._warnDefault(u,t,c,r,o,"string"),this._postTranslation&&null!==c&&void 0!==c&&(c=this._postTranslation(c,t)),c},Kc.prototype.t=function(t){var e,n=[],r=arguments.length-1;while(r-- >0)n[r]=arguments[r+1];return(e=this)._t.apply(e,[t,this.locale,this._getMessages(),null].concat(n))},Kc.prototype._i=function(t,e,n,r,i){var o=this._translate(n,e,this.fallbackLocale,t,r,"raw",i);if(this._isFallbackRoot(o)){if(!this._root)throw Error("unexpected error");return this._root.$i18n.i(t,e,i)}return this._warnDefault(e,t,o,r,[i],"raw")},Kc.prototype.i=function(t,e,n){return t?(Ru(e)||(e=this.locale),this._i(t,e,this._getMessages(),null,n)):""},Kc.prototype._tc=function(t,e,n,r,i){var o,a=[],s=arguments.length-5;while(s-- >0)a[s]=arguments[s+5];if(!t)return"";void 0===i&&(i=1);var u={count:i,n:i},c=Fu.apply(void 0,a);return c.params=Object.assign(u,c.params),a=null===c.locale?[c.params]:[c.locale,c.params],this.fetchChoice((o=this)._t.apply(o,[t,e,n,r].concat(a)),i)},Kc.prototype.fetchChoice=function(t,e){if(!t||!Ru(t))return null;var n=t.split("|");return e=this.getChoiceIndex(e,n.length),n[e]?n[e].trim():t},Kc.prototype.tc=function(t,e){var n,r=[],i=arguments.length-2;while(i-- >0)r[i]=arguments[i+2];return(n=this)._tc.apply(n,[t,this.locale,this._getMessages(),null,e].concat(r))},Kc.prototype._te=function(t,e,n){var r=[],i=arguments.length-3;while(i-- >0)r[i]=arguments[i+3];var o=Fu.apply(void 0,r).locale||e;return this._exist(n[o],t)},Kc.prototype.te=function(t,e){return this._te(t,this.locale,this._getMessages(),e)},Kc.prototype.getLocaleMessage=function(t){return Uu(this._vm.messages[t]||{})},Kc.prototype.setLocaleMessage=function(t,e){"warn"!==this._warnHtmlInMessage&&"error"!==this._warnHtmlInMessage||this._checkLocaleMessage(t,this._warnHtmlInMessage,e),this._vm.$set(this._vm.messages,t,e)},Kc.prototype.mergeLocaleMessage=function(t,e){"warn"!==this._warnHtmlInMessage&&"error"!==this._warnHtmlInMessage||this._checkLocaleMessage(t,this._warnHtmlInMessage,e),this._vm.$set(this._vm.messages,t,qu("undefined"!==typeof this._vm.messages[t]&&Object.keys(this._vm.messages[t]).length?Object.assign({},this._vm.messages[t]):{},e))},Kc.prototype.getDateTimeFormat=function(t){return Uu(this._vm.dateTimeFormats[t]||{})},Kc.prototype.setDateTimeFormat=function(t,e){this._vm.$set(this._vm.dateTimeFormats,t,e),this._clearDateTimeFormat(t,e)},Kc.prototype.mergeDateTimeFormat=function(t,e){this._vm.$set(this._vm.dateTimeFormats,t,qu(this._vm.dateTimeFormats[t]||{},e)),this._clearDateTimeFormat(t,e)},Kc.prototype._clearDateTimeFormat=function(t,e){for(var n in e){var r=t+"__"+n;this._dateTimeFormatters.hasOwnProperty(r)&&delete this._dateTimeFormatters[r]}},Kc.prototype._localizeDateTime=function(t,e,n,r,i){for(var o=e,a=r[o],s=this._getLocaleChain(e,n),u=0;u0)e[n]=arguments[n+1];var r=this.locale,i=null;return 1===e.length?Ru(e[0])?i=e[0]:ju(e[0])&&(e[0].locale&&(r=e[0].locale),e[0].key&&(i=e[0].key)):2===e.length&&(Ru(e[0])&&(i=e[0]),Ru(e[1])&&(r=e[1])),this._d(t,r,i)},Kc.prototype.getNumberFormat=function(t){return Uu(this._vm.numberFormats[t]||{})},Kc.prototype.setNumberFormat=function(t,e){this._vm.$set(this._vm.numberFormats,t,e),this._clearNumberFormat(t,e)},Kc.prototype.mergeNumberFormat=function(t,e){this._vm.$set(this._vm.numberFormats,t,qu(this._vm.numberFormats[t]||{},e)),this._clearNumberFormat(t,e)},Kc.prototype._clearNumberFormat=function(t,e){for(var n in e){var r=t+"__"+n;this._numberFormatters.hasOwnProperty(r)&&delete this._numberFormatters[r]}},Kc.prototype._getNumberFormatter=function(t,e,n,r,i,o){for(var a=e,s=r[a],u=this._getLocaleChain(e,n),c=0;c0)e[n]=arguments[n+1];var r=this.locale,i=null,o=null;return 1===e.length?Ru(e[0])?i=e[0]:ju(e[0])&&(e[0].locale&&(r=e[0].locale),e[0].key&&(i=e[0].key),o=Object.keys(e[0]).reduce((function(t,n){var r;return zu(Pu,n)?Object.assign({},t,(r={},r[n]=e[0][n],r)):t}),null)):2===e.length&&(Ru(e[0])&&(i=e[0]),Ru(e[1])&&(r=e[1])),this._n(t,r,i,o)},Kc.prototype._ntp=function(t,e,n,r){if(!Kc.availabilities.numberFormat)return[];if(!n){var i=r?new Intl.NumberFormat(e,r):new Intl.NumberFormat(e);return i.formatToParts(t)}var o=this._getNumberFormatter(t,e,this.fallbackLocale,this._getNumberFormats(),n,r),a=o&&o.formatToParts(t);if(this._isFallbackRoot(a)){if(!this._root)throw Error("unexpected error");return this._root.$i18n._ntp(t,e,n,r)}return a||[]},Object.defineProperties(Kc.prototype,Xc),Object.defineProperty(Kc,"availabilities",{get:function(){if(!Gc){var t="undefined"!==typeof Intl;Gc={dateTimeFormat:t&&"undefined"!==typeof Intl.DateTimeFormat,numberFormat:t&&"undefined"!==typeof Intl.NumberFormat}}return Gc}}),Kc.install=vc,Kc.version="8.27.2";var Jc=Kc,Zc=n("c2a1"),Qc=n("d266"),tl=function(t,e){Jc.install(t);const n=new Jc({locale:e.language||"en",fallbackLocale:"en",messages:i});t.prototype._i18n=n;const o=Y();t.mixin({components:{...r},data(){return{magpie:null}},computed:{$magpie(){return this.magpie||this.$parent&&this.$parent.$magpie||o},$i18n(){return n}},magpie:e,mounted(){this.$options.socket&&this.$magpie.socket&&this.$magpie.socket.setUpSubscriptions(this.$options.socket,this)},beforeDestroy(){this.$options.socket&&this.$magpie.socket&&this.$magpie.socket.tearDownSubscriptions(this.$options.socket)}})}},3698:function(t,e){function n(t,e){return null==t?void 0:t[e]}t.exports=n},"36da":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Konva=void 0;var r=n("d777"),i=n("9cb8"),o=n("4971"),a=n("ea61"),s=n("eba4"),u=n("0ff5"),c=n("2fb2"),l=n("f35c"),f=n("df93"),h=n("fce6"),d=n("ed3d"),p=n("06f8"),v=n("c527"),g=n("f655");e.Konva=i.Util._assign(r.Konva,{Collection:i.Collection,Util:i.Util,Transform:i.Transform,Node:o.Node,ids:o.ids,names:o.names,Container:a.Container,Stage:s.Stage,stages:s.stages,Layer:u.Layer,FastLayer:c.FastLayer,Group:l.Group,DD:f.DD,Shape:h.Shape,shapes:h.shapes,Animation:d.Animation,Tween:p.Tween,Easings:p.Easings,Context:v.Context,Canvas:g.Canvas})},3729:function(t,e,n){var r=n("9e69"),i=n("00fd"),o=n("29f3"),a="[object Null]",s="[object Undefined]",u=r?r.toStringTag:void 0;function c(t){return null==t?void 0===t?s:a:u&&u in Object(t)?i(t):o(t)}t.exports=c},"383f":function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(e,"__esModule",{value:!0}),e.Ellipse=void 0;var i=n("9cb8"),o=n("f0b4"),a=n("fce6"),s=n("4546"),u=n("d777"),c=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r(e,t),e.prototype._sceneFunc=function(t){var e=this.radiusX(),n=this.radiusY();t.beginPath(),t.save(),e!==n&&t.scale(1,n/e),t.arc(0,0,e,0,2*Math.PI,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)},e.prototype.getWidth=function(){return 2*this.radiusX()},e.prototype.getHeight=function(){return 2*this.radiusY()},e.prototype.setWidth=function(t){this.radiusX(t/2)},e.prototype.setHeight=function(t){this.radiusY(t/2)},e}(a.Shape);e.Ellipse=c,c.prototype.className="Ellipse",c.prototype._centroid=!0,c.prototype._attrsAffectingSize=["radiusX","radiusY"],u._registerNode(c),o.Factory.addComponentsGetterSetter(c,"radius",["x","y"]),o.Factory.addGetterSetter(c,"radiusX",0,s.getNumberValidator()),o.Factory.addGetterSetter(c,"radiusY",0,s.getNumberValidator()),i.Collection.mapMethods(c)},"38e4":function(t,e){},3956:function(t,e,n){var r=n("d460"),i=n("3ff1");function o(t){return r(i(t))}t.exports=o},"39a4":function(t,e){},"39cd":function(t,e){},"39ff":function(t,e,n){var r=n("0b07"),i=n("2b3e"),o=r(i,"WeakMap");t.exports=o},"3a54":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n("78ef"),i=(0,r.regex)("alphaNum",/^[a-zA-Z0-9]*$/);e.default=i},"3a7c":function(t,e,n){function r(t){return Array.isArray?Array.isArray(t):"[object Array]"===m(t)}function i(t){return"boolean"===typeof t}function o(t){return null===t}function a(t){return null==t}function s(t){return"number"===typeof t}function u(t){return"string"===typeof t}function c(t){return"symbol"===typeof t}function l(t){return void 0===t}function f(t){return"[object RegExp]"===m(t)}function h(t){return"object"===typeof t&&null!==t}function d(t){return"[object Date]"===m(t)}function p(t){return"[object Error]"===m(t)||t instanceof Error}function v(t){return"function"===typeof t}function g(t){return null===t||"boolean"===typeof t||"number"===typeof t||"string"===typeof t||"symbol"===typeof t||"undefined"===typeof t}function m(t){return Object.prototype.toString.call(t)}e.isArray=r,e.isBoolean=i,e.isNull=o,e.isNullOrUndefined=a,e.isNumber=s,e.isString=u,e.isSymbol=c,e.isUndefined=l,e.isRegExp=f,e.isObject=h,e.isDate=d,e.isError=p,e.isFunction=v,e.isPrimitive=g,e.isBuffer=n("b639").Buffer.isBuffer},"3b4a":function(t,e,n){var r=n("0b07"),i=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();t.exports=i},"3bb4":function(t,e,n){var r=n("08cc"),i=n("ec69");function o(t){var e=i(t),n=e.length;while(n--){var o=e[n],a=t[o];e[n]=[o,a,r(a)]}return e}t.exports=o},"3d7b":function(t,e){},"3fb5":function(t,e){"function"===typeof Object.create?t.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(t,e){if(e){t.super_=e;var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}}},"3ff1":function(t,e,n){var r=n("266a"),i=n("ec69");function o(t){return null==t?[]:r(t,i(t))}t.exports=o},"402d":function(t,e,n){"use strict";n("dc6a")},"405a":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Pixelate=void 0;var r=n("f0b4"),i=n("9cb8"),o=n("4971"),a=n("4546"),s=function(t){var e,n,r,o,a,s,u,c,l,f,h,d,p,v,g=Math.ceil(this.pixelSize()),m=t.width,y=t.height,b=Math.ceil(m/g),_=Math.ceil(y/g),w=t.data;if(g<=0)i.Util.error("pixelSize value can not be <= 0");else for(d=0;d=m))for(n=f;n=y||(r=4*(m*n+e),o+=w[r+0],a+=w[r+1],s+=w[r+2],u+=w[r+3],v+=1);for(o/=v,a/=v,s/=v,u/=v,e=c;e=m))for(n=f;n=y||(r=4*(m*n+e),w[r+0]=o,w[r+1]=a,w[r+2]=s,w[r+3]=u)}};e.Pixelate=s,r.Factory.addGetterSetter(o.Node,"pixelSize",8,a.getNumberValidator(),r.Factory.afterSetFilter)},4092:function(t,e,n){},4143:function(t,e,n){},"41c3":function(t,e,n){var r=n("1a8c"),i=n("eac5"),o=n("ec8c"),a=Object.prototype,s=a.hasOwnProperty;function u(t){if(!r(t))return o(t);var e=i(t),n=[];for(var a in t)("constructor"!=a||!e&&s.call(t,a))&&n.push(a);return n}t.exports=u},4245:function(t,e,n){var r=n("1290");function i(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map}t.exports=i},42454:function(t,e,n){var r=n("f909"),i=n("2ec1"),o=i((function(t,e,n){r(t,e,n)}));t.exports=o},4284:function(t,e){function n(t,e){var n=-1,r=null==t?0:t.length;while(++n255?255:t<0?0:Math.round(t)}function s(t){return t>1?1:t<1e-4?1e-4:t}function u(){if(r.Konva.isUnminified)return function(t,e){return i.Util._isNumber(t)||i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),t}}function c(t){if(r.Konva.isUnminified)return function(e,n){var r=i.Util._isNumber(e),a=i.Util._isArray(e)&&e.length==t;return r||a||i.Util.warn(o(e)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+t+")"),e}}function l(){if(r.Konva.isUnminified)return function(t,e){var n=i.Util._isNumber(t),r="auto"===t;return n||r||i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),t}}function f(){if(r.Konva.isUnminified)return function(t,e){return i.Util._isString(t)||i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),t}}function h(){if(r.Konva.isUnminified)return function(t,e){var n=i.Util._isString(t),r="[object CanvasGradient]"===Object.prototype.toString.call(t);return n||r||i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),t}}function d(){if(r.Konva.isUnminified)return function(t,e){return i.Util._isFunction(t)||i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a function.'),t}}function p(){if(r.Konva.isUnminified)return function(t,e){return i.Util._isArray(t)?t.forEach((function(t){i.Util._isNumber(t)||i.Util.warn('"'+e+'" attribute has non numeric element '+t+". Make sure that all elements are numbers.")})):i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.'),t}}function v(){if(r.Konva.isUnminified)return function(t,e){var n=!0===t||!1===t;return n||i.Util.warn(o(t)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),t}}function g(t){if(r.Konva.isUnminified)return function(e,n){return i.Util.isObject(e)||i.Util.warn(o(e)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+t),e}}e.RGBComponent=a,e.alphaComponent=s,e.getNumberValidator=u,e.getNumberOrArrayOfNumbersValidator=c,e.getNumberOrAutoValidator=l,e.getStringValidator=f,e.getStringOrGradientValidator=h,e.getFunctionValidator=d,e.getNumberArrayValidator=p,e.getBooleanValidator=v,e.getComponentValidator=g},"45b8":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n("78ef"),i=(0,r.regex)("numeric",/^[0-9]*$/);e.default=i},"461e":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.HSV=void 0;var r=n("f0b4"),i=n("4971"),o=n("4546"),a=function(t){var e,n,r,i,o,a=t.data,s=a.length,u=Math.pow(2,this.value()),c=Math.pow(2,this.saturation()),l=Math.abs(this.hue()+360)%360,f=u*c*Math.cos(l*Math.PI/180),h=u*c*Math.sin(l*Math.PI/180),d=.299*u+.701*f+.167*h,p=.587*u-.587*f+.33*h,v=.114*u-.114*f-.497*h,g=.299*u-.299*f-.328*h,m=.587*u+.413*f+.035*h,y=.114*u-.114*f+.293*h,b=.299*u-.3*f+1.25*h,_=.587*u-.586*f-1.05*h,w=.114*u+.886*f-.2*h;for(e=0;e0&&t[0].getDepth()<=i&&s(t)}return o.nodeType!==E&&s(o.getStage().getChildren()),a},t.prototype.getDepth=function(){var t=0,e=this.parent;while(e)t++,e=e.parent;return t},t.prototype._batchTransformChanges=function(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(A),this._clearSelfAndDescendantCache(v,!0)),this._needClearTransformCache=!1},t.prototype.setPosition=function(t){var e=this;return this._batchTransformChanges((function(){e.x(t.x),e.y(t.y)})),this},t.prototype.getPosition=function(){return{x:this.x(),y:this.y()}},t.prototype.getAbsolutePosition=function(t){var e=!1,n=this.parent;while(n){if(n.isCached()){e=!0;break}n=n.parent}e&&!t&&(t=!0);var i=this.getAbsoluteTransform(t).getMatrix(),o=new r.Transform,a=this.offset();return o.m=i.slice(),o.translate(a.x,a.y),o.getTranslation()},t.prototype.setAbsolutePosition=function(t){var e=this._clearTransform();this.attrs.x=e.x,this.attrs.y=e.y,delete e.x,delete e.y,this._clearCache(A);var n=this._getAbsoluteTransform().copy();return n.invert(),n.translate(t.x,t.y),t={x:this.attrs.x+n.getTranslation().x,y:this.attrs.y+n.getTranslation().y},this._setTransform(e),this.setPosition({x:t.x,y:t.y}),this._clearCache(A),this._clearSelfAndDescendantCache(v),this},t.prototype._setTransform=function(t){var e;for(e in t)this.attrs[e]=t[e]},t.prototype._clearTransform=function(){var t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t},t.prototype.move=function(t){var e=t.x,n=t.y,r=this.x(),i=this.y();return void 0!==e&&(r+=e),void 0!==n&&(i+=n),this.setPosition({x:r,y:i}),this},t.prototype._eachAncestorReverse=function(t,e){var n,r,i=[],o=this.getParent();if(!e||e._id!==this._id){i.unshift(this);while(o&&(!e||o._id!==e._id))i.unshift(o),o=o.parent;for(n=i.length,r=0;r0&&(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0)},t.prototype.moveToBottom=function(){if(!this.parent)return r.Util.warn("Node has no parent. moveToBottom function is ignored."),!1;var t=this.index;return t>0&&(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0)},t.prototype.setZIndex=function(t){if(!this.parent)return r.Util.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&r.Util.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this},t.prototype.getAbsoluteOpacity=function(){return this._getCache(d,this._getAbsoluteOpacity)},t.prototype._getAbsoluteOpacity=function(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=e.getAbsoluteOpacity()),t},t.prototype.moveTo=function(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this},t.prototype.toObject=function(){var t,e,n,i,o,a={},s=this.getAttrs();for(t in a.attrs={},s)e=s[t],o=r.Util.isObject(e)&&!r.Util._isPlainObject(e)&&!r.Util._isArray(e),o||(n="function"===typeof this[t]&&this[t],delete s[t],i=n?n.call(this):null,s[t]=e,i!==e&&(a.attrs[t]=e));return a.className=this.getClassName(),r.Util._prepareToStringify(a)},t.prototype.toJSON=function(){return JSON.stringify(this.toObject())},t.prototype.getParent=function(){return this.parent},t.prototype.findAncestors=function(t,e,n){var r=[];e&&this._isMatch(t)&&r.push(this);var i=this.parent;while(i){if(i===n)return r;i._isMatch(t)&&r.push(i),i=i.parent}return r},t.prototype.isAncestorOf=function(t){return!1},t.prototype.findAncestor=function(t,e,n){return this.findAncestors(t,e,n)[0]},t.prototype._isMatch=function(t){if(!t)return!1;if("function"===typeof t)return t(this);var e,n,i=t.replace(/ /g,"").split(","),o=i.length;for(e=0;e=0;if(r&&!this.isDragging()){var i=!1;s.DD._dragElements.forEach((function(t){e.isAncestorOf(t.node)&&(i=!0)})),i||this._createDragElement(t)}}))},t.prototype._dragChange=function(){if(this.attrs.draggable)this._listenDrag();else{this._dragCleanup();var t=this.getStage();if(!t)return;var e=s.DD._dragElements.get(this._id),n=e&&"dragging"===e.dragStatus,r=e&&"ready"===e.dragStatus;n?this.stopDrag():r&&s.DD._dragElements.delete(this._id)}},t.prototype._dragCleanup=function(){this.off("mousedown.konva"),this.off("touchstart.konva")},t.create=function(t,e){return r.Util._isString(t)&&(t=JSON.parse(t)),this._createNode(t,e)},t._createNode=function(e,n){var i,o,s,u=t.prototype.getClassName.call(e),c=e.children;n&&(e.attrs.container=n),a._NODES_REGISTRY[u]||(r.Util.warn('Can not find a node with class name "'+u+'". Fallback to "Shape".'),u="Shape");var l=a._NODES_REGISTRY[u];if(i=new l(e.attrs),c)for(o=c.length,s=0;sn.parts.length&&(r.parts.length=n.parts.length)}else{var a=[];for(i=0;i-1)e[t]=n[t];else{var r=Object.getOwnPropertyDescriptor(n,t);void 0!==r.value?"function"===typeof r.value?(e.methods||(e.methods={}))[t]=r.value:(e.mixins||(e.mixins=[])).push({data:function(){var e;return e={},e[t]=r.value,e}}):(r.get||r.set)&&((e.computed||(e.computed={}))[t]={get:r.get,set:r.set})}})),(e.mixins||(e.mixins=[])).push({data:function(){return d(this,t)}});var r=t.__decorators__;r&&(r.forEach((function(t){return t(e)})),delete t.__decorators__);var s=Object.getPrototypeOf(t.prototype),u=s instanceof i?s.constructor:i,c=u.extend(e);return g(c,t,u),o&&a(c,t),c}function g(t,e,n){Object.getOwnPropertyNames(e).forEach((function(r){if("prototype"!==r){var i=Object.getOwnPropertyDescriptor(t,r);if(!i||i.configurable){var o=Object.getOwnPropertyDescriptor(e,r);if(!c){if("cid"===r)return;var a=Object.getOwnPropertyDescriptor(n,r);if(!h(o.value)&&a&&a.value===o.value)return}Object.defineProperty(t,r,o)}}}))}function m(t){return"function"===typeof t?v(t):function(e){return v(e,t)}}m.registerHooks=function(t){p.push.apply(p,t)},e.default=m,e.createDecorator=l,e.mixins=f},"7a57":function(t,e,n){var r=n("24fb");e=r(!1),e.push([t.i,".vue-slider{position:relative;-webkit-box-sizing:content-box;box-sizing:content-box;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:block;-webkit-tap-highlight-color:rgba(0,0,0,0)}.vue-slider-rail{position:relative;width:100%;height:100%;-webkit-transition-property:width,height,left,right,top,bottom;transition-property:width,height,left,right,top,bottom}.vue-slider-process{position:absolute;z-index:1}",""]),t.exports=e},8875:function(t,e,n){var r,i,o;(function(n,a){i=[],r=a,o="function"===typeof r?r.apply(e,i):r,void 0===o||(t.exports=o)})("undefined"!==typeof self&&self,(function(){function t(){var e=Object.getOwnPropertyDescriptor(document,"currentScript");if(!e&&"currentScript"in document&&document.currentScript)return document.currentScript;if(e&&e.get!==t&&document.currentScript)return document.currentScript;try{throw new Error}catch(d){var n,r,i,o=/.*at [^(]*\((.*):(.+):(.+)\)$/gi,a=/@([^@]*):(\d+):(\d+)\s*$/gi,s=o.exec(d.stack)||a.exec(d.stack),u=s&&s[1]||!1,c=s&&s[2]||!1,l=document.location.href.replace(document.location.hash,""),f=document.getElementsByTagName("script");u===l&&(n=document.documentElement.outerHTML,r=new RegExp("(?:[^\\n]+?\\n){0,"+(c-2)+"}[^<]*\n\n\n","import mod from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./Experiment.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./Experiment.vue?vue&type=script&lang=js&\"","var render, staticRenderFns\nimport script from \"./Screen.vue?vue&type=script&lang=js&\"\nexport * from \"./Screen.vue?vue&type=script&lang=js&\"\nimport style0 from \"./Screen.vue?vue&type=style&index=0&id=2db71145&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"2db71145\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./Screen.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"debug-statement\"},[_c('h2',[_vm._v(\"magpie \"+_vm._s(_vm.type))]),_vm._v(\" \"+_vm._s(_vm.text)+\" \")])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n\n\n\n","import mod from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./DebugStatement.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./DebugStatement.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./DebugStatement.vue?vue&type=template&id=5a63c536&scoped=true&\"\nimport script from \"./DebugStatement.vue?vue&type=script&lang=js&\"\nexport * from \"./DebugStatement.vue?vue&type=script&lang=js&\"\nimport style0 from \"./DebugStatement.vue?vue&type=style&index=0&id=5a63c536&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"5a63c536\",\n null\n \n)\n\nexport default component.exports","\n### Simple screen\n\n```vue\n\n \n Hello World.\n \n\n```\n\n### Show progress\n\n```vue\n\n \n Hello World.\n \n \n\n```\n\n### Multiple slides\nOne screen may consist of multiple slides that are numbered incrementally and displayed one after another.\nYou can go to the next slide with the `nextSlide` function that is exposed by the Screen component.\n\n```vue\n\n \n\n \n Hello .\n \n\n \n Hello you.\n \n\n \n\n```\n\n### Store measurements\nThe screen component also conveniently exposes an object for you to store in the measurements of the current screen, so you can later save them.\n\n```vue\n\n \n \n Hello\n \n {{ $magpie.measurements.text }}?\n \n \n \n\n \n\n\n```\n\n### Validate measurements\nThe screen can also be used to validate observations.\n\n```vue\n\n \n\n \n Hello\n \n\n {{ $magpie.measurements.text }}?\n\n \n\n

At least 4 characters required and only alphabetic characters, please.

\n\n
\n\n
\n\n \n
\n```\n\n### Jump using labels\n\n```vue\n\n \n Hello {{i}}th World.\n \n \n \n \n World's End.\n \n \n\n```\n\n
\n\n\n\n\n","import mod from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./Screen.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./Screen.vue?vue&type=script&lang=js&\"","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',[_vm._t(\"default\")],2)\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n\n","import mod from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./Slide.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../cache-loader/dist/cjs.js??ref--1-0!../../../vue-loader/lib/index.js??vue-loader-options!./Slide.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./Slide.vue?vue&type=template&id=5720c65a&\"\nimport script from \"./Slide.vue?vue&type=script&lang=js&\"\nexport * from \"./Slide.vue?vue&type=script&lang=js&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n null,\n null\n \n)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"completion\"},[_c('div',{staticClass:\"question\"},_vm._l((_vm.slices),function(slice,i){return _c('span',{key:i},[_vm._v(_vm._s(slice)+\" \"),(i !== _vm.slices.length - 1)?_c('select',{directives:[{name:\"model\",rawName:\"v-model\",value:(_vm.answers[i]),expression:\"answers[i]\"}],on:{\"change\":[function($event){var $$selectedVal = Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = \"_value\" in o ? o._value : o.value;return val}); _vm.$set(_vm.answers, i, $event.target.multiple ? $$selectedVal : $$selectedVal[0])},function($event){/**\n * Change event with the fully completed text. Useful for response.sync\n */\n _vm.$emit('update:response', _vm.fullAnswer);\n /**\n * Change event as an array of completions. Useful for responses.sync\n */\n _vm.$emit('update:responses', _vm.answers);}]}},_vm._l((_vm.options[i]),function(option){return _c('option',{key:option,domProps:{\"textContent\":_vm._s(option)}})}),0):_vm._e()])}),0)])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n```vue\n\n \n\n \n \n

A {{$magpie.measurements.words[0]}} would never fall over {{$magpie.measurements.words[1]}}

\n \n
\n\n
\n\n
\n```\n
\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./CompletionInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./CompletionInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./CompletionInput.vue?vue&type=template&id=20ec9a19&scoped=true&\"\nimport script from \"./CompletionInput.vue?vue&type=script&lang=js&\"\nexport * from \"./CompletionInput.vue?vue&type=script&lang=js&\"\nimport style0 from \"./CompletionInput.vue?vue&type=style&index=0&id=20ec9a19&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"20ec9a19\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./CompletionInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"dropdown-input\"},[_c('select',{ref:\"input\",on:{\"change\":function($event){return _vm.$emit('update:response', _vm.$refs.input.value)}}},_vm._l((_vm.options),function(option){return _c('option',{key:option,domProps:{\"value\":option,\"textContent\":_vm._s(option)}})}),0)])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n```vue\n\n \n\n \n

Fries or soup?

\n \n

I disagree!

\n \n
\n\n
\n\n \n\n
\n```\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./DropdownInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./DropdownInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./DropdownInput.vue?vue&type=template&id=6fb3df0e&scoped=true&\"\nimport script from \"./DropdownInput.vue?vue&type=script&lang=js&\"\nexport * from \"./DropdownInput.vue?vue&type=script&lang=js&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"6fb3df0e\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./DropdownInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"forced_choice\"},[_c('div',{staticClass:\"options\"},_vm._l((_vm.options),function(option){return _c('div',{key:option,staticClass:\"option\",on:{\"click\":function($event){return _vm.onOptionClick(option)}}},[_vm._v(\" \"+_vm._s(option)+\" \")])}),0)])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n```vue\n\n \n\n \n

What's on the bread?

\n \n

A sweet tooth, eh!?

\n \n
\n\n
\n\n
\n```\n\nThe following example will submit the response directly on clicking it.\n\n```vue\n\n \n\n \n

What's on the bread?

\n \n
\n\n
\n
\n```\n\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./ForcedChoiceInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./ForcedChoiceInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./ForcedChoiceInput.vue?vue&type=template&id=0428af94&scoped=true&\"\nimport script from \"./ForcedChoiceInput.vue?vue&type=script&lang=js&\"\nexport * from \"./ForcedChoiceInput.vue?vue&type=script&lang=js&\"\nimport style0 from \"./ForcedChoiceInput.vue?vue&type=style&index=0&id=0428af94&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"0428af94\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./ForcedChoiceInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"image_selection\"},[_c('div',{staticClass:\"options\"},_vm._l((_vm.options),function(option){return _c('div',{key:option.label,staticClass:\"option\",on:{\"click\":function($event){return _vm.onOptionClick(option.label)}}},[_c('img',{attrs:{\"src\":option.src,\"alt\":option.label},on:{\"click\":function($event){return _vm.onOptionClick(option.label)}}})])}),0)])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n```vue\n\n \n\n \n

Fries or soup?

\n \n
\n\n
\n
\n```\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./ImageSelectionInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./ImageSelectionInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./ImageSelectionInput.vue?vue&type=template&id=36baf217&scoped=true&\"\nimport script from \"./ImageSelectionInput.vue?vue&type=script&lang=js&\"\nexport * from \"./ImageSelectionInput.vue?vue&type=script&lang=js&\"\nimport style0 from \"./ImageSelectionInput.vue?vue&type=style&index=0&id=36baf217&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"36baf217\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./ImageSelectionInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"keypress\"},[(_vm.showOptions)?_c('div',{staticClass:\"options\"},_vm._l((_vm.keys),function(option,key){return _c('span',{key:key},[_c('strong',{domProps:{\"textContent\":_vm._s(key)}}),_vm._v(\" = \"+_vm._s(option)+\" \")])}),0):_vm._e()])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n```vue\n\n \n\n \n

Fries or soup?

\n \n
\n\n
\n
\n```\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./KeypressInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./KeypressInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./KeypressInput.vue?vue&type=template&id=6de4318b&scoped=true&\"\nimport script from \"./KeypressInput.vue?vue&type=script&lang=js&\"\nexport * from \"./KeypressInput.vue?vue&type=script&lang=js&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"6de4318b\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./KeypressInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"rating\"},[_c('form',[_c('div',{staticClass:\"options\"},[_c('div',{staticClass:\"left\"},[_vm._v(_vm._s(_vm.left))]),_vm._l((_vm.count),function(i){return _c('label',{key:i},[_c('input',{directives:[{name:\"model\",rawName:\"v-model\",value:(_vm.answers[i]),expression:\"answers[i]\"}],attrs:{\"type\":\"radio\",\"name\":\"rating\"},domProps:{\"checked\":_vm._q(_vm.answers[i],null)},on:{\"input\":function($event){return _vm.$emit('update:response', i)},\"change\":function($event){return _vm.$set(_vm.answers, i, null)}}}),_vm._v(\" \"+_vm._s(i))])}),_c('div',{staticClass:\"right\"},[_vm._v(_vm._s(_vm.right))])],2)])])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n```vue\n\n \n\n \n

Fries or soup?

\n \n

4\">I concur!

\n \n
\n\n
\n\n
\n```\n\n```vue\n\n \n

Fries or soup?

\n \n
\n\n
\n```\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./RatingInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./RatingInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./RatingInput.vue?vue&type=template&id=50f61df4&scoped=true&\"\nimport script from \"./RatingInput.vue?vue&type=script&lang=js&\"\nexport * from \"./RatingInput.vue?vue&type=script&lang=js&\"\nimport style0 from \"./RatingInput.vue?vue&type=style&index=0&id=50f61df4&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"50f61df4\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./RatingInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"slider\"},[_c('div',{staticClass:\"slider-element\"},[_c('div',{staticClass:\"left\"},[_vm._v(_vm._s(_vm.left))]),_c('Slider',{staticClass:\"slider\",attrs:{\"tooltip\":_vm.tooltip ? 'always' : 'none',\"min\":_vm.min,\"max\":_vm.max,\"interval\":_vm.interval,\"disabled\":_vm.disabled},model:{value:(_vm.value),callback:function ($$v) {_vm.value=$$v},expression:\"value\"}}),_c('div',{staticClass:\"right\"},[_vm._v(_vm._s(_vm.right))])],1)])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n```vue\n\n \n\n \n

Fries or soup?

\n \n Lunch: {{$magpie.measurements.lunch}}% Soup\n \n
\n\n
\n\n
\n```\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./SliderInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./SliderInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./SliderInput.vue?vue&type=template&id=6c73a9d4&scoped=true&\"\nimport script from \"./SliderInput.vue?vue&type=script&lang=js&\"\nexport * from \"./SliderInput.vue?vue&type=script&lang=js&\"\nimport style0 from \"./SliderInput.vue?vue&type=style&index=0&id=6c73a9d4&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"6c73a9d4\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./SliderInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{staticClass:\"textarea\"},[_c('textarea',{ref:\"text\",on:{\"input\":function($event){return _vm.$emit('update:response', _vm.$refs.text.value)}}})])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n```vue\n\n \n\n \n

Fries or soup? Discuss.

\n \n

32\">I disagree!

\n \n
\n\n
\n
\n```\n
\n\n\n\n\n\n\n","import mod from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./TextareaInput.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../../../cache-loader/dist/cjs.js??ref--1-0!../../../../vue-loader/lib/index.js??vue-loader-options!./TextareaInput.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./TextareaInput.vue?vue&type=template&id=7a50d03b&scoped=true&\"\nimport script from \"./TextareaInput.vue?vue&type=script&lang=js&\"\nexport * from \"./TextareaInput.vue?vue&type=script&lang=js&\"\nimport style0 from \"./TextareaInput.vue?vue&type=style&index=0&id=7a50d03b&prod&scoped=true&lang=css&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../../vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"7a50d03b\",\n null\n \n)\n\n/* custom blocks */\nimport block0 from \"./TextareaInput.vue?vue&type=custom&index=0&blockType=docs\"\nif (typeof block0 === 'function') block0(component)\n\nexport default component.exports","var render = function render(){var _vm=this,_c=_vm._self._c;return _c('div',{class:['multiple-choice', _vm.orientation]},[_c('form',[_c('div',{staticClass:\"options\"},_vm._l((_vm.order),function(i){return _c('label',{key:i},[_c('input',{attrs:{\"type\":\"radio\",\"name\":\"options\"},domProps:{\"value\":_vm.options[i]},on:{\"input\":function($event){return _vm.$emit('update:response', _vm.options[i])}}}),(_vm.labels)?[(!_vm.optionsHtml.length)?_c('span',[_vm._v(_vm._s(_vm.options[i]))]):_c('span',{domProps:{\"innerHTML\":_vm._s(_vm.optionsHtml[i])}})]:_vm._e()],2)}),0)])])\n}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n```vue\n\n \n\n \n

How was your breakfast?

\n \n \n
\n\n
\n
\n```\n\n\n```vue\n\n \n\n \n

How was your breakfast?

\n \n \n
\n\n
\n
\n```\n\n```vue\n\n \n

Which sentence is ungrammatical?

\n banana went out to buy some groceries.',\n 'The bear raced past the barn froze.',\n 'The horse could not have been eaten why it was racing.',\n 'The bread was sour before it was made.'\n ]\">\n \n \n
\n \n
\n```\n\n
\n\n